PackageManagerService.java revision 052366ca4e6138b583d08535bd1837deb7cd58d0
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.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 228import com.android.server.pm.Settings.VersionInfo; 229import com.android.server.storage.DeviceStorageMonitorInternal; 230 231import org.xmlpull.v1.XmlPullParser; 232import org.xmlpull.v1.XmlPullParserException; 233import org.xmlpull.v1.XmlSerializer; 234 235import java.io.BufferedInputStream; 236import java.io.BufferedOutputStream; 237import java.io.BufferedReader; 238import java.io.ByteArrayInputStream; 239import java.io.ByteArrayOutputStream; 240import java.io.File; 241import java.io.FileDescriptor; 242import java.io.FileNotFoundException; 243import java.io.FileOutputStream; 244import java.io.FileReader; 245import java.io.FilenameFilter; 246import java.io.IOException; 247import java.io.InputStream; 248import java.io.PrintWriter; 249import java.nio.charset.StandardCharsets; 250import java.security.NoSuchAlgorithmException; 251import java.security.PublicKey; 252import java.security.cert.CertificateEncodingException; 253import java.security.cert.CertificateException; 254import java.text.SimpleDateFormat; 255import java.util.ArrayList; 256import java.util.Arrays; 257import java.util.Collection; 258import java.util.Collections; 259import java.util.Comparator; 260import java.util.Date; 261import java.util.Iterator; 262import java.util.List; 263import java.util.Map; 264import java.util.Objects; 265import java.util.Set; 266import java.util.concurrent.CountDownLatch; 267import java.util.concurrent.TimeUnit; 268import java.util.concurrent.atomic.AtomicBoolean; 269import java.util.concurrent.atomic.AtomicInteger; 270import java.util.concurrent.atomic.AtomicLong; 271 272/** 273 * Keep track of all those .apks everywhere. 274 * 275 * This is very central to the platform's security; please run the unit 276 * tests whenever making modifications here: 277 * 278mmm frameworks/base/tests/AndroidTests 279adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 280adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 // If this is the only one pending we might 1150 // have to bind to the service again. 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 params.serviceError(); 1154 return; 1155 } else { 1156 // Once we bind to the service, the first 1157 // pending request will be processed. 1158 mPendingInstalls.add(idx, params); 1159 } 1160 } else { 1161 mPendingInstalls.add(idx, params); 1162 // Already bound to the service. Just make 1163 // sure we trigger off processing the first request. 1164 if (idx == 0) { 1165 mHandler.sendEmptyMessage(MCS_BOUND); 1166 } 1167 } 1168 break; 1169 } 1170 case MCS_BOUND: { 1171 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1172 if (msg.obj != null) { 1173 mContainerService = (IMediaContainerService) msg.obj; 1174 } 1175 if (mContainerService == null) { 1176 if (!mBound) { 1177 // Something seriously wrong since we are not bound and we are not 1178 // waiting for connection. Bail out. 1179 Slog.e(TAG, "Cannot bind to media container service"); 1180 for (HandlerParams params : mPendingInstalls) { 1181 // Indicate service bind error 1182 params.serviceError(); 1183 } 1184 mPendingInstalls.clear(); 1185 } else { 1186 Slog.w(TAG, "Waiting to connect to media container service"); 1187 } 1188 } else if (mPendingInstalls.size() > 0) { 1189 HandlerParams params = mPendingInstalls.get(0); 1190 if (params != null) { 1191 if (params.startCopy()) { 1192 // We are done... look for more work or to 1193 // go idle. 1194 if (DEBUG_SD_INSTALL) Log.i(TAG, 1195 "Checking for more work or unbind..."); 1196 // Delete pending install 1197 if (mPendingInstalls.size() > 0) { 1198 mPendingInstalls.remove(0); 1199 } 1200 if (mPendingInstalls.size() == 0) { 1201 if (mBound) { 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Posting delayed MCS_UNBIND"); 1204 removeMessages(MCS_UNBIND); 1205 Message ubmsg = obtainMessage(MCS_UNBIND); 1206 // Unbind after a little delay, to avoid 1207 // continual thrashing. 1208 sendMessageDelayed(ubmsg, 10000); 1209 } 1210 } else { 1211 // There are more pending requests in queue. 1212 // Just post MCS_BOUND message to trigger processing 1213 // of next pending install. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Posting MCS_BOUND for next work"); 1216 mHandler.sendEmptyMessage(MCS_BOUND); 1217 } 1218 } 1219 } 1220 } else { 1221 // Should never happen ideally. 1222 Slog.w(TAG, "Empty queue"); 1223 } 1224 break; 1225 } 1226 case MCS_RECONNECT: { 1227 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1228 if (mPendingInstalls.size() > 0) { 1229 if (mBound) { 1230 disconnectService(); 1231 } 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 for (HandlerParams params : mPendingInstalls) { 1235 // Indicate service bind error 1236 params.serviceError(); 1237 } 1238 mPendingInstalls.clear(); 1239 } 1240 } 1241 break; 1242 } 1243 case MCS_UNBIND: { 1244 // If there is no actual work left, then time to unbind. 1245 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1246 1247 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1248 if (mBound) { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1250 1251 disconnectService(); 1252 } 1253 } else if (mPendingInstalls.size() > 0) { 1254 // There are more pending requests in queue. 1255 // Just post MCS_BOUND message to trigger processing 1256 // of next pending install. 1257 mHandler.sendEmptyMessage(MCS_BOUND); 1258 } 1259 1260 break; 1261 } 1262 case MCS_GIVE_UP: { 1263 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1264 mPendingInstalls.remove(0); 1265 break; 1266 } 1267 case SEND_PENDING_BROADCAST: { 1268 String packages[]; 1269 ArrayList<String> components[]; 1270 int size = 0; 1271 int uids[]; 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1273 synchronized (mPackages) { 1274 if (mPendingBroadcasts == null) { 1275 return; 1276 } 1277 size = mPendingBroadcasts.size(); 1278 if (size <= 0) { 1279 // Nothing to be done. Just return 1280 return; 1281 } 1282 packages = new String[size]; 1283 components = new ArrayList[size]; 1284 uids = new int[size]; 1285 int i = 0; // filling out the above arrays 1286 1287 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1288 int packageUserId = mPendingBroadcasts.userIdAt(n); 1289 Iterator<Map.Entry<String, ArrayList<String>>> it 1290 = mPendingBroadcasts.packagesForUserId(packageUserId) 1291 .entrySet().iterator(); 1292 while (it.hasNext() && i < size) { 1293 Map.Entry<String, ArrayList<String>> ent = it.next(); 1294 packages[i] = ent.getKey(); 1295 components[i] = ent.getValue(); 1296 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1297 uids[i] = (ps != null) 1298 ? UserHandle.getUid(packageUserId, ps.appId) 1299 : -1; 1300 i++; 1301 } 1302 } 1303 size = i; 1304 mPendingBroadcasts.clear(); 1305 } 1306 // Send broadcasts 1307 for (int i = 0; i < size; i++) { 1308 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1309 } 1310 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1311 break; 1312 } 1313 case START_CLEANING_PACKAGE: { 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 final String packageName = (String)msg.obj; 1316 final int userId = msg.arg1; 1317 final boolean andCode = msg.arg2 != 0; 1318 synchronized (mPackages) { 1319 if (userId == UserHandle.USER_ALL) { 1320 int[] users = sUserManager.getUserIds(); 1321 for (int user : users) { 1322 mSettings.addPackageToCleanLPw( 1323 new PackageCleanItem(user, packageName, andCode)); 1324 } 1325 } else { 1326 mSettings.addPackageToCleanLPw( 1327 new PackageCleanItem(userId, packageName, andCode)); 1328 } 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 startCleaningPackages(); 1332 } break; 1333 case POST_INSTALL: { 1334 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1335 PostInstallData data = mRunningInstalls.get(msg.arg1); 1336 mRunningInstalls.delete(msg.arg1); 1337 boolean deleteOld = false; 1338 1339 if (data != null) { 1340 InstallArgs args = data.args; 1341 PackageInstalledInfo res = data.res; 1342 1343 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1344 final String packageName = res.pkg.applicationInfo.packageName; 1345 res.removedInfo.sendBroadcast(false, true, false); 1346 Bundle extras = new Bundle(1); 1347 extras.putInt(Intent.EXTRA_UID, res.uid); 1348 1349 // Now that we successfully installed the package, grant runtime 1350 // permissions if requested before broadcasting the install. 1351 if ((args.installFlags 1352 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1353 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1354 args.installGrantPermissions); 1355 } 1356 1357 // Determine the set of users who are adding this 1358 // package for the first time vs. those who are seeing 1359 // an update. 1360 int[] firstUsers; 1361 int[] updateUsers = new int[0]; 1362 if (res.origUsers == null || res.origUsers.length == 0) { 1363 firstUsers = res.newUsers; 1364 } else { 1365 firstUsers = new int[0]; 1366 for (int i=0; i<res.newUsers.length; i++) { 1367 int user = res.newUsers[i]; 1368 boolean isNew = true; 1369 for (int j=0; j<res.origUsers.length; j++) { 1370 if (res.origUsers[j] == user) { 1371 isNew = false; 1372 break; 1373 } 1374 } 1375 if (isNew) { 1376 int[] newFirst = new int[firstUsers.length+1]; 1377 System.arraycopy(firstUsers, 0, newFirst, 0, 1378 firstUsers.length); 1379 newFirst[firstUsers.length] = user; 1380 firstUsers = newFirst; 1381 } else { 1382 int[] newUpdate = new int[updateUsers.length+1]; 1383 System.arraycopy(updateUsers, 0, newUpdate, 0, 1384 updateUsers.length); 1385 newUpdate[updateUsers.length] = user; 1386 updateUsers = newUpdate; 1387 } 1388 } 1389 } 1390 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1391 packageName, extras, null, null, firstUsers); 1392 final boolean update = res.removedInfo.removedPackage != null; 1393 if (update) { 1394 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1395 } 1396 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1397 packageName, extras, null, null, updateUsers); 1398 if (update) { 1399 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1400 packageName, extras, null, null, updateUsers); 1401 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1402 null, null, packageName, null, updateUsers); 1403 1404 // treat asec-hosted packages like removable media on upgrade 1405 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1406 if (DEBUG_INSTALL) { 1407 Slog.i(TAG, "upgrading pkg " + res.pkg 1408 + " is ASEC-hosted -> AVAILABLE"); 1409 } 1410 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1411 ArrayList<String> pkgList = new ArrayList<String>(1); 1412 pkgList.add(packageName); 1413 sendResourcesChangedBroadcast(true, true, 1414 pkgList,uidArray, null); 1415 } 1416 } 1417 if (res.removedInfo.args != null) { 1418 // Remove the replaced package's older resources safely now 1419 deleteOld = true; 1420 } 1421 1422 // If this app is a browser and it's newly-installed for some 1423 // users, clear any default-browser state in those users 1424 if (firstUsers.length > 0) { 1425 // the app's nature doesn't depend on the user, so we can just 1426 // check its browser nature in any user and generalize. 1427 if (packageIsBrowser(packageName, firstUsers[0])) { 1428 synchronized (mPackages) { 1429 for (int userId : firstUsers) { 1430 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1431 } 1432 } 1433 } 1434 } 1435 // Log current value of "unknown sources" setting 1436 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1437 getUnknownSourcesSettings()); 1438 } 1439 // Force a gc to clear up things 1440 Runtime.getRuntime().gc(); 1441 // We delete after a gc for applications on sdcard. 1442 if (deleteOld) { 1443 synchronized (mInstallLock) { 1444 res.removedInfo.args.doPostDeleteLI(true); 1445 } 1446 } 1447 if (args.observer != null) { 1448 try { 1449 Bundle extras = extrasForInstallResult(res); 1450 args.observer.onPackageInstalled(res.name, res.returnCode, 1451 res.returnMsg, extras); 1452 } catch (RemoteException e) { 1453 Slog.i(TAG, "Observer no longer exists."); 1454 } 1455 } 1456 } else { 1457 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1458 } 1459 } break; 1460 case UPDATED_MEDIA_STATUS: { 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1462 boolean reportStatus = msg.arg1 == 1; 1463 boolean doGc = msg.arg2 == 1; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1465 if (doGc) { 1466 // Force a gc to clear up stale containers. 1467 Runtime.getRuntime().gc(); 1468 } 1469 if (msg.obj != null) { 1470 @SuppressWarnings("unchecked") 1471 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1473 // Unload containers 1474 unloadAllContainers(args); 1475 } 1476 if (reportStatus) { 1477 try { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1479 PackageHelper.getMountService().finishMediaUpdate(); 1480 } catch (RemoteException e) { 1481 Log.e(TAG, "MountService not running?"); 1482 } 1483 } 1484 } break; 1485 case WRITE_SETTINGS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_SETTINGS); 1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1490 mSettings.writeLPr(); 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case WRITE_PACKAGE_RESTRICTIONS: { 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1497 synchronized (mPackages) { 1498 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1499 for (int userId : mDirtyUsers) { 1500 mSettings.writePackageRestrictionsLPr(userId); 1501 } 1502 mDirtyUsers.clear(); 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 } break; 1506 case CHECK_PENDING_VERIFICATION: { 1507 final int verificationId = msg.arg1; 1508 final PackageVerificationState state = mPendingVerification.get(verificationId); 1509 1510 if ((state != null) && !state.timeoutExtended()) { 1511 final InstallArgs args = state.getInstallArgs(); 1512 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1513 1514 Slog.i(TAG, "Verification timed out for " + originUri); 1515 mPendingVerification.remove(verificationId); 1516 1517 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1518 1519 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1520 Slog.i(TAG, "Continuing with installation of " + originUri); 1521 state.setVerifierResponse(Binder.getCallingUid(), 1522 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1523 broadcastPackageVerified(verificationId, originUri, 1524 PackageManager.VERIFICATION_ALLOW, 1525 state.getInstallArgs().getUser()); 1526 try { 1527 ret = args.copyApk(mContainerService, true); 1528 } catch (RemoteException e) { 1529 Slog.e(TAG, "Could not contact the ContainerService"); 1530 } 1531 } else { 1532 broadcastPackageVerified(verificationId, originUri, 1533 PackageManager.VERIFICATION_REJECT, 1534 state.getInstallArgs().getUser()); 1535 } 1536 1537 processPendingInstall(args, ret); 1538 mHandler.sendEmptyMessage(MCS_UNBIND); 1539 } 1540 break; 1541 } 1542 case PACKAGE_VERIFIED: { 1543 final int verificationId = msg.arg1; 1544 1545 final PackageVerificationState state = mPendingVerification.get(verificationId); 1546 if (state == null) { 1547 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1548 break; 1549 } 1550 1551 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1552 1553 state.setVerifierResponse(response.callerUid, response.code); 1554 1555 if (state.isVerificationComplete()) { 1556 mPendingVerification.remove(verificationId); 1557 1558 final InstallArgs args = state.getInstallArgs(); 1559 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1560 1561 int ret; 1562 if (state.isInstallAllowed()) { 1563 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1564 broadcastPackageVerified(verificationId, originUri, 1565 response.code, state.getInstallArgs().getUser()); 1566 try { 1567 ret = args.copyApk(mContainerService, true); 1568 } catch (RemoteException e) { 1569 Slog.e(TAG, "Could not contact the ContainerService"); 1570 } 1571 } else { 1572 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1573 } 1574 1575 processPendingInstall(args, ret); 1576 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 1580 break; 1581 } 1582 case START_INTENT_FILTER_VERIFICATIONS: { 1583 IFVerificationParams params = (IFVerificationParams) msg.obj; 1584 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1585 params.replacing, params.pkg); 1586 break; 1587 } 1588 case INTENT_FILTER_VERIFIED: { 1589 final int verificationId = msg.arg1; 1590 1591 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1592 verificationId); 1593 if (state == null) { 1594 Slog.w(TAG, "Invalid IntentFilter verification token " 1595 + verificationId + " received"); 1596 break; 1597 } 1598 1599 final int userId = state.getUserId(); 1600 1601 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1602 "Processing IntentFilter verification with token:" 1603 + verificationId + " and userId:" + userId); 1604 1605 final IntentFilterVerificationResponse response = 1606 (IntentFilterVerificationResponse) msg.obj; 1607 1608 state.setVerifierResponse(response.callerUid, response.code); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "IntentFilter verification with token:" + verificationId 1612 + " and userId:" + userId 1613 + " is settings verifier response with response code:" 1614 + response.code); 1615 1616 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1617 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1618 + response.getFailedDomainsString()); 1619 } 1620 1621 if (state.isVerificationComplete()) { 1622 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1623 } else { 1624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1625 "IntentFilter verification with token:" + verificationId 1626 + " was not said to be complete"); 1627 } 1628 1629 break; 1630 } 1631 } 1632 } 1633 } 1634 1635 private StorageEventListener mStorageListener = new StorageEventListener() { 1636 @Override 1637 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1638 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1639 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1640 final String volumeUuid = vol.getFsUuid(); 1641 1642 // Clean up any users or apps that were removed or recreated 1643 // while this volume was missing 1644 reconcileUsers(volumeUuid); 1645 reconcileApps(volumeUuid); 1646 1647 // Clean up any install sessions that expired or were 1648 // cancelled while this volume was missing 1649 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1650 1651 loadPrivatePackages(vol); 1652 1653 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1654 unloadPrivatePackages(vol); 1655 } 1656 } 1657 1658 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1659 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1660 updateExternalMediaStatus(true, false); 1661 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1662 updateExternalMediaStatus(false, false); 1663 } 1664 } 1665 } 1666 1667 @Override 1668 public void onVolumeForgotten(String fsUuid) { 1669 if (TextUtils.isEmpty(fsUuid)) { 1670 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1671 return; 1672 } 1673 1674 // Remove any apps installed on the forgotten volume 1675 synchronized (mPackages) { 1676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1677 for (PackageSetting ps : packages) { 1678 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1679 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1680 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1681 } 1682 1683 mSettings.onVolumeForgotten(fsUuid); 1684 mSettings.writeLPr(); 1685 } 1686 } 1687 }; 1688 1689 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1690 String[] grantedPermissions) { 1691 if (userId >= UserHandle.USER_OWNER) { 1692 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1693 } else if (userId == UserHandle.USER_ALL) { 1694 final int[] userIds; 1695 synchronized (mPackages) { 1696 userIds = UserManagerService.getInstance().getUserIds(); 1697 } 1698 for (int someUserId : userIds) { 1699 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1700 } 1701 } 1702 1703 // We could have touched GID membership, so flush out packages.list 1704 synchronized (mPackages) { 1705 mSettings.writePackageListLPr(); 1706 } 1707 } 1708 1709 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1710 String[] grantedPermissions) { 1711 SettingBase sb = (SettingBase) pkg.mExtras; 1712 if (sb == null) { 1713 return; 1714 } 1715 1716 PermissionsState permissionsState = sb.getPermissionsState(); 1717 1718 for (String permission : pkg.requestedPermissions) { 1719 BasePermission bp = mSettings.mPermissions.get(permission); 1720 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1721 || ArrayUtils.contains(grantedPermissions, permission))) { 1722 permissionsState.grantRuntimePermission(bp, userId); 1723 } 1724 } 1725 } 1726 1727 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1728 Bundle extras = null; 1729 switch (res.returnCode) { 1730 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1731 extras = new Bundle(); 1732 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1733 res.origPermission); 1734 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1735 res.origPackage); 1736 break; 1737 } 1738 case PackageManager.INSTALL_SUCCEEDED: { 1739 extras = new Bundle(); 1740 extras.putBoolean(Intent.EXTRA_REPLACING, 1741 res.removedInfo != null && res.removedInfo.removedPackage != null); 1742 break; 1743 } 1744 } 1745 return extras; 1746 } 1747 1748 void scheduleWriteSettingsLocked() { 1749 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1750 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1751 } 1752 } 1753 1754 void scheduleWritePackageRestrictionsLocked(int userId) { 1755 if (!sUserManager.exists(userId)) return; 1756 mDirtyUsers.add(userId); 1757 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1758 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1759 } 1760 } 1761 1762 public static PackageManagerService main(Context context, Installer installer, 1763 boolean factoryTest, boolean onlyCore) { 1764 PackageManagerService m = new PackageManagerService(context, installer, 1765 factoryTest, onlyCore); 1766 ServiceManager.addService("package", m); 1767 return m; 1768 } 1769 1770 static String[] splitString(String str, char sep) { 1771 int count = 1; 1772 int i = 0; 1773 while ((i=str.indexOf(sep, i)) >= 0) { 1774 count++; 1775 i++; 1776 } 1777 1778 String[] res = new String[count]; 1779 i=0; 1780 count = 0; 1781 int lastI=0; 1782 while ((i=str.indexOf(sep, i)) >= 0) { 1783 res[count] = str.substring(lastI, i); 1784 count++; 1785 i++; 1786 lastI = i; 1787 } 1788 res[count] = str.substring(lastI, str.length()); 1789 return res; 1790 } 1791 1792 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1793 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1794 Context.DISPLAY_SERVICE); 1795 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1796 } 1797 1798 public PackageManagerService(Context context, Installer installer, 1799 boolean factoryTest, boolean onlyCore) { 1800 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1801 SystemClock.uptimeMillis()); 1802 1803 if (mSdkVersion <= 0) { 1804 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1805 } 1806 1807 mContext = context; 1808 mFactoryTest = factoryTest; 1809 mOnlyCore = onlyCore; 1810 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1811 mMetrics = new DisplayMetrics(); 1812 mSettings = new Settings(mPackages); 1813 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1814 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1815 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1816 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1817 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1818 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1819 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1820 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1821 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1822 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1823 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1824 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1825 1826 // TODO: add a property to control this? 1827 long dexOptLRUThresholdInMinutes; 1828 if (mLazyDexOpt) { 1829 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1830 } else { 1831 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1832 } 1833 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1834 1835 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1836 if (separateProcesses != null && separateProcesses.length() > 0) { 1837 if ("*".equals(separateProcesses)) { 1838 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1839 mSeparateProcesses = null; 1840 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1841 } else { 1842 mDefParseFlags = 0; 1843 mSeparateProcesses = separateProcesses.split(","); 1844 Slog.w(TAG, "Running with debug.separate_processes: " 1845 + separateProcesses); 1846 } 1847 } else { 1848 mDefParseFlags = 0; 1849 mSeparateProcesses = null; 1850 } 1851 1852 mInstaller = installer; 1853 mPackageDexOptimizer = new PackageDexOptimizer(this); 1854 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1855 1856 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1857 FgThread.get().getLooper()); 1858 1859 getDefaultDisplayMetrics(context, mMetrics); 1860 1861 SystemConfig systemConfig = SystemConfig.getInstance(); 1862 mGlobalGids = systemConfig.getGlobalGids(); 1863 mSystemPermissions = systemConfig.getSystemPermissions(); 1864 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1865 1866 synchronized (mInstallLock) { 1867 // writer 1868 synchronized (mPackages) { 1869 mHandlerThread = new ServiceThread(TAG, 1870 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1871 mHandlerThread.start(); 1872 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1873 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1874 1875 File dataDir = Environment.getDataDirectory(); 1876 mAppDataDir = new File(dataDir, "data"); 1877 mAppInstallDir = new File(dataDir, "app"); 1878 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1879 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1880 mUserAppDataDir = new File(dataDir, "user"); 1881 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1882 1883 sUserManager = new UserManagerService(context, this, 1884 mInstallLock, mPackages); 1885 1886 // Propagate permission configuration in to package manager. 1887 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1888 = systemConfig.getPermissions(); 1889 for (int i=0; i<permConfig.size(); i++) { 1890 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1891 BasePermission bp = mSettings.mPermissions.get(perm.name); 1892 if (bp == null) { 1893 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1894 mSettings.mPermissions.put(perm.name, bp); 1895 } 1896 if (perm.gids != null) { 1897 bp.setGids(perm.gids, perm.perUser); 1898 } 1899 } 1900 1901 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1902 for (int i=0; i<libConfig.size(); i++) { 1903 mSharedLibraries.put(libConfig.keyAt(i), 1904 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1905 } 1906 1907 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1908 1909 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1910 mSdkVersion, mOnlyCore); 1911 1912 String customResolverActivity = Resources.getSystem().getString( 1913 R.string.config_customResolverActivity); 1914 if (TextUtils.isEmpty(customResolverActivity)) { 1915 customResolverActivity = null; 1916 } else { 1917 mCustomResolverComponentName = ComponentName.unflattenFromString( 1918 customResolverActivity); 1919 } 1920 1921 long startTime = SystemClock.uptimeMillis(); 1922 1923 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1924 startTime); 1925 1926 // Set flag to monitor and not change apk file paths when 1927 // scanning install directories. 1928 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1929 1930 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1931 1932 /** 1933 * Add everything in the in the boot class path to the 1934 * list of process files because dexopt will have been run 1935 * if necessary during zygote startup. 1936 */ 1937 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1938 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1939 1940 if (bootClassPath != null) { 1941 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1942 for (String element : bootClassPathElements) { 1943 alreadyDexOpted.add(element); 1944 } 1945 } else { 1946 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1947 } 1948 1949 if (systemServerClassPath != null) { 1950 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1951 for (String element : systemServerClassPathElements) { 1952 alreadyDexOpted.add(element); 1953 } 1954 } else { 1955 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1956 } 1957 1958 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1959 final String[] dexCodeInstructionSets = 1960 getDexCodeInstructionSets( 1961 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1962 1963 /** 1964 * Ensure all external libraries have had dexopt run on them. 1965 */ 1966 if (mSharedLibraries.size() > 0) { 1967 // NOTE: For now, we're compiling these system "shared libraries" 1968 // (and framework jars) into all available architectures. It's possible 1969 // to compile them only when we come across an app that uses them (there's 1970 // already logic for that in scanPackageLI) but that adds some complexity. 1971 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1972 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1973 final String lib = libEntry.path; 1974 if (lib == null) { 1975 continue; 1976 } 1977 1978 try { 1979 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1980 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1981 alreadyDexOpted.add(lib); 1982 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false); 1983 } 1984 } catch (FileNotFoundException e) { 1985 Slog.w(TAG, "Library not found: " + lib); 1986 } catch (IOException e) { 1987 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1988 + e.getMessage()); 1989 } 1990 } 1991 } 1992 } 1993 1994 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1995 1996 // Gross hack for now: we know this file doesn't contain any 1997 // code, so don't dexopt it to avoid the resulting log spew. 1998 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1999 2000 // Gross hack for now: we know this file is only part of 2001 // the boot class path for art, so don't dexopt it to 2002 // avoid the resulting log spew. 2003 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2004 2005 /** 2006 * There are a number of commands implemented in Java, which 2007 * we currently need to do the dexopt on so that they can be 2008 * run from a non-root shell. 2009 */ 2010 String[] frameworkFiles = frameworkDir.list(); 2011 if (frameworkFiles != null) { 2012 // TODO: We could compile these only for the most preferred ABI. We should 2013 // first double check that the dex files for these commands are not referenced 2014 // by other system apps. 2015 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2016 for (int i=0; i<frameworkFiles.length; i++) { 2017 File libPath = new File(frameworkDir, frameworkFiles[i]); 2018 String path = libPath.getPath(); 2019 // Skip the file if we already did it. 2020 if (alreadyDexOpted.contains(path)) { 2021 continue; 2022 } 2023 // Skip the file if it is not a type we want to dexopt. 2024 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2025 continue; 2026 } 2027 try { 2028 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2029 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2030 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false); 2031 } 2032 } catch (FileNotFoundException e) { 2033 Slog.w(TAG, "Jar not found: " + path); 2034 } catch (IOException e) { 2035 Slog.w(TAG, "Exception reading jar: " + path, e); 2036 } 2037 } 2038 } 2039 } 2040 2041 final VersionInfo ver = mSettings.getInternalVersion(); 2042 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2043 // when upgrading from pre-M, promote system app permissions from install to runtime 2044 mPromoteSystemApps = 2045 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2046 2047 // save off the names of pre-existing system packages prior to scanning; we don't 2048 // want to automatically grant runtime permissions for new system apps 2049 if (mPromoteSystemApps) { 2050 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2051 while (pkgSettingIter.hasNext()) { 2052 PackageSetting ps = pkgSettingIter.next(); 2053 if (isSystemApp(ps)) { 2054 mExistingSystemPackages.add(ps.name); 2055 } 2056 } 2057 } 2058 2059 // Collect vendor overlay packages. 2060 // (Do this before scanning any apps.) 2061 // For security and version matching reason, only consider 2062 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2063 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2064 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2065 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2066 2067 // Find base frameworks (resource packages without code). 2068 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR 2070 | PackageParser.PARSE_IS_PRIVILEGED, 2071 scanFlags | SCAN_NO_DEX, 0); 2072 2073 // Collected privileged system packages. 2074 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2075 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR 2077 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2078 2079 // Collect ordinary system packages. 2080 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2081 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2083 2084 // Collect all vendor packages. 2085 File vendorAppDir = new File("/vendor/app"); 2086 try { 2087 vendorAppDir = vendorAppDir.getCanonicalFile(); 2088 } catch (IOException e) { 2089 // failed to look up canonical path, continue with original one 2090 } 2091 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2093 2094 // Collect all OEM packages. 2095 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2096 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2097 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2098 2099 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2100 mInstaller.moveFiles(); 2101 2102 // Prune any system packages that no longer exist. 2103 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2104 if (!mOnlyCore) { 2105 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2106 while (psit.hasNext()) { 2107 PackageSetting ps = psit.next(); 2108 2109 /* 2110 * If this is not a system app, it can't be a 2111 * disable system app. 2112 */ 2113 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2114 continue; 2115 } 2116 2117 /* 2118 * If the package is scanned, it's not erased. 2119 */ 2120 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2121 if (scannedPkg != null) { 2122 /* 2123 * If the system app is both scanned and in the 2124 * disabled packages list, then it must have been 2125 * added via OTA. Remove it from the currently 2126 * scanned package so the previously user-installed 2127 * application can be scanned. 2128 */ 2129 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2130 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2131 + ps.name + "; removing system app. Last known codePath=" 2132 + ps.codePathString + ", installStatus=" + ps.installStatus 2133 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2134 + scannedPkg.mVersionCode); 2135 removePackageLI(ps, true); 2136 mExpectingBetter.put(ps.name, ps.codePath); 2137 } 2138 2139 continue; 2140 } 2141 2142 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2143 psit.remove(); 2144 logCriticalInfo(Log.WARN, "System package " + ps.name 2145 + " no longer exists; wiping its data"); 2146 removeDataDirsLI(null, ps.name); 2147 } else { 2148 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2149 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2150 possiblyDeletedUpdatedSystemApps.add(ps.name); 2151 } 2152 } 2153 } 2154 } 2155 2156 //look for any incomplete package installations 2157 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2158 //clean up list 2159 for(int i = 0; i < deletePkgsList.size(); i++) { 2160 //clean up here 2161 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2162 } 2163 //delete tmp files 2164 deleteTempPackageFiles(); 2165 2166 // Remove any shared userIDs that have no associated packages 2167 mSettings.pruneSharedUsersLPw(); 2168 2169 if (!mOnlyCore) { 2170 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2171 SystemClock.uptimeMillis()); 2172 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2173 2174 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2175 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2176 2177 /** 2178 * Remove disable package settings for any updated system 2179 * apps that were removed via an OTA. If they're not a 2180 * previously-updated app, remove them completely. 2181 * Otherwise, just revoke their system-level permissions. 2182 */ 2183 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2184 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2185 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2186 2187 String msg; 2188 if (deletedPkg == null) { 2189 msg = "Updated system package " + deletedAppName 2190 + " no longer exists; wiping its data"; 2191 removeDataDirsLI(null, deletedAppName); 2192 } else { 2193 msg = "Updated system app + " + deletedAppName 2194 + " no longer present; removing system privileges for " 2195 + deletedAppName; 2196 2197 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2198 2199 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2200 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2201 } 2202 logCriticalInfo(Log.WARN, msg); 2203 } 2204 2205 /** 2206 * Make sure all system apps that we expected to appear on 2207 * the userdata partition actually showed up. If they never 2208 * appeared, crawl back and revive the system version. 2209 */ 2210 for (int i = 0; i < mExpectingBetter.size(); i++) { 2211 final String packageName = mExpectingBetter.keyAt(i); 2212 if (!mPackages.containsKey(packageName)) { 2213 final File scanFile = mExpectingBetter.valueAt(i); 2214 2215 logCriticalInfo(Log.WARN, "Expected better " + packageName 2216 + " but never showed up; reverting to system"); 2217 2218 final int reparseFlags; 2219 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2220 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2221 | PackageParser.PARSE_IS_SYSTEM_DIR 2222 | PackageParser.PARSE_IS_PRIVILEGED; 2223 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2224 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2225 | PackageParser.PARSE_IS_SYSTEM_DIR; 2226 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2227 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2228 | PackageParser.PARSE_IS_SYSTEM_DIR; 2229 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2230 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR; 2232 } else { 2233 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2234 continue; 2235 } 2236 2237 mSettings.enableSystemPackageLPw(packageName); 2238 2239 try { 2240 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2241 } catch (PackageManagerException e) { 2242 Slog.e(TAG, "Failed to parse original system package: " 2243 + e.getMessage()); 2244 } 2245 } 2246 } 2247 } 2248 mExpectingBetter.clear(); 2249 2250 // Now that we know all of the shared libraries, update all clients to have 2251 // the correct library paths. 2252 updateAllSharedLibrariesLPw(); 2253 2254 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2255 // NOTE: We ignore potential failures here during a system scan (like 2256 // the rest of the commands above) because there's precious little we 2257 // can do about it. A settings error is reported, though. 2258 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2259 false /* force dexopt */, false /* defer dexopt */, 2260 false /* boot complete */); 2261 } 2262 2263 // Now that we know all the packages we are keeping, 2264 // read and update their last usage times. 2265 mPackageUsage.readLP(); 2266 2267 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2268 SystemClock.uptimeMillis()); 2269 Slog.i(TAG, "Time to scan packages: " 2270 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2271 + " seconds"); 2272 2273 // If the platform SDK has changed since the last time we booted, 2274 // we need to re-grant app permission to catch any new ones that 2275 // appear. This is really a hack, and means that apps can in some 2276 // cases get permissions that the user didn't initially explicitly 2277 // allow... it would be nice to have some better way to handle 2278 // this situation. 2279 int updateFlags = UPDATE_PERMISSIONS_ALL; 2280 if (ver.sdkVersion != mSdkVersion) { 2281 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2282 + mSdkVersion + "; regranting permissions for internal storage"); 2283 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2284 } 2285 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2286 ver.sdkVersion = mSdkVersion; 2287 2288 // If this is the first boot or an update from pre-M, and it is a normal 2289 // boot, then we need to initialize the default preferred apps across 2290 // all defined users. 2291 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2292 for (UserInfo user : sUserManager.getUsers(true)) { 2293 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2294 applyFactoryDefaultBrowserLPw(user.id); 2295 primeDomainVerificationsLPw(user.id); 2296 } 2297 } 2298 2299 // If this is first boot after an OTA, and a normal boot, then 2300 // we need to clear code cache directories. 2301 if (mIsUpgrade && !onlyCore) { 2302 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2303 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2304 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2305 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2306 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2307 } 2308 } 2309 ver.fingerprint = Build.FINGERPRINT; 2310 } 2311 2312 checkDefaultBrowser(); 2313 2314 // clear only after permissions and other defaults have been updated 2315 mExistingSystemPackages.clear(); 2316 mPromoteSystemApps = false; 2317 2318 // All the changes are done during package scanning. 2319 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2320 2321 // can downgrade to reader 2322 mSettings.writeLPr(); 2323 2324 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2325 SystemClock.uptimeMillis()); 2326 2327 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2328 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2329 2330 mInstallerService = new PackageInstallerService(context, this); 2331 2332 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2333 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2334 mIntentFilterVerifierComponent); 2335 2336 } // synchronized (mPackages) 2337 } // synchronized (mInstallLock) 2338 2339 // Now after opening every single application zip, make sure they 2340 // are all flushed. Not really needed, but keeps things nice and 2341 // tidy. 2342 Runtime.getRuntime().gc(); 2343 2344 // Expose private service for system components to use. 2345 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2346 } 2347 2348 @Override 2349 public boolean isFirstBoot() { 2350 return !mRestoredSettings; 2351 } 2352 2353 @Override 2354 public boolean isOnlyCoreApps() { 2355 return mOnlyCore; 2356 } 2357 2358 @Override 2359 public boolean isUpgrade() { 2360 return mIsUpgrade; 2361 } 2362 2363 private String getRequiredVerifierLPr() { 2364 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2365 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2366 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2367 2368 String requiredVerifier = null; 2369 2370 final int N = receivers.size(); 2371 for (int i = 0; i < N; i++) { 2372 final ResolveInfo info = receivers.get(i); 2373 2374 if (info.activityInfo == null) { 2375 continue; 2376 } 2377 2378 final String packageName = info.activityInfo.packageName; 2379 2380 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2381 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2382 continue; 2383 } 2384 2385 if (requiredVerifier != null) { 2386 throw new RuntimeException("There can be only one required verifier"); 2387 } 2388 2389 requiredVerifier = packageName; 2390 } 2391 2392 return requiredVerifier; 2393 } 2394 2395 private String getRequiredInstallerLPr() { 2396 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2397 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2398 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2399 2400 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2401 PACKAGE_MIME_TYPE, 0, 0); 2402 2403 String requiredInstaller = null; 2404 2405 final int N = installers.size(); 2406 for (int i = 0; i < N; i++) { 2407 final ResolveInfo info = installers.get(i); 2408 final String packageName = info.activityInfo.packageName; 2409 2410 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2411 continue; 2412 } 2413 2414 if (requiredInstaller != null) { 2415 throw new RuntimeException("There must be one required installer"); 2416 } 2417 2418 requiredInstaller = packageName; 2419 } 2420 2421 if (requiredInstaller == null) { 2422 throw new RuntimeException("There must be one required installer"); 2423 } 2424 2425 return requiredInstaller; 2426 } 2427 2428 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2429 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2430 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2431 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2432 2433 ComponentName verifierComponentName = null; 2434 2435 int priority = -1000; 2436 final int N = receivers.size(); 2437 for (int i = 0; i < N; i++) { 2438 final ResolveInfo info = receivers.get(i); 2439 2440 if (info.activityInfo == null) { 2441 continue; 2442 } 2443 2444 final String packageName = info.activityInfo.packageName; 2445 2446 final PackageSetting ps = mSettings.mPackages.get(packageName); 2447 if (ps == null) { 2448 continue; 2449 } 2450 2451 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2452 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2453 continue; 2454 } 2455 2456 // Select the IntentFilterVerifier with the highest priority 2457 if (priority < info.priority) { 2458 priority = info.priority; 2459 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2460 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2461 + verifierComponentName + " with priority: " + info.priority); 2462 } 2463 } 2464 2465 return verifierComponentName; 2466 } 2467 2468 private void primeDomainVerificationsLPw(int userId) { 2469 if (DEBUG_DOMAIN_VERIFICATION) { 2470 Slog.d(TAG, "Priming domain verifications in user " + userId); 2471 } 2472 2473 SystemConfig systemConfig = SystemConfig.getInstance(); 2474 ArraySet<String> packages = systemConfig.getLinkedApps(); 2475 ArraySet<String> domains = new ArraySet<String>(); 2476 2477 for (String packageName : packages) { 2478 PackageParser.Package pkg = mPackages.get(packageName); 2479 if (pkg != null) { 2480 if (!pkg.isSystemApp()) { 2481 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2482 continue; 2483 } 2484 2485 domains.clear(); 2486 for (PackageParser.Activity a : pkg.activities) { 2487 for (ActivityIntentInfo filter : a.intents) { 2488 if (hasValidDomains(filter)) { 2489 domains.addAll(filter.getHostsList()); 2490 } 2491 } 2492 } 2493 2494 if (domains.size() > 0) { 2495 if (DEBUG_DOMAIN_VERIFICATION) { 2496 Slog.v(TAG, " + " + packageName); 2497 } 2498 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2499 // state w.r.t. the formal app-linkage "no verification attempted" state; 2500 // and then 'always' in the per-user state actually used for intent resolution. 2501 final IntentFilterVerificationInfo ivi; 2502 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2503 new ArrayList<String>(domains)); 2504 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2505 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2506 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2507 } else { 2508 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2509 + "' does not handle web links"); 2510 } 2511 } else { 2512 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2513 } 2514 } 2515 2516 scheduleWritePackageRestrictionsLocked(userId); 2517 scheduleWriteSettingsLocked(); 2518 } 2519 2520 private void applyFactoryDefaultBrowserLPw(int userId) { 2521 // The default browser app's package name is stored in a string resource, 2522 // with a product-specific overlay used for vendor customization. 2523 String browserPkg = mContext.getResources().getString( 2524 com.android.internal.R.string.default_browser); 2525 if (!TextUtils.isEmpty(browserPkg)) { 2526 // non-empty string => required to be a known package 2527 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2528 if (ps == null) { 2529 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2530 browserPkg = null; 2531 } else { 2532 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2533 } 2534 } 2535 2536 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2537 // default. If there's more than one, just leave everything alone. 2538 if (browserPkg == null) { 2539 calculateDefaultBrowserLPw(userId); 2540 } 2541 } 2542 2543 private void calculateDefaultBrowserLPw(int userId) { 2544 List<String> allBrowsers = resolveAllBrowserApps(userId); 2545 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2546 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2547 } 2548 2549 private List<String> resolveAllBrowserApps(int userId) { 2550 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2551 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2552 PackageManager.MATCH_ALL, userId); 2553 2554 final int count = list.size(); 2555 List<String> result = new ArrayList<String>(count); 2556 for (int i=0; i<count; i++) { 2557 ResolveInfo info = list.get(i); 2558 if (info.activityInfo == null 2559 || !info.handleAllWebDataURI 2560 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2561 || result.contains(info.activityInfo.packageName)) { 2562 continue; 2563 } 2564 result.add(info.activityInfo.packageName); 2565 } 2566 2567 return result; 2568 } 2569 2570 private boolean packageIsBrowser(String packageName, int userId) { 2571 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2572 PackageManager.MATCH_ALL, userId); 2573 final int N = list.size(); 2574 for (int i = 0; i < N; i++) { 2575 ResolveInfo info = list.get(i); 2576 if (packageName.equals(info.activityInfo.packageName)) { 2577 return true; 2578 } 2579 } 2580 return false; 2581 } 2582 2583 private void checkDefaultBrowser() { 2584 final int myUserId = UserHandle.myUserId(); 2585 final String packageName = getDefaultBrowserPackageName(myUserId); 2586 if (packageName != null) { 2587 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2588 if (info == null) { 2589 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2590 synchronized (mPackages) { 2591 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2592 } 2593 } 2594 } 2595 } 2596 2597 @Override 2598 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2599 throws RemoteException { 2600 try { 2601 return super.onTransact(code, data, reply, flags); 2602 } catch (RuntimeException e) { 2603 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2604 Slog.wtf(TAG, "Package Manager Crash", e); 2605 } 2606 throw e; 2607 } 2608 } 2609 2610 void cleanupInstallFailedPackage(PackageSetting ps) { 2611 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2612 2613 removeDataDirsLI(ps.volumeUuid, ps.name); 2614 if (ps.codePath != null) { 2615 if (ps.codePath.isDirectory()) { 2616 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2617 } else { 2618 ps.codePath.delete(); 2619 } 2620 } 2621 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2622 if (ps.resourcePath.isDirectory()) { 2623 FileUtils.deleteContents(ps.resourcePath); 2624 } 2625 ps.resourcePath.delete(); 2626 } 2627 mSettings.removePackageLPw(ps.name); 2628 } 2629 2630 static int[] appendInts(int[] cur, int[] add) { 2631 if (add == null) return cur; 2632 if (cur == null) return add; 2633 final int N = add.length; 2634 for (int i=0; i<N; i++) { 2635 cur = appendInt(cur, add[i]); 2636 } 2637 return cur; 2638 } 2639 2640 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2641 if (!sUserManager.exists(userId)) return null; 2642 final PackageSetting ps = (PackageSetting) p.mExtras; 2643 if (ps == null) { 2644 return null; 2645 } 2646 2647 final PermissionsState permissionsState = ps.getPermissionsState(); 2648 2649 final int[] gids = permissionsState.computeGids(userId); 2650 final Set<String> permissions = permissionsState.getPermissions(userId); 2651 final PackageUserState state = ps.readUserState(userId); 2652 2653 return PackageParser.generatePackageInfo(p, gids, flags, 2654 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2655 } 2656 2657 @Override 2658 public boolean isPackageFrozen(String packageName) { 2659 synchronized (mPackages) { 2660 final PackageSetting ps = mSettings.mPackages.get(packageName); 2661 if (ps != null) { 2662 return ps.frozen; 2663 } 2664 } 2665 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2666 return true; 2667 } 2668 2669 @Override 2670 public boolean isPackageAvailable(String packageName, int userId) { 2671 if (!sUserManager.exists(userId)) return false; 2672 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2673 synchronized (mPackages) { 2674 PackageParser.Package p = mPackages.get(packageName); 2675 if (p != null) { 2676 final PackageSetting ps = (PackageSetting) p.mExtras; 2677 if (ps != null) { 2678 final PackageUserState state = ps.readUserState(userId); 2679 if (state != null) { 2680 return PackageParser.isAvailable(state); 2681 } 2682 } 2683 } 2684 } 2685 return false; 2686 } 2687 2688 @Override 2689 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2690 if (!sUserManager.exists(userId)) return null; 2691 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2692 // reader 2693 synchronized (mPackages) { 2694 PackageParser.Package p = mPackages.get(packageName); 2695 if (DEBUG_PACKAGE_INFO) 2696 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2697 if (p != null) { 2698 return generatePackageInfo(p, flags, userId); 2699 } 2700 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2701 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2702 } 2703 } 2704 return null; 2705 } 2706 2707 @Override 2708 public String[] currentToCanonicalPackageNames(String[] names) { 2709 String[] out = new String[names.length]; 2710 // reader 2711 synchronized (mPackages) { 2712 for (int i=names.length-1; i>=0; i--) { 2713 PackageSetting ps = mSettings.mPackages.get(names[i]); 2714 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2715 } 2716 } 2717 return out; 2718 } 2719 2720 @Override 2721 public String[] canonicalToCurrentPackageNames(String[] names) { 2722 String[] out = new String[names.length]; 2723 // reader 2724 synchronized (mPackages) { 2725 for (int i=names.length-1; i>=0; i--) { 2726 String cur = mSettings.mRenamedPackages.get(names[i]); 2727 out[i] = cur != null ? cur : names[i]; 2728 } 2729 } 2730 return out; 2731 } 2732 2733 @Override 2734 public int getPackageUid(String packageName, int userId) { 2735 if (!sUserManager.exists(userId)) return -1; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2737 2738 // reader 2739 synchronized (mPackages) { 2740 PackageParser.Package p = mPackages.get(packageName); 2741 if(p != null) { 2742 return UserHandle.getUid(userId, p.applicationInfo.uid); 2743 } 2744 PackageSetting ps = mSettings.mPackages.get(packageName); 2745 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2746 return -1; 2747 } 2748 p = ps.pkg; 2749 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2750 } 2751 } 2752 2753 @Override 2754 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2755 if (!sUserManager.exists(userId)) { 2756 return null; 2757 } 2758 2759 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2760 "getPackageGids"); 2761 2762 // reader 2763 synchronized (mPackages) { 2764 PackageParser.Package p = mPackages.get(packageName); 2765 if (DEBUG_PACKAGE_INFO) { 2766 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2767 } 2768 if (p != null) { 2769 PackageSetting ps = (PackageSetting) p.mExtras; 2770 return ps.getPermissionsState().computeGids(userId); 2771 } 2772 } 2773 2774 return null; 2775 } 2776 2777 static PermissionInfo generatePermissionInfo( 2778 BasePermission bp, int flags) { 2779 if (bp.perm != null) { 2780 return PackageParser.generatePermissionInfo(bp.perm, flags); 2781 } 2782 PermissionInfo pi = new PermissionInfo(); 2783 pi.name = bp.name; 2784 pi.packageName = bp.sourcePackage; 2785 pi.nonLocalizedLabel = bp.name; 2786 pi.protectionLevel = bp.protectionLevel; 2787 return pi; 2788 } 2789 2790 @Override 2791 public PermissionInfo getPermissionInfo(String name, int flags) { 2792 // reader 2793 synchronized (mPackages) { 2794 final BasePermission p = mSettings.mPermissions.get(name); 2795 if (p != null) { 2796 return generatePermissionInfo(p, flags); 2797 } 2798 return null; 2799 } 2800 } 2801 2802 @Override 2803 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2804 // reader 2805 synchronized (mPackages) { 2806 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2807 for (BasePermission p : mSettings.mPermissions.values()) { 2808 if (group == null) { 2809 if (p.perm == null || p.perm.info.group == null) { 2810 out.add(generatePermissionInfo(p, flags)); 2811 } 2812 } else { 2813 if (p.perm != null && group.equals(p.perm.info.group)) { 2814 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2815 } 2816 } 2817 } 2818 2819 if (out.size() > 0) { 2820 return out; 2821 } 2822 return mPermissionGroups.containsKey(group) ? out : null; 2823 } 2824 } 2825 2826 @Override 2827 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2828 // reader 2829 synchronized (mPackages) { 2830 return PackageParser.generatePermissionGroupInfo( 2831 mPermissionGroups.get(name), flags); 2832 } 2833 } 2834 2835 @Override 2836 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2837 // reader 2838 synchronized (mPackages) { 2839 final int N = mPermissionGroups.size(); 2840 ArrayList<PermissionGroupInfo> out 2841 = new ArrayList<PermissionGroupInfo>(N); 2842 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2843 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2844 } 2845 return out; 2846 } 2847 } 2848 2849 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2850 int userId) { 2851 if (!sUserManager.exists(userId)) return null; 2852 PackageSetting ps = mSettings.mPackages.get(packageName); 2853 if (ps != null) { 2854 if (ps.pkg == null) { 2855 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2856 flags, userId); 2857 if (pInfo != null) { 2858 return pInfo.applicationInfo; 2859 } 2860 return null; 2861 } 2862 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2863 ps.readUserState(userId), userId); 2864 } 2865 return null; 2866 } 2867 2868 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2869 int userId) { 2870 if (!sUserManager.exists(userId)) return null; 2871 PackageSetting ps = mSettings.mPackages.get(packageName); 2872 if (ps != null) { 2873 PackageParser.Package pkg = ps.pkg; 2874 if (pkg == null) { 2875 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2876 return null; 2877 } 2878 // Only data remains, so we aren't worried about code paths 2879 pkg = new PackageParser.Package(packageName); 2880 pkg.applicationInfo.packageName = packageName; 2881 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2882 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2883 pkg.applicationInfo.dataDir = Environment 2884 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2885 .getAbsolutePath(); 2886 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2887 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2888 } 2889 return generatePackageInfo(pkg, flags, userId); 2890 } 2891 return null; 2892 } 2893 2894 @Override 2895 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2896 if (!sUserManager.exists(userId)) return null; 2897 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2898 // writer 2899 synchronized (mPackages) { 2900 PackageParser.Package p = mPackages.get(packageName); 2901 if (DEBUG_PACKAGE_INFO) Log.v( 2902 TAG, "getApplicationInfo " + packageName 2903 + ": " + p); 2904 if (p != null) { 2905 PackageSetting ps = mSettings.mPackages.get(packageName); 2906 if (ps == null) return null; 2907 // Note: isEnabledLP() does not apply here - always return info 2908 return PackageParser.generateApplicationInfo( 2909 p, flags, ps.readUserState(userId), userId); 2910 } 2911 if ("android".equals(packageName)||"system".equals(packageName)) { 2912 return mAndroidApplication; 2913 } 2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2915 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2916 } 2917 } 2918 return null; 2919 } 2920 2921 @Override 2922 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2923 final IPackageDataObserver observer) { 2924 mContext.enforceCallingOrSelfPermission( 2925 android.Manifest.permission.CLEAR_APP_CACHE, null); 2926 // Queue up an async operation since clearing cache may take a little while. 2927 mHandler.post(new Runnable() { 2928 public void run() { 2929 mHandler.removeCallbacks(this); 2930 int retCode = -1; 2931 synchronized (mInstallLock) { 2932 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2933 if (retCode < 0) { 2934 Slog.w(TAG, "Couldn't clear application caches"); 2935 } 2936 } 2937 if (observer != null) { 2938 try { 2939 observer.onRemoveCompleted(null, (retCode >= 0)); 2940 } catch (RemoteException e) { 2941 Slog.w(TAG, "RemoveException when invoking call back"); 2942 } 2943 } 2944 } 2945 }); 2946 } 2947 2948 @Override 2949 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2950 final IntentSender pi) { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.CLEAR_APP_CACHE, null); 2953 // Queue up an async operation since clearing cache may take a little while. 2954 mHandler.post(new Runnable() { 2955 public void run() { 2956 mHandler.removeCallbacks(this); 2957 int retCode = -1; 2958 synchronized (mInstallLock) { 2959 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2960 if (retCode < 0) { 2961 Slog.w(TAG, "Couldn't clear application caches"); 2962 } 2963 } 2964 if(pi != null) { 2965 try { 2966 // Callback via pending intent 2967 int code = (retCode >= 0) ? 1 : 0; 2968 pi.sendIntent(null, code, null, 2969 null, null); 2970 } catch (SendIntentException e1) { 2971 Slog.i(TAG, "Failed to send pending intent"); 2972 } 2973 } 2974 } 2975 }); 2976 } 2977 2978 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2979 synchronized (mInstallLock) { 2980 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2981 throw new IOException("Failed to free enough space"); 2982 } 2983 } 2984 } 2985 2986 @Override 2987 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2988 if (!sUserManager.exists(userId)) return null; 2989 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2990 synchronized (mPackages) { 2991 PackageParser.Activity a = mActivities.mActivities.get(component); 2992 2993 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2994 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2995 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2996 if (ps == null) return null; 2997 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2998 userId); 2999 } 3000 if (mResolveComponentName.equals(component)) { 3001 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3002 new PackageUserState(), userId); 3003 } 3004 } 3005 return null; 3006 } 3007 3008 @Override 3009 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3010 String resolvedType) { 3011 synchronized (mPackages) { 3012 if (component.equals(mResolveComponentName)) { 3013 // The resolver supports EVERYTHING! 3014 return true; 3015 } 3016 PackageParser.Activity a = mActivities.mActivities.get(component); 3017 if (a == null) { 3018 return false; 3019 } 3020 for (int i=0; i<a.intents.size(); i++) { 3021 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3022 intent.getData(), intent.getCategories(), TAG) >= 0) { 3023 return true; 3024 } 3025 } 3026 return false; 3027 } 3028 } 3029 3030 @Override 3031 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3032 if (!sUserManager.exists(userId)) return null; 3033 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3034 synchronized (mPackages) { 3035 PackageParser.Activity a = mReceivers.mActivities.get(component); 3036 if (DEBUG_PACKAGE_INFO) Log.v( 3037 TAG, "getReceiverInfo " + component + ": " + a); 3038 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3039 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3040 if (ps == null) return null; 3041 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3042 userId); 3043 } 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3052 synchronized (mPackages) { 3053 PackageParser.Service s = mServices.mServices.get(component); 3054 if (DEBUG_PACKAGE_INFO) Log.v( 3055 TAG, "getServiceInfo " + component + ": " + s); 3056 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3057 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3058 if (ps == null) return null; 3059 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3060 userId); 3061 } 3062 } 3063 return null; 3064 } 3065 3066 @Override 3067 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3068 if (!sUserManager.exists(userId)) return null; 3069 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3070 synchronized (mPackages) { 3071 PackageParser.Provider p = mProviders.mProviders.get(component); 3072 if (DEBUG_PACKAGE_INFO) Log.v( 3073 TAG, "getProviderInfo " + component + ": " + p); 3074 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3075 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3076 if (ps == null) return null; 3077 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3078 userId); 3079 } 3080 } 3081 return null; 3082 } 3083 3084 @Override 3085 public String[] getSystemSharedLibraryNames() { 3086 Set<String> libSet; 3087 synchronized (mPackages) { 3088 libSet = mSharedLibraries.keySet(); 3089 int size = libSet.size(); 3090 if (size > 0) { 3091 String[] libs = new String[size]; 3092 libSet.toArray(libs); 3093 return libs; 3094 } 3095 } 3096 return null; 3097 } 3098 3099 /** 3100 * @hide 3101 */ 3102 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3103 synchronized (mPackages) { 3104 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3105 if (lib != null && lib.apk != null) { 3106 return mPackages.get(lib.apk); 3107 } 3108 } 3109 return null; 3110 } 3111 3112 @Override 3113 public FeatureInfo[] getSystemAvailableFeatures() { 3114 Collection<FeatureInfo> featSet; 3115 synchronized (mPackages) { 3116 featSet = mAvailableFeatures.values(); 3117 int size = featSet.size(); 3118 if (size > 0) { 3119 FeatureInfo[] features = new FeatureInfo[size+1]; 3120 featSet.toArray(features); 3121 FeatureInfo fi = new FeatureInfo(); 3122 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3123 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3124 features[size] = fi; 3125 return features; 3126 } 3127 } 3128 return null; 3129 } 3130 3131 @Override 3132 public boolean hasSystemFeature(String name) { 3133 synchronized (mPackages) { 3134 return mAvailableFeatures.containsKey(name); 3135 } 3136 } 3137 3138 private void checkValidCaller(int uid, int userId) { 3139 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3140 return; 3141 3142 throw new SecurityException("Caller uid=" + uid 3143 + " is not privileged to communicate with user=" + userId); 3144 } 3145 3146 @Override 3147 public int checkPermission(String permName, String pkgName, int userId) { 3148 if (!sUserManager.exists(userId)) { 3149 return PackageManager.PERMISSION_DENIED; 3150 } 3151 3152 synchronized (mPackages) { 3153 final PackageParser.Package p = mPackages.get(pkgName); 3154 if (p != null && p.mExtras != null) { 3155 final PackageSetting ps = (PackageSetting) p.mExtras; 3156 final PermissionsState permissionsState = ps.getPermissionsState(); 3157 if (permissionsState.hasPermission(permName, userId)) { 3158 return PackageManager.PERMISSION_GRANTED; 3159 } 3160 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3161 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3162 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3163 return PackageManager.PERMISSION_GRANTED; 3164 } 3165 } 3166 } 3167 3168 return PackageManager.PERMISSION_DENIED; 3169 } 3170 3171 @Override 3172 public int checkUidPermission(String permName, int uid) { 3173 final int userId = UserHandle.getUserId(uid); 3174 3175 if (!sUserManager.exists(userId)) { 3176 return PackageManager.PERMISSION_DENIED; 3177 } 3178 3179 synchronized (mPackages) { 3180 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3181 if (obj != null) { 3182 final SettingBase ps = (SettingBase) obj; 3183 final PermissionsState permissionsState = ps.getPermissionsState(); 3184 if (permissionsState.hasPermission(permName, userId)) { 3185 return PackageManager.PERMISSION_GRANTED; 3186 } 3187 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3188 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3189 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3190 return PackageManager.PERMISSION_GRANTED; 3191 } 3192 } else { 3193 ArraySet<String> perms = mSystemPermissions.get(uid); 3194 if (perms != null) { 3195 if (perms.contains(permName)) { 3196 return PackageManager.PERMISSION_GRANTED; 3197 } 3198 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3199 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3200 return PackageManager.PERMISSION_GRANTED; 3201 } 3202 } 3203 } 3204 } 3205 3206 return PackageManager.PERMISSION_DENIED; 3207 } 3208 3209 @Override 3210 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3211 if (UserHandle.getCallingUserId() != userId) { 3212 mContext.enforceCallingPermission( 3213 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3214 "isPermissionRevokedByPolicy for user " + userId); 3215 } 3216 3217 if (checkPermission(permission, packageName, userId) 3218 == PackageManager.PERMISSION_GRANTED) { 3219 return false; 3220 } 3221 3222 final long identity = Binder.clearCallingIdentity(); 3223 try { 3224 final int flags = getPermissionFlags(permission, packageName, userId); 3225 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3226 } finally { 3227 Binder.restoreCallingIdentity(identity); 3228 } 3229 } 3230 3231 @Override 3232 public String getPermissionControllerPackageName() { 3233 synchronized (mPackages) { 3234 return mRequiredInstallerPackage; 3235 } 3236 } 3237 3238 /** 3239 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3240 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3241 * @param checkShell TODO(yamasani): 3242 * @param message the message to log on security exception 3243 */ 3244 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3245 boolean checkShell, String message) { 3246 if (userId < 0) { 3247 throw new IllegalArgumentException("Invalid userId " + userId); 3248 } 3249 if (checkShell) { 3250 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3251 } 3252 if (userId == UserHandle.getUserId(callingUid)) return; 3253 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3254 if (requireFullPermission) { 3255 mContext.enforceCallingOrSelfPermission( 3256 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3257 } else { 3258 try { 3259 mContext.enforceCallingOrSelfPermission( 3260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3261 } catch (SecurityException se) { 3262 mContext.enforceCallingOrSelfPermission( 3263 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3264 } 3265 } 3266 } 3267 } 3268 3269 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3270 if (callingUid == Process.SHELL_UID) { 3271 if (userHandle >= 0 3272 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3273 throw new SecurityException("Shell does not have permission to access user " 3274 + userHandle); 3275 } else if (userHandle < 0) { 3276 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3277 + Debug.getCallers(3)); 3278 } 3279 } 3280 } 3281 3282 private BasePermission findPermissionTreeLP(String permName) { 3283 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3284 if (permName.startsWith(bp.name) && 3285 permName.length() > bp.name.length() && 3286 permName.charAt(bp.name.length()) == '.') { 3287 return bp; 3288 } 3289 } 3290 return null; 3291 } 3292 3293 private BasePermission checkPermissionTreeLP(String permName) { 3294 if (permName != null) { 3295 BasePermission bp = findPermissionTreeLP(permName); 3296 if (bp != null) { 3297 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3298 return bp; 3299 } 3300 throw new SecurityException("Calling uid " 3301 + Binder.getCallingUid() 3302 + " is not allowed to add to permission tree " 3303 + bp.name + " owned by uid " + bp.uid); 3304 } 3305 } 3306 throw new SecurityException("No permission tree found for " + permName); 3307 } 3308 3309 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3310 if (s1 == null) { 3311 return s2 == null; 3312 } 3313 if (s2 == null) { 3314 return false; 3315 } 3316 if (s1.getClass() != s2.getClass()) { 3317 return false; 3318 } 3319 return s1.equals(s2); 3320 } 3321 3322 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3323 if (pi1.icon != pi2.icon) return false; 3324 if (pi1.logo != pi2.logo) return false; 3325 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3326 if (!compareStrings(pi1.name, pi2.name)) return false; 3327 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3328 // We'll take care of setting this one. 3329 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3330 // These are not currently stored in settings. 3331 //if (!compareStrings(pi1.group, pi2.group)) return false; 3332 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3333 //if (pi1.labelRes != pi2.labelRes) return false; 3334 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3335 return true; 3336 } 3337 3338 int permissionInfoFootprint(PermissionInfo info) { 3339 int size = info.name.length(); 3340 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3341 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3342 return size; 3343 } 3344 3345 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3346 int size = 0; 3347 for (BasePermission perm : mSettings.mPermissions.values()) { 3348 if (perm.uid == tree.uid) { 3349 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3350 } 3351 } 3352 return size; 3353 } 3354 3355 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3356 // We calculate the max size of permissions defined by this uid and throw 3357 // if that plus the size of 'info' would exceed our stated maximum. 3358 if (tree.uid != Process.SYSTEM_UID) { 3359 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3360 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3361 throw new SecurityException("Permission tree size cap exceeded"); 3362 } 3363 } 3364 } 3365 3366 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3367 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3368 throw new SecurityException("Label must be specified in permission"); 3369 } 3370 BasePermission tree = checkPermissionTreeLP(info.name); 3371 BasePermission bp = mSettings.mPermissions.get(info.name); 3372 boolean added = bp == null; 3373 boolean changed = true; 3374 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3375 if (added) { 3376 enforcePermissionCapLocked(info, tree); 3377 bp = new BasePermission(info.name, tree.sourcePackage, 3378 BasePermission.TYPE_DYNAMIC); 3379 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3380 throw new SecurityException( 3381 "Not allowed to modify non-dynamic permission " 3382 + info.name); 3383 } else { 3384 if (bp.protectionLevel == fixedLevel 3385 && bp.perm.owner.equals(tree.perm.owner) 3386 && bp.uid == tree.uid 3387 && comparePermissionInfos(bp.perm.info, info)) { 3388 changed = false; 3389 } 3390 } 3391 bp.protectionLevel = fixedLevel; 3392 info = new PermissionInfo(info); 3393 info.protectionLevel = fixedLevel; 3394 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3395 bp.perm.info.packageName = tree.perm.info.packageName; 3396 bp.uid = tree.uid; 3397 if (added) { 3398 mSettings.mPermissions.put(info.name, bp); 3399 } 3400 if (changed) { 3401 if (!async) { 3402 mSettings.writeLPr(); 3403 } else { 3404 scheduleWriteSettingsLocked(); 3405 } 3406 } 3407 return added; 3408 } 3409 3410 @Override 3411 public boolean addPermission(PermissionInfo info) { 3412 synchronized (mPackages) { 3413 return addPermissionLocked(info, false); 3414 } 3415 } 3416 3417 @Override 3418 public boolean addPermissionAsync(PermissionInfo info) { 3419 synchronized (mPackages) { 3420 return addPermissionLocked(info, true); 3421 } 3422 } 3423 3424 @Override 3425 public void removePermission(String name) { 3426 synchronized (mPackages) { 3427 checkPermissionTreeLP(name); 3428 BasePermission bp = mSettings.mPermissions.get(name); 3429 if (bp != null) { 3430 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3431 throw new SecurityException( 3432 "Not allowed to modify non-dynamic permission " 3433 + name); 3434 } 3435 mSettings.mPermissions.remove(name); 3436 mSettings.writeLPr(); 3437 } 3438 } 3439 } 3440 3441 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3442 BasePermission bp) { 3443 int index = pkg.requestedPermissions.indexOf(bp.name); 3444 if (index == -1) { 3445 throw new SecurityException("Package " + pkg.packageName 3446 + " has not requested permission " + bp.name); 3447 } 3448 if (!bp.isRuntime() && !bp.isDevelopment()) { 3449 throw new SecurityException("Permission " + bp.name 3450 + " is not a changeable permission type"); 3451 } 3452 } 3453 3454 @Override 3455 public void grantRuntimePermission(String packageName, String name, final int userId) { 3456 if (!sUserManager.exists(userId)) { 3457 Log.e(TAG, "No such user:" + userId); 3458 return; 3459 } 3460 3461 mContext.enforceCallingOrSelfPermission( 3462 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3463 "grantRuntimePermission"); 3464 3465 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3466 "grantRuntimePermission"); 3467 3468 final int uid; 3469 final SettingBase sb; 3470 3471 synchronized (mPackages) { 3472 final PackageParser.Package pkg = mPackages.get(packageName); 3473 if (pkg == null) { 3474 throw new IllegalArgumentException("Unknown package: " + packageName); 3475 } 3476 3477 final BasePermission bp = mSettings.mPermissions.get(name); 3478 if (bp == null) { 3479 throw new IllegalArgumentException("Unknown permission: " + name); 3480 } 3481 3482 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3483 3484 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3485 sb = (SettingBase) pkg.mExtras; 3486 if (sb == null) { 3487 throw new IllegalArgumentException("Unknown package: " + packageName); 3488 } 3489 3490 final PermissionsState permissionsState = sb.getPermissionsState(); 3491 3492 final int flags = permissionsState.getPermissionFlags(name, userId); 3493 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3494 throw new SecurityException("Cannot grant system fixed permission: " 3495 + name + " for package: " + packageName); 3496 } 3497 3498 if (bp.isDevelopment()) { 3499 // Development permissions must be handled specially, since they are not 3500 // normal runtime permissions. For now they apply to all users. 3501 if (permissionsState.grantInstallPermission(bp) != 3502 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3503 scheduleWriteSettingsLocked(); 3504 } 3505 return; 3506 } 3507 3508 final int result = permissionsState.grantRuntimePermission(bp, userId); 3509 switch (result) { 3510 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3511 return; 3512 } 3513 3514 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3515 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3516 mHandler.post(new Runnable() { 3517 @Override 3518 public void run() { 3519 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3520 } 3521 }); 3522 } break; 3523 } 3524 3525 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3526 3527 // Not critical if that is lost - app has to request again. 3528 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3529 } 3530 3531 // Only need to do this if user is initialized. Otherwise it's a new user 3532 // and there are no processes running as the user yet and there's no need 3533 // to make an expensive call to remount processes for the changed permissions. 3534 if (READ_EXTERNAL_STORAGE.equals(name) 3535 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3536 final long token = Binder.clearCallingIdentity(); 3537 try { 3538 if (sUserManager.isInitialized(userId)) { 3539 MountServiceInternal mountServiceInternal = LocalServices.getService( 3540 MountServiceInternal.class); 3541 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3542 } 3543 } finally { 3544 Binder.restoreCallingIdentity(token); 3545 } 3546 } 3547 } 3548 3549 @Override 3550 public void revokeRuntimePermission(String packageName, String name, int userId) { 3551 if (!sUserManager.exists(userId)) { 3552 Log.e(TAG, "No such user:" + userId); 3553 return; 3554 } 3555 3556 mContext.enforceCallingOrSelfPermission( 3557 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3558 "revokeRuntimePermission"); 3559 3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3561 "revokeRuntimePermission"); 3562 3563 final int appId; 3564 3565 synchronized (mPackages) { 3566 final PackageParser.Package pkg = mPackages.get(packageName); 3567 if (pkg == null) { 3568 throw new IllegalArgumentException("Unknown package: " + packageName); 3569 } 3570 3571 final BasePermission bp = mSettings.mPermissions.get(name); 3572 if (bp == null) { 3573 throw new IllegalArgumentException("Unknown permission: " + name); 3574 } 3575 3576 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3577 3578 SettingBase sb = (SettingBase) pkg.mExtras; 3579 if (sb == null) { 3580 throw new IllegalArgumentException("Unknown package: " + packageName); 3581 } 3582 3583 final PermissionsState permissionsState = sb.getPermissionsState(); 3584 3585 final int flags = permissionsState.getPermissionFlags(name, userId); 3586 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3587 throw new SecurityException("Cannot revoke system fixed permission: " 3588 + name + " for package: " + packageName); 3589 } 3590 3591 if (bp.isDevelopment()) { 3592 // Development permissions must be handled specially, since they are not 3593 // normal runtime permissions. For now they apply to all users. 3594 if (permissionsState.revokeInstallPermission(bp) != 3595 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3596 scheduleWriteSettingsLocked(); 3597 } 3598 return; 3599 } 3600 3601 if (permissionsState.revokeRuntimePermission(bp, userId) == 3602 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3603 return; 3604 } 3605 3606 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3607 3608 // Critical, after this call app should never have the permission. 3609 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3610 3611 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3612 } 3613 3614 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3615 } 3616 3617 @Override 3618 public void resetRuntimePermissions() { 3619 mContext.enforceCallingOrSelfPermission( 3620 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3621 "revokeRuntimePermission"); 3622 3623 int callingUid = Binder.getCallingUid(); 3624 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3625 mContext.enforceCallingOrSelfPermission( 3626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3627 "resetRuntimePermissions"); 3628 } 3629 3630 synchronized (mPackages) { 3631 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3632 for (int userId : UserManagerService.getInstance().getUserIds()) { 3633 final int packageCount = mPackages.size(); 3634 for (int i = 0; i < packageCount; i++) { 3635 PackageParser.Package pkg = mPackages.valueAt(i); 3636 if (!(pkg.mExtras instanceof PackageSetting)) { 3637 continue; 3638 } 3639 PackageSetting ps = (PackageSetting) pkg.mExtras; 3640 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3641 } 3642 } 3643 } 3644 } 3645 3646 @Override 3647 public int getPermissionFlags(String name, String packageName, int userId) { 3648 if (!sUserManager.exists(userId)) { 3649 return 0; 3650 } 3651 3652 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3653 3654 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3655 "getPermissionFlags"); 3656 3657 synchronized (mPackages) { 3658 final PackageParser.Package pkg = mPackages.get(packageName); 3659 if (pkg == null) { 3660 throw new IllegalArgumentException("Unknown package: " + packageName); 3661 } 3662 3663 final BasePermission bp = mSettings.mPermissions.get(name); 3664 if (bp == null) { 3665 throw new IllegalArgumentException("Unknown permission: " + name); 3666 } 3667 3668 SettingBase sb = (SettingBase) pkg.mExtras; 3669 if (sb == null) { 3670 throw new IllegalArgumentException("Unknown package: " + packageName); 3671 } 3672 3673 PermissionsState permissionsState = sb.getPermissionsState(); 3674 return permissionsState.getPermissionFlags(name, userId); 3675 } 3676 } 3677 3678 @Override 3679 public void updatePermissionFlags(String name, String packageName, int flagMask, 3680 int flagValues, int userId) { 3681 if (!sUserManager.exists(userId)) { 3682 return; 3683 } 3684 3685 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3686 3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3688 "updatePermissionFlags"); 3689 3690 // Only the system can change these flags and nothing else. 3691 if (getCallingUid() != Process.SYSTEM_UID) { 3692 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3693 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3694 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3695 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3696 } 3697 3698 synchronized (mPackages) { 3699 final PackageParser.Package pkg = mPackages.get(packageName); 3700 if (pkg == null) { 3701 throw new IllegalArgumentException("Unknown package: " + packageName); 3702 } 3703 3704 final BasePermission bp = mSettings.mPermissions.get(name); 3705 if (bp == null) { 3706 throw new IllegalArgumentException("Unknown permission: " + name); 3707 } 3708 3709 SettingBase sb = (SettingBase) pkg.mExtras; 3710 if (sb == null) { 3711 throw new IllegalArgumentException("Unknown package: " + packageName); 3712 } 3713 3714 PermissionsState permissionsState = sb.getPermissionsState(); 3715 3716 // Only the package manager can change flags for system component permissions. 3717 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3718 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3719 return; 3720 } 3721 3722 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3723 3724 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3725 // Install and runtime permissions are stored in different places, 3726 // so figure out what permission changed and persist the change. 3727 if (permissionsState.getInstallPermissionState(name) != null) { 3728 scheduleWriteSettingsLocked(); 3729 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3730 || hadState) { 3731 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3732 } 3733 } 3734 } 3735 } 3736 3737 /** 3738 * Update the permission flags for all packages and runtime permissions of a user in order 3739 * to allow device or profile owner to remove POLICY_FIXED. 3740 */ 3741 @Override 3742 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3743 if (!sUserManager.exists(userId)) { 3744 return; 3745 } 3746 3747 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3748 3749 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3750 "updatePermissionFlagsForAllApps"); 3751 3752 // Only the system can change system fixed flags. 3753 if (getCallingUid() != Process.SYSTEM_UID) { 3754 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3755 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3756 } 3757 3758 synchronized (mPackages) { 3759 boolean changed = false; 3760 final int packageCount = mPackages.size(); 3761 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3762 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3763 SettingBase sb = (SettingBase) pkg.mExtras; 3764 if (sb == null) { 3765 continue; 3766 } 3767 PermissionsState permissionsState = sb.getPermissionsState(); 3768 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3769 userId, flagMask, flagValues); 3770 } 3771 if (changed) { 3772 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3773 } 3774 } 3775 } 3776 3777 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3778 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3779 != PackageManager.PERMISSION_GRANTED 3780 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3781 != PackageManager.PERMISSION_GRANTED) { 3782 throw new SecurityException(message + " requires " 3783 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3784 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3785 } 3786 } 3787 3788 @Override 3789 public boolean shouldShowRequestPermissionRationale(String permissionName, 3790 String packageName, int userId) { 3791 if (UserHandle.getCallingUserId() != userId) { 3792 mContext.enforceCallingPermission( 3793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3794 "canShowRequestPermissionRationale for user " + userId); 3795 } 3796 3797 final int uid = getPackageUid(packageName, userId); 3798 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3799 return false; 3800 } 3801 3802 if (checkPermission(permissionName, packageName, userId) 3803 == PackageManager.PERMISSION_GRANTED) { 3804 return false; 3805 } 3806 3807 final int flags; 3808 3809 final long identity = Binder.clearCallingIdentity(); 3810 try { 3811 flags = getPermissionFlags(permissionName, 3812 packageName, userId); 3813 } finally { 3814 Binder.restoreCallingIdentity(identity); 3815 } 3816 3817 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3818 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3819 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3820 3821 if ((flags & fixedFlags) != 0) { 3822 return false; 3823 } 3824 3825 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3826 } 3827 3828 @Override 3829 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3830 mContext.enforceCallingOrSelfPermission( 3831 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3832 "addOnPermissionsChangeListener"); 3833 3834 synchronized (mPackages) { 3835 mOnPermissionChangeListeners.addListenerLocked(listener); 3836 } 3837 } 3838 3839 @Override 3840 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3841 synchronized (mPackages) { 3842 mOnPermissionChangeListeners.removeListenerLocked(listener); 3843 } 3844 } 3845 3846 @Override 3847 public boolean isProtectedBroadcast(String actionName) { 3848 synchronized (mPackages) { 3849 return mProtectedBroadcasts.contains(actionName); 3850 } 3851 } 3852 3853 @Override 3854 public int checkSignatures(String pkg1, String pkg2) { 3855 synchronized (mPackages) { 3856 final PackageParser.Package p1 = mPackages.get(pkg1); 3857 final PackageParser.Package p2 = mPackages.get(pkg2); 3858 if (p1 == null || p1.mExtras == null 3859 || p2 == null || p2.mExtras == null) { 3860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3861 } 3862 return compareSignatures(p1.mSignatures, p2.mSignatures); 3863 } 3864 } 3865 3866 @Override 3867 public int checkUidSignatures(int uid1, int uid2) { 3868 // Map to base uids. 3869 uid1 = UserHandle.getAppId(uid1); 3870 uid2 = UserHandle.getAppId(uid2); 3871 // reader 3872 synchronized (mPackages) { 3873 Signature[] s1; 3874 Signature[] s2; 3875 Object obj = mSettings.getUserIdLPr(uid1); 3876 if (obj != null) { 3877 if (obj instanceof SharedUserSetting) { 3878 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3879 } else if (obj instanceof PackageSetting) { 3880 s1 = ((PackageSetting)obj).signatures.mSignatures; 3881 } else { 3882 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3883 } 3884 } else { 3885 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3886 } 3887 obj = mSettings.getUserIdLPr(uid2); 3888 if (obj != null) { 3889 if (obj instanceof SharedUserSetting) { 3890 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3891 } else if (obj instanceof PackageSetting) { 3892 s2 = ((PackageSetting)obj).signatures.mSignatures; 3893 } else { 3894 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3895 } 3896 } else { 3897 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3898 } 3899 return compareSignatures(s1, s2); 3900 } 3901 } 3902 3903 private void killUid(int appId, int userId, String reason) { 3904 final long identity = Binder.clearCallingIdentity(); 3905 try { 3906 IActivityManager am = ActivityManagerNative.getDefault(); 3907 if (am != null) { 3908 try { 3909 am.killUid(appId, userId, reason); 3910 } catch (RemoteException e) { 3911 /* ignore - same process */ 3912 } 3913 } 3914 } finally { 3915 Binder.restoreCallingIdentity(identity); 3916 } 3917 } 3918 3919 /** 3920 * Compares two sets of signatures. Returns: 3921 * <br /> 3922 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3923 * <br /> 3924 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3925 * <br /> 3926 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3927 * <br /> 3928 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3929 * <br /> 3930 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3931 */ 3932 static int compareSignatures(Signature[] s1, Signature[] s2) { 3933 if (s1 == null) { 3934 return s2 == null 3935 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3936 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3937 } 3938 3939 if (s2 == null) { 3940 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3941 } 3942 3943 if (s1.length != s2.length) { 3944 return PackageManager.SIGNATURE_NO_MATCH; 3945 } 3946 3947 // Since both signature sets are of size 1, we can compare without HashSets. 3948 if (s1.length == 1) { 3949 return s1[0].equals(s2[0]) ? 3950 PackageManager.SIGNATURE_MATCH : 3951 PackageManager.SIGNATURE_NO_MATCH; 3952 } 3953 3954 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3955 for (Signature sig : s1) { 3956 set1.add(sig); 3957 } 3958 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3959 for (Signature sig : s2) { 3960 set2.add(sig); 3961 } 3962 // Make sure s2 contains all signatures in s1. 3963 if (set1.equals(set2)) { 3964 return PackageManager.SIGNATURE_MATCH; 3965 } 3966 return PackageManager.SIGNATURE_NO_MATCH; 3967 } 3968 3969 /** 3970 * If the database version for this type of package (internal storage or 3971 * external storage) is less than the version where package signatures 3972 * were updated, return true. 3973 */ 3974 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3975 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3976 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3977 } 3978 3979 /** 3980 * Used for backward compatibility to make sure any packages with 3981 * certificate chains get upgraded to the new style. {@code existingSigs} 3982 * will be in the old format (since they were stored on disk from before the 3983 * system upgrade) and {@code scannedSigs} will be in the newer format. 3984 */ 3985 private int compareSignaturesCompat(PackageSignatures existingSigs, 3986 PackageParser.Package scannedPkg) { 3987 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3988 return PackageManager.SIGNATURE_NO_MATCH; 3989 } 3990 3991 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3992 for (Signature sig : existingSigs.mSignatures) { 3993 existingSet.add(sig); 3994 } 3995 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3996 for (Signature sig : scannedPkg.mSignatures) { 3997 try { 3998 Signature[] chainSignatures = sig.getChainSignatures(); 3999 for (Signature chainSig : chainSignatures) { 4000 scannedCompatSet.add(chainSig); 4001 } 4002 } catch (CertificateEncodingException e) { 4003 scannedCompatSet.add(sig); 4004 } 4005 } 4006 /* 4007 * Make sure the expanded scanned set contains all signatures in the 4008 * existing one. 4009 */ 4010 if (scannedCompatSet.equals(existingSet)) { 4011 // Migrate the old signatures to the new scheme. 4012 existingSigs.assignSignatures(scannedPkg.mSignatures); 4013 // The new KeySets will be re-added later in the scanning process. 4014 synchronized (mPackages) { 4015 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4016 } 4017 return PackageManager.SIGNATURE_MATCH; 4018 } 4019 return PackageManager.SIGNATURE_NO_MATCH; 4020 } 4021 4022 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4023 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4024 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4025 } 4026 4027 private int compareSignaturesRecover(PackageSignatures existingSigs, 4028 PackageParser.Package scannedPkg) { 4029 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4030 return PackageManager.SIGNATURE_NO_MATCH; 4031 } 4032 4033 String msg = null; 4034 try { 4035 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4036 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4037 + scannedPkg.packageName); 4038 return PackageManager.SIGNATURE_MATCH; 4039 } 4040 } catch (CertificateException e) { 4041 msg = e.getMessage(); 4042 } 4043 4044 logCriticalInfo(Log.INFO, 4045 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4046 return PackageManager.SIGNATURE_NO_MATCH; 4047 } 4048 4049 @Override 4050 public String[] getPackagesForUid(int uid) { 4051 uid = UserHandle.getAppId(uid); 4052 // reader 4053 synchronized (mPackages) { 4054 Object obj = mSettings.getUserIdLPr(uid); 4055 if (obj instanceof SharedUserSetting) { 4056 final SharedUserSetting sus = (SharedUserSetting) obj; 4057 final int N = sus.packages.size(); 4058 final String[] res = new String[N]; 4059 final Iterator<PackageSetting> it = sus.packages.iterator(); 4060 int i = 0; 4061 while (it.hasNext()) { 4062 res[i++] = it.next().name; 4063 } 4064 return res; 4065 } else if (obj instanceof PackageSetting) { 4066 final PackageSetting ps = (PackageSetting) obj; 4067 return new String[] { ps.name }; 4068 } 4069 } 4070 return null; 4071 } 4072 4073 @Override 4074 public String getNameForUid(int uid) { 4075 // reader 4076 synchronized (mPackages) { 4077 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4078 if (obj instanceof SharedUserSetting) { 4079 final SharedUserSetting sus = (SharedUserSetting) obj; 4080 return sus.name + ":" + sus.userId; 4081 } else if (obj instanceof PackageSetting) { 4082 final PackageSetting ps = (PackageSetting) obj; 4083 return ps.name; 4084 } 4085 } 4086 return null; 4087 } 4088 4089 @Override 4090 public int getUidForSharedUser(String sharedUserName) { 4091 if(sharedUserName == null) { 4092 return -1; 4093 } 4094 // reader 4095 synchronized (mPackages) { 4096 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4097 if (suid == null) { 4098 return -1; 4099 } 4100 return suid.userId; 4101 } 4102 } 4103 4104 @Override 4105 public int getFlagsForUid(int uid) { 4106 synchronized (mPackages) { 4107 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4108 if (obj instanceof SharedUserSetting) { 4109 final SharedUserSetting sus = (SharedUserSetting) obj; 4110 return sus.pkgFlags; 4111 } else if (obj instanceof PackageSetting) { 4112 final PackageSetting ps = (PackageSetting) obj; 4113 return ps.pkgFlags; 4114 } 4115 } 4116 return 0; 4117 } 4118 4119 @Override 4120 public int getPrivateFlagsForUid(int uid) { 4121 synchronized (mPackages) { 4122 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4123 if (obj instanceof SharedUserSetting) { 4124 final SharedUserSetting sus = (SharedUserSetting) obj; 4125 return sus.pkgPrivateFlags; 4126 } else if (obj instanceof PackageSetting) { 4127 final PackageSetting ps = (PackageSetting) obj; 4128 return ps.pkgPrivateFlags; 4129 } 4130 } 4131 return 0; 4132 } 4133 4134 @Override 4135 public boolean isUidPrivileged(int uid) { 4136 uid = UserHandle.getAppId(uid); 4137 // reader 4138 synchronized (mPackages) { 4139 Object obj = mSettings.getUserIdLPr(uid); 4140 if (obj instanceof SharedUserSetting) { 4141 final SharedUserSetting sus = (SharedUserSetting) obj; 4142 final Iterator<PackageSetting> it = sus.packages.iterator(); 4143 while (it.hasNext()) { 4144 if (it.next().isPrivileged()) { 4145 return true; 4146 } 4147 } 4148 } else if (obj instanceof PackageSetting) { 4149 final PackageSetting ps = (PackageSetting) obj; 4150 return ps.isPrivileged(); 4151 } 4152 } 4153 return false; 4154 } 4155 4156 @Override 4157 public String[] getAppOpPermissionPackages(String permissionName) { 4158 synchronized (mPackages) { 4159 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4160 if (pkgs == null) { 4161 return null; 4162 } 4163 return pkgs.toArray(new String[pkgs.size()]); 4164 } 4165 } 4166 4167 @Override 4168 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4169 int flags, int userId) { 4170 if (!sUserManager.exists(userId)) return null; 4171 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4172 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4173 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4174 } 4175 4176 @Override 4177 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4178 IntentFilter filter, int match, ComponentName activity) { 4179 final int userId = UserHandle.getCallingUserId(); 4180 if (DEBUG_PREFERRED) { 4181 Log.v(TAG, "setLastChosenActivity intent=" + intent 4182 + " resolvedType=" + resolvedType 4183 + " flags=" + flags 4184 + " filter=" + filter 4185 + " match=" + match 4186 + " activity=" + activity); 4187 filter.dump(new PrintStreamPrinter(System.out), " "); 4188 } 4189 intent.setComponent(null); 4190 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4191 // Find any earlier preferred or last chosen entries and nuke them 4192 findPreferredActivity(intent, resolvedType, 4193 flags, query, 0, false, true, false, userId); 4194 // Add the new activity as the last chosen for this filter 4195 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4196 "Setting last chosen"); 4197 } 4198 4199 @Override 4200 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4201 final int userId = UserHandle.getCallingUserId(); 4202 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4203 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4204 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4205 false, false, false, userId); 4206 } 4207 4208 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4209 int flags, List<ResolveInfo> query, int userId) { 4210 if (query != null) { 4211 final int N = query.size(); 4212 if (N == 1) { 4213 return query.get(0); 4214 } else if (N > 1) { 4215 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4216 // If there is more than one activity with the same priority, 4217 // then let the user decide between them. 4218 ResolveInfo r0 = query.get(0); 4219 ResolveInfo r1 = query.get(1); 4220 if (DEBUG_INTENT_MATCHING || debug) { 4221 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4222 + r1.activityInfo.name + "=" + r1.priority); 4223 } 4224 // If the first activity has a higher priority, or a different 4225 // default, then it is always desireable to pick it. 4226 if (r0.priority != r1.priority 4227 || r0.preferredOrder != r1.preferredOrder 4228 || r0.isDefault != r1.isDefault) { 4229 return query.get(0); 4230 } 4231 // If we have saved a preference for a preferred activity for 4232 // this Intent, use that. 4233 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4234 flags, query, r0.priority, true, false, debug, userId); 4235 if (ri != null) { 4236 return ri; 4237 } 4238 ri = new ResolveInfo(mResolveInfo); 4239 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4240 ri.activityInfo.applicationInfo = new ApplicationInfo( 4241 ri.activityInfo.applicationInfo); 4242 if (userId != 0) { 4243 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4244 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4245 } 4246 // Make sure that the resolver is displayable in car mode 4247 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4248 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4249 return ri; 4250 } 4251 } 4252 return null; 4253 } 4254 4255 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4256 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4257 final int N = query.size(); 4258 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4259 .get(userId); 4260 // Get the list of persistent preferred activities that handle the intent 4261 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4262 List<PersistentPreferredActivity> pprefs = ppir != null 4263 ? ppir.queryIntent(intent, resolvedType, 4264 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4265 : null; 4266 if (pprefs != null && pprefs.size() > 0) { 4267 final int M = pprefs.size(); 4268 for (int i=0; i<M; i++) { 4269 final PersistentPreferredActivity ppa = pprefs.get(i); 4270 if (DEBUG_PREFERRED || debug) { 4271 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4272 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4273 + "\n component=" + ppa.mComponent); 4274 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4275 } 4276 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4277 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4278 if (DEBUG_PREFERRED || debug) { 4279 Slog.v(TAG, "Found persistent preferred activity:"); 4280 if (ai != null) { 4281 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4282 } else { 4283 Slog.v(TAG, " null"); 4284 } 4285 } 4286 if (ai == null) { 4287 // This previously registered persistent preferred activity 4288 // component is no longer known. Ignore it and do NOT remove it. 4289 continue; 4290 } 4291 for (int j=0; j<N; j++) { 4292 final ResolveInfo ri = query.get(j); 4293 if (!ri.activityInfo.applicationInfo.packageName 4294 .equals(ai.applicationInfo.packageName)) { 4295 continue; 4296 } 4297 if (!ri.activityInfo.name.equals(ai.name)) { 4298 continue; 4299 } 4300 // Found a persistent preference that can handle the intent. 4301 if (DEBUG_PREFERRED || debug) { 4302 Slog.v(TAG, "Returning persistent preferred activity: " + 4303 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4304 } 4305 return ri; 4306 } 4307 } 4308 } 4309 return null; 4310 } 4311 4312 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4313 List<ResolveInfo> query, int priority, boolean always, 4314 boolean removeMatches, boolean debug, int userId) { 4315 if (!sUserManager.exists(userId)) return null; 4316 // writer 4317 synchronized (mPackages) { 4318 if (intent.getSelector() != null) { 4319 intent = intent.getSelector(); 4320 } 4321 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4322 4323 // Try to find a matching persistent preferred activity. 4324 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4325 debug, userId); 4326 4327 // If a persistent preferred activity matched, use it. 4328 if (pri != null) { 4329 return pri; 4330 } 4331 4332 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4333 // Get the list of preferred activities that handle the intent 4334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4335 List<PreferredActivity> prefs = pir != null 4336 ? pir.queryIntent(intent, resolvedType, 4337 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4338 : null; 4339 if (prefs != null && prefs.size() > 0) { 4340 boolean changed = false; 4341 try { 4342 // First figure out how good the original match set is. 4343 // We will only allow preferred activities that came 4344 // from the same match quality. 4345 int match = 0; 4346 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4348 4349 final int N = query.size(); 4350 for (int j=0; j<N; j++) { 4351 final ResolveInfo ri = query.get(j); 4352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4353 + ": 0x" + Integer.toHexString(match)); 4354 if (ri.match > match) { 4355 match = ri.match; 4356 } 4357 } 4358 4359 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4360 + Integer.toHexString(match)); 4361 4362 match &= IntentFilter.MATCH_CATEGORY_MASK; 4363 final int M = prefs.size(); 4364 for (int i=0; i<M; i++) { 4365 final PreferredActivity pa = prefs.get(i); 4366 if (DEBUG_PREFERRED || debug) { 4367 Slog.v(TAG, "Checking PreferredActivity ds=" 4368 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4369 + "\n component=" + pa.mPref.mComponent); 4370 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4371 } 4372 if (pa.mPref.mMatch != match) { 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4374 + Integer.toHexString(pa.mPref.mMatch)); 4375 continue; 4376 } 4377 // If it's not an "always" type preferred activity and that's what we're 4378 // looking for, skip it. 4379 if (always && !pa.mPref.mAlways) { 4380 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4381 continue; 4382 } 4383 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4384 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4385 if (DEBUG_PREFERRED || debug) { 4386 Slog.v(TAG, "Found preferred activity:"); 4387 if (ai != null) { 4388 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4389 } else { 4390 Slog.v(TAG, " null"); 4391 } 4392 } 4393 if (ai == null) { 4394 // This previously registered preferred activity 4395 // component is no longer known. Most likely an update 4396 // to the app was installed and in the new version this 4397 // component no longer exists. Clean it up by removing 4398 // it from the preferred activities list, and skip it. 4399 Slog.w(TAG, "Removing dangling preferred activity: " 4400 + pa.mPref.mComponent); 4401 pir.removeFilter(pa); 4402 changed = true; 4403 continue; 4404 } 4405 for (int j=0; j<N; j++) { 4406 final ResolveInfo ri = query.get(j); 4407 if (!ri.activityInfo.applicationInfo.packageName 4408 .equals(ai.applicationInfo.packageName)) { 4409 continue; 4410 } 4411 if (!ri.activityInfo.name.equals(ai.name)) { 4412 continue; 4413 } 4414 4415 if (removeMatches) { 4416 pir.removeFilter(pa); 4417 changed = true; 4418 if (DEBUG_PREFERRED) { 4419 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4420 } 4421 break; 4422 } 4423 4424 // Okay we found a previously set preferred or last chosen app. 4425 // If the result set is different from when this 4426 // was created, we need to clear it and re-ask the 4427 // user their preference, if we're looking for an "always" type entry. 4428 if (always && !pa.mPref.sameSet(query)) { 4429 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4430 + intent + " type " + resolvedType); 4431 if (DEBUG_PREFERRED) { 4432 Slog.v(TAG, "Removing preferred activity since set changed " 4433 + pa.mPref.mComponent); 4434 } 4435 pir.removeFilter(pa); 4436 // Re-add the filter as a "last chosen" entry (!always) 4437 PreferredActivity lastChosen = new PreferredActivity( 4438 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4439 pir.addFilter(lastChosen); 4440 changed = true; 4441 return null; 4442 } 4443 4444 // Yay! Either the set matched or we're looking for the last chosen 4445 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4446 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4447 return ri; 4448 } 4449 } 4450 } finally { 4451 if (changed) { 4452 if (DEBUG_PREFERRED) { 4453 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4454 } 4455 scheduleWritePackageRestrictionsLocked(userId); 4456 } 4457 } 4458 } 4459 } 4460 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4461 return null; 4462 } 4463 4464 /* 4465 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4466 */ 4467 @Override 4468 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4469 int targetUserId) { 4470 mContext.enforceCallingOrSelfPermission( 4471 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4472 List<CrossProfileIntentFilter> matches = 4473 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4474 if (matches != null) { 4475 int size = matches.size(); 4476 for (int i = 0; i < size; i++) { 4477 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4478 } 4479 } 4480 if (hasWebURI(intent)) { 4481 // cross-profile app linking works only towards the parent. 4482 final UserInfo parent = getProfileParent(sourceUserId); 4483 synchronized(mPackages) { 4484 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4485 intent, resolvedType, 0, sourceUserId, parent.id); 4486 return xpDomainInfo != null; 4487 } 4488 } 4489 return false; 4490 } 4491 4492 private UserInfo getProfileParent(int userId) { 4493 final long identity = Binder.clearCallingIdentity(); 4494 try { 4495 return sUserManager.getProfileParent(userId); 4496 } finally { 4497 Binder.restoreCallingIdentity(identity); 4498 } 4499 } 4500 4501 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4502 String resolvedType, int userId) { 4503 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4504 if (resolver != null) { 4505 return resolver.queryIntent(intent, resolvedType, false, userId); 4506 } 4507 return null; 4508 } 4509 4510 @Override 4511 public List<ResolveInfo> queryIntentActivities(Intent intent, 4512 String resolvedType, int flags, int userId) { 4513 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4514 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4515 ComponentName comp = intent.getComponent(); 4516 if (comp == null) { 4517 if (intent.getSelector() != null) { 4518 intent = intent.getSelector(); 4519 comp = intent.getComponent(); 4520 } 4521 } 4522 4523 if (comp != null) { 4524 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4525 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4526 if (ai != null) { 4527 final ResolveInfo ri = new ResolveInfo(); 4528 ri.activityInfo = ai; 4529 list.add(ri); 4530 } 4531 return list; 4532 } 4533 4534 // reader 4535 synchronized (mPackages) { 4536 final String pkgName = intent.getPackage(); 4537 if (pkgName == null) { 4538 List<CrossProfileIntentFilter> matchingFilters = 4539 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4540 // Check for results that need to skip the current profile. 4541 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4542 resolvedType, flags, userId); 4543 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4544 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4545 result.add(xpResolveInfo); 4546 return filterIfNotPrimaryUser(result, userId); 4547 } 4548 4549 // Check for results in the current profile. 4550 List<ResolveInfo> result = mActivities.queryIntent( 4551 intent, resolvedType, flags, userId); 4552 4553 // Check for cross profile results. 4554 xpResolveInfo = queryCrossProfileIntents( 4555 matchingFilters, intent, resolvedType, flags, userId); 4556 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4557 result.add(xpResolveInfo); 4558 Collections.sort(result, mResolvePrioritySorter); 4559 } 4560 result = filterIfNotPrimaryUser(result, userId); 4561 if (hasWebURI(intent)) { 4562 CrossProfileDomainInfo xpDomainInfo = null; 4563 final UserInfo parent = getProfileParent(userId); 4564 if (parent != null) { 4565 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4566 flags, userId, parent.id); 4567 } 4568 if (xpDomainInfo != null) { 4569 if (xpResolveInfo != null) { 4570 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4571 // in the result. 4572 result.remove(xpResolveInfo); 4573 } 4574 if (result.size() == 0) { 4575 result.add(xpDomainInfo.resolveInfo); 4576 return result; 4577 } 4578 } else if (result.size() <= 1) { 4579 return result; 4580 } 4581 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4582 xpDomainInfo, userId); 4583 Collections.sort(result, mResolvePrioritySorter); 4584 } 4585 return result; 4586 } 4587 final PackageParser.Package pkg = mPackages.get(pkgName); 4588 if (pkg != null) { 4589 return filterIfNotPrimaryUser( 4590 mActivities.queryIntentForPackage( 4591 intent, resolvedType, flags, pkg.activities, userId), 4592 userId); 4593 } 4594 return new ArrayList<ResolveInfo>(); 4595 } 4596 } 4597 4598 private static class CrossProfileDomainInfo { 4599 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4600 ResolveInfo resolveInfo; 4601 /* Best domain verification status of the activities found in the other profile */ 4602 int bestDomainVerificationStatus; 4603 } 4604 4605 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4606 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4607 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4608 sourceUserId)) { 4609 return null; 4610 } 4611 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4612 resolvedType, flags, parentUserId); 4613 4614 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4615 return null; 4616 } 4617 CrossProfileDomainInfo result = null; 4618 int size = resultTargetUser.size(); 4619 for (int i = 0; i < size; i++) { 4620 ResolveInfo riTargetUser = resultTargetUser.get(i); 4621 // Intent filter verification is only for filters that specify a host. So don't return 4622 // those that handle all web uris. 4623 if (riTargetUser.handleAllWebDataURI) { 4624 continue; 4625 } 4626 String packageName = riTargetUser.activityInfo.packageName; 4627 PackageSetting ps = mSettings.mPackages.get(packageName); 4628 if (ps == null) { 4629 continue; 4630 } 4631 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4632 int status = (int)(verificationState >> 32); 4633 if (result == null) { 4634 result = new CrossProfileDomainInfo(); 4635 result.resolveInfo = 4636 createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId); 4637 result.bestDomainVerificationStatus = status; 4638 } else { 4639 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4640 result.bestDomainVerificationStatus); 4641 } 4642 } 4643 // Don't consider matches with status NEVER across profiles. 4644 if (result != null && result.bestDomainVerificationStatus 4645 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4646 return null; 4647 } 4648 return result; 4649 } 4650 4651 /** 4652 * Verification statuses are ordered from the worse to the best, except for 4653 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4654 */ 4655 private int bestDomainVerificationStatus(int status1, int status2) { 4656 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4657 return status2; 4658 } 4659 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4660 return status1; 4661 } 4662 return (int) MathUtils.max(status1, status2); 4663 } 4664 4665 private boolean isUserEnabled(int userId) { 4666 long callingId = Binder.clearCallingIdentity(); 4667 try { 4668 UserInfo userInfo = sUserManager.getUserInfo(userId); 4669 return userInfo != null && userInfo.isEnabled(); 4670 } finally { 4671 Binder.restoreCallingIdentity(callingId); 4672 } 4673 } 4674 4675 /** 4676 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4677 * 4678 * @return filtered list 4679 */ 4680 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4681 if (userId == UserHandle.USER_OWNER) { 4682 return resolveInfos; 4683 } 4684 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4685 ResolveInfo info = resolveInfos.get(i); 4686 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4687 resolveInfos.remove(i); 4688 } 4689 } 4690 return resolveInfos; 4691 } 4692 4693 private static boolean hasWebURI(Intent intent) { 4694 if (intent.getData() == null) { 4695 return false; 4696 } 4697 final String scheme = intent.getScheme(); 4698 if (TextUtils.isEmpty(scheme)) { 4699 return false; 4700 } 4701 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4702 } 4703 4704 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4705 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4706 int userId) { 4707 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4708 4709 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4710 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4711 candidates.size()); 4712 } 4713 4714 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4715 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4716 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4717 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4718 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4719 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4720 4721 synchronized (mPackages) { 4722 final int count = candidates.size(); 4723 // First, try to use linked apps. Partition the candidates into four lists: 4724 // one for the final results, one for the "do not use ever", one for "undefined status" 4725 // and finally one for "browser app type". 4726 for (int n=0; n<count; n++) { 4727 ResolveInfo info = candidates.get(n); 4728 String packageName = info.activityInfo.packageName; 4729 PackageSetting ps = mSettings.mPackages.get(packageName); 4730 if (ps != null) { 4731 // Add to the special match all list (Browser use case) 4732 if (info.handleAllWebDataURI) { 4733 matchAllList.add(info); 4734 continue; 4735 } 4736 // Try to get the status from User settings first 4737 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4738 int status = (int)(packedStatus >> 32); 4739 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4740 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4741 if (DEBUG_DOMAIN_VERIFICATION) { 4742 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4743 + " : linkgen=" + linkGeneration); 4744 } 4745 // Use link-enabled generation as preferredOrder, i.e. 4746 // prefer newly-enabled over earlier-enabled. 4747 info.preferredOrder = linkGeneration; 4748 alwaysList.add(info); 4749 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4750 if (DEBUG_DOMAIN_VERIFICATION) { 4751 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4752 } 4753 neverList.add(info); 4754 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4755 if (DEBUG_DOMAIN_VERIFICATION) { 4756 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4757 } 4758 alwaysAskList.add(info); 4759 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4760 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4761 if (DEBUG_DOMAIN_VERIFICATION) { 4762 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4763 } 4764 undefinedList.add(info); 4765 } 4766 } 4767 } 4768 4769 // We'll want to include browser possibilities in a few cases 4770 boolean includeBrowser = false; 4771 4772 // First try to add the "always" resolution(s) for the current user, if any 4773 if (alwaysList.size() > 0) { 4774 result.addAll(alwaysList); 4775 // if there is an "always" for the parent user, add it. 4776 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4777 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4778 result.add(xpDomainInfo.resolveInfo); 4779 } else { 4780 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4781 result.addAll(undefinedList); 4782 if (xpDomainInfo != null && ( 4783 xpDomainInfo.bestDomainVerificationStatus 4784 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4785 || xpDomainInfo.bestDomainVerificationStatus 4786 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4787 result.add(xpDomainInfo.resolveInfo); 4788 } 4789 includeBrowser = true; 4790 } 4791 4792 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4793 // If there were 'always' entries their preferred order has been set, so we also 4794 // back that off to make the alternatives equivalent 4795 if (alwaysAskList.size() > 0) { 4796 for (ResolveInfo i : result) { 4797 i.preferredOrder = 0; 4798 } 4799 result.addAll(alwaysAskList); 4800 includeBrowser = true; 4801 } 4802 4803 if (includeBrowser) { 4804 // Also add browsers (all of them or only the default one) 4805 if (DEBUG_DOMAIN_VERIFICATION) { 4806 Slog.v(TAG, " ...including browsers in candidate set"); 4807 } 4808 if ((matchFlags & MATCH_ALL) != 0) { 4809 result.addAll(matchAllList); 4810 } else { 4811 // Browser/generic handling case. If there's a default browser, go straight 4812 // to that (but only if there is no other higher-priority match). 4813 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4814 int maxMatchPrio = 0; 4815 ResolveInfo defaultBrowserMatch = null; 4816 final int numCandidates = matchAllList.size(); 4817 for (int n = 0; n < numCandidates; n++) { 4818 ResolveInfo info = matchAllList.get(n); 4819 // track the highest overall match priority... 4820 if (info.priority > maxMatchPrio) { 4821 maxMatchPrio = info.priority; 4822 } 4823 // ...and the highest-priority default browser match 4824 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4825 if (defaultBrowserMatch == null 4826 || (defaultBrowserMatch.priority < info.priority)) { 4827 if (debug) { 4828 Slog.v(TAG, "Considering default browser match " + info); 4829 } 4830 defaultBrowserMatch = info; 4831 } 4832 } 4833 } 4834 if (defaultBrowserMatch != null 4835 && defaultBrowserMatch.priority >= maxMatchPrio 4836 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4837 { 4838 if (debug) { 4839 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4840 } 4841 result.add(defaultBrowserMatch); 4842 } else { 4843 result.addAll(matchAllList); 4844 } 4845 } 4846 4847 // If there is nothing selected, add all candidates and remove the ones that the user 4848 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4849 if (result.size() == 0) { 4850 result.addAll(candidates); 4851 result.removeAll(neverList); 4852 } 4853 } 4854 } 4855 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4856 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4857 result.size()); 4858 for (ResolveInfo info : result) { 4859 Slog.v(TAG, " + " + info.activityInfo); 4860 } 4861 } 4862 return result; 4863 } 4864 4865 // Returns a packed value as a long: 4866 // 4867 // high 'int'-sized word: link status: undefined/ask/never/always. 4868 // low 'int'-sized word: relative priority among 'always' results. 4869 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4870 long result = ps.getDomainVerificationStatusForUser(userId); 4871 // if none available, get the master status 4872 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4873 if (ps.getIntentFilterVerificationInfo() != null) { 4874 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4875 } 4876 } 4877 return result; 4878 } 4879 4880 private ResolveInfo querySkipCurrentProfileIntents( 4881 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4882 int flags, int sourceUserId) { 4883 if (matchingFilters != null) { 4884 int size = matchingFilters.size(); 4885 for (int i = 0; i < size; i ++) { 4886 CrossProfileIntentFilter filter = matchingFilters.get(i); 4887 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4888 // Checking if there are activities in the target user that can handle the 4889 // intent. 4890 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4891 flags, sourceUserId); 4892 if (resolveInfo != null) { 4893 return resolveInfo; 4894 } 4895 } 4896 } 4897 } 4898 return null; 4899 } 4900 4901 // Return matching ResolveInfo if any for skip current profile intent filters. 4902 private ResolveInfo queryCrossProfileIntents( 4903 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4904 int flags, int sourceUserId) { 4905 if (matchingFilters != null) { 4906 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4907 // match the same intent. For performance reasons, it is better not to 4908 // run queryIntent twice for the same userId 4909 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4910 int size = matchingFilters.size(); 4911 for (int i = 0; i < size; i++) { 4912 CrossProfileIntentFilter filter = matchingFilters.get(i); 4913 int targetUserId = filter.getTargetUserId(); 4914 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4915 && !alreadyTriedUserIds.get(targetUserId)) { 4916 // Checking if there are activities in the target user that can handle the 4917 // intent. 4918 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4919 flags, sourceUserId); 4920 if (resolveInfo != null) return resolveInfo; 4921 alreadyTriedUserIds.put(targetUserId, true); 4922 } 4923 } 4924 } 4925 return null; 4926 } 4927 4928 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4929 String resolvedType, int flags, int sourceUserId) { 4930 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4931 resolvedType, flags, filter.getTargetUserId()); 4932 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4933 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4934 } 4935 return null; 4936 } 4937 4938 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4939 int sourceUserId, int targetUserId) { 4940 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4941 String className; 4942 if (targetUserId == UserHandle.USER_OWNER) { 4943 className = FORWARD_INTENT_TO_USER_OWNER; 4944 } else { 4945 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4946 } 4947 ComponentName forwardingActivityComponentName = new ComponentName( 4948 mAndroidApplication.packageName, className); 4949 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4950 sourceUserId); 4951 if (targetUserId == UserHandle.USER_OWNER) { 4952 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4953 forwardingResolveInfo.noResourceId = true; 4954 } 4955 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4956 forwardingResolveInfo.priority = 0; 4957 forwardingResolveInfo.preferredOrder = 0; 4958 forwardingResolveInfo.match = 0; 4959 forwardingResolveInfo.isDefault = true; 4960 forwardingResolveInfo.filter = filter; 4961 forwardingResolveInfo.targetUserId = targetUserId; 4962 return forwardingResolveInfo; 4963 } 4964 4965 @Override 4966 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4967 Intent[] specifics, String[] specificTypes, Intent intent, 4968 String resolvedType, int flags, int userId) { 4969 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4970 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4971 false, "query intent activity options"); 4972 final String resultsAction = intent.getAction(); 4973 4974 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4975 | PackageManager.GET_RESOLVED_FILTER, userId); 4976 4977 if (DEBUG_INTENT_MATCHING) { 4978 Log.v(TAG, "Query " + intent + ": " + results); 4979 } 4980 4981 int specificsPos = 0; 4982 int N; 4983 4984 // todo: note that the algorithm used here is O(N^2). This 4985 // isn't a problem in our current environment, but if we start running 4986 // into situations where we have more than 5 or 10 matches then this 4987 // should probably be changed to something smarter... 4988 4989 // First we go through and resolve each of the specific items 4990 // that were supplied, taking care of removing any corresponding 4991 // duplicate items in the generic resolve list. 4992 if (specifics != null) { 4993 for (int i=0; i<specifics.length; i++) { 4994 final Intent sintent = specifics[i]; 4995 if (sintent == null) { 4996 continue; 4997 } 4998 4999 if (DEBUG_INTENT_MATCHING) { 5000 Log.v(TAG, "Specific #" + i + ": " + sintent); 5001 } 5002 5003 String action = sintent.getAction(); 5004 if (resultsAction != null && resultsAction.equals(action)) { 5005 // If this action was explicitly requested, then don't 5006 // remove things that have it. 5007 action = null; 5008 } 5009 5010 ResolveInfo ri = null; 5011 ActivityInfo ai = null; 5012 5013 ComponentName comp = sintent.getComponent(); 5014 if (comp == null) { 5015 ri = resolveIntent( 5016 sintent, 5017 specificTypes != null ? specificTypes[i] : null, 5018 flags, userId); 5019 if (ri == null) { 5020 continue; 5021 } 5022 if (ri == mResolveInfo) { 5023 // ACK! Must do something better with this. 5024 } 5025 ai = ri.activityInfo; 5026 comp = new ComponentName(ai.applicationInfo.packageName, 5027 ai.name); 5028 } else { 5029 ai = getActivityInfo(comp, flags, userId); 5030 if (ai == null) { 5031 continue; 5032 } 5033 } 5034 5035 // Look for any generic query activities that are duplicates 5036 // of this specific one, and remove them from the results. 5037 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5038 N = results.size(); 5039 int j; 5040 for (j=specificsPos; j<N; j++) { 5041 ResolveInfo sri = results.get(j); 5042 if ((sri.activityInfo.name.equals(comp.getClassName()) 5043 && sri.activityInfo.applicationInfo.packageName.equals( 5044 comp.getPackageName())) 5045 || (action != null && sri.filter.matchAction(action))) { 5046 results.remove(j); 5047 if (DEBUG_INTENT_MATCHING) Log.v( 5048 TAG, "Removing duplicate item from " + j 5049 + " due to specific " + specificsPos); 5050 if (ri == null) { 5051 ri = sri; 5052 } 5053 j--; 5054 N--; 5055 } 5056 } 5057 5058 // Add this specific item to its proper place. 5059 if (ri == null) { 5060 ri = new ResolveInfo(); 5061 ri.activityInfo = ai; 5062 } 5063 results.add(specificsPos, ri); 5064 ri.specificIndex = i; 5065 specificsPos++; 5066 } 5067 } 5068 5069 // Now we go through the remaining generic results and remove any 5070 // duplicate actions that are found here. 5071 N = results.size(); 5072 for (int i=specificsPos; i<N-1; i++) { 5073 final ResolveInfo rii = results.get(i); 5074 if (rii.filter == null) { 5075 continue; 5076 } 5077 5078 // Iterate over all of the actions of this result's intent 5079 // filter... typically this should be just one. 5080 final Iterator<String> it = rii.filter.actionsIterator(); 5081 if (it == null) { 5082 continue; 5083 } 5084 while (it.hasNext()) { 5085 final String action = it.next(); 5086 if (resultsAction != null && resultsAction.equals(action)) { 5087 // If this action was explicitly requested, then don't 5088 // remove things that have it. 5089 continue; 5090 } 5091 for (int j=i+1; j<N; j++) { 5092 final ResolveInfo rij = results.get(j); 5093 if (rij.filter != null && rij.filter.hasAction(action)) { 5094 results.remove(j); 5095 if (DEBUG_INTENT_MATCHING) Log.v( 5096 TAG, "Removing duplicate item from " + j 5097 + " due to action " + action + " at " + i); 5098 j--; 5099 N--; 5100 } 5101 } 5102 } 5103 5104 // If the caller didn't request filter information, drop it now 5105 // so we don't have to marshall/unmarshall it. 5106 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5107 rii.filter = null; 5108 } 5109 } 5110 5111 // Filter out the caller activity if so requested. 5112 if (caller != null) { 5113 N = results.size(); 5114 for (int i=0; i<N; i++) { 5115 ActivityInfo ainfo = results.get(i).activityInfo; 5116 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5117 && caller.getClassName().equals(ainfo.name)) { 5118 results.remove(i); 5119 break; 5120 } 5121 } 5122 } 5123 5124 // If the caller didn't request filter information, 5125 // drop them now so we don't have to 5126 // marshall/unmarshall it. 5127 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5128 N = results.size(); 5129 for (int i=0; i<N; i++) { 5130 results.get(i).filter = null; 5131 } 5132 } 5133 5134 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5135 return results; 5136 } 5137 5138 @Override 5139 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5140 int userId) { 5141 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5142 ComponentName comp = intent.getComponent(); 5143 if (comp == null) { 5144 if (intent.getSelector() != null) { 5145 intent = intent.getSelector(); 5146 comp = intent.getComponent(); 5147 } 5148 } 5149 if (comp != null) { 5150 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5151 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5152 if (ai != null) { 5153 ResolveInfo ri = new ResolveInfo(); 5154 ri.activityInfo = ai; 5155 list.add(ri); 5156 } 5157 return list; 5158 } 5159 5160 // reader 5161 synchronized (mPackages) { 5162 String pkgName = intent.getPackage(); 5163 if (pkgName == null) { 5164 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5165 } 5166 final PackageParser.Package pkg = mPackages.get(pkgName); 5167 if (pkg != null) { 5168 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5169 userId); 5170 } 5171 return null; 5172 } 5173 } 5174 5175 @Override 5176 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5177 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5178 if (!sUserManager.exists(userId)) return null; 5179 if (query != null) { 5180 if (query.size() >= 1) { 5181 // If there is more than one service with the same priority, 5182 // just arbitrarily pick the first one. 5183 return query.get(0); 5184 } 5185 } 5186 return null; 5187 } 5188 5189 @Override 5190 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5191 int userId) { 5192 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5193 ComponentName comp = intent.getComponent(); 5194 if (comp == null) { 5195 if (intent.getSelector() != null) { 5196 intent = intent.getSelector(); 5197 comp = intent.getComponent(); 5198 } 5199 } 5200 if (comp != null) { 5201 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5202 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5203 if (si != null) { 5204 final ResolveInfo ri = new ResolveInfo(); 5205 ri.serviceInfo = si; 5206 list.add(ri); 5207 } 5208 return list; 5209 } 5210 5211 // reader 5212 synchronized (mPackages) { 5213 String pkgName = intent.getPackage(); 5214 if (pkgName == null) { 5215 return mServices.queryIntent(intent, resolvedType, flags, userId); 5216 } 5217 final PackageParser.Package pkg = mPackages.get(pkgName); 5218 if (pkg != null) { 5219 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5220 userId); 5221 } 5222 return null; 5223 } 5224 } 5225 5226 @Override 5227 public List<ResolveInfo> queryIntentContentProviders( 5228 Intent intent, String resolvedType, int flags, int userId) { 5229 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5230 ComponentName comp = intent.getComponent(); 5231 if (comp == null) { 5232 if (intent.getSelector() != null) { 5233 intent = intent.getSelector(); 5234 comp = intent.getComponent(); 5235 } 5236 } 5237 if (comp != null) { 5238 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5239 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5240 if (pi != null) { 5241 final ResolveInfo ri = new ResolveInfo(); 5242 ri.providerInfo = pi; 5243 list.add(ri); 5244 } 5245 return list; 5246 } 5247 5248 // reader 5249 synchronized (mPackages) { 5250 String pkgName = intent.getPackage(); 5251 if (pkgName == null) { 5252 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5253 } 5254 final PackageParser.Package pkg = mPackages.get(pkgName); 5255 if (pkg != null) { 5256 return mProviders.queryIntentForPackage( 5257 intent, resolvedType, flags, pkg.providers, userId); 5258 } 5259 return null; 5260 } 5261 } 5262 5263 @Override 5264 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5265 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5266 5267 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5268 5269 // writer 5270 synchronized (mPackages) { 5271 ArrayList<PackageInfo> list; 5272 if (listUninstalled) { 5273 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5274 for (PackageSetting ps : mSettings.mPackages.values()) { 5275 PackageInfo pi; 5276 if (ps.pkg != null) { 5277 pi = generatePackageInfo(ps.pkg, flags, userId); 5278 } else { 5279 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5280 } 5281 if (pi != null) { 5282 list.add(pi); 5283 } 5284 } 5285 } else { 5286 list = new ArrayList<PackageInfo>(mPackages.size()); 5287 for (PackageParser.Package p : mPackages.values()) { 5288 PackageInfo pi = generatePackageInfo(p, flags, userId); 5289 if (pi != null) { 5290 list.add(pi); 5291 } 5292 } 5293 } 5294 5295 return new ParceledListSlice<PackageInfo>(list); 5296 } 5297 } 5298 5299 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5300 String[] permissions, boolean[] tmp, int flags, int userId) { 5301 int numMatch = 0; 5302 final PermissionsState permissionsState = ps.getPermissionsState(); 5303 for (int i=0; i<permissions.length; i++) { 5304 final String permission = permissions[i]; 5305 if (permissionsState.hasPermission(permission, userId)) { 5306 tmp[i] = true; 5307 numMatch++; 5308 } else { 5309 tmp[i] = false; 5310 } 5311 } 5312 if (numMatch == 0) { 5313 return; 5314 } 5315 PackageInfo pi; 5316 if (ps.pkg != null) { 5317 pi = generatePackageInfo(ps.pkg, flags, userId); 5318 } else { 5319 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5320 } 5321 // The above might return null in cases of uninstalled apps or install-state 5322 // skew across users/profiles. 5323 if (pi != null) { 5324 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5325 if (numMatch == permissions.length) { 5326 pi.requestedPermissions = permissions; 5327 } else { 5328 pi.requestedPermissions = new String[numMatch]; 5329 numMatch = 0; 5330 for (int i=0; i<permissions.length; i++) { 5331 if (tmp[i]) { 5332 pi.requestedPermissions[numMatch] = permissions[i]; 5333 numMatch++; 5334 } 5335 } 5336 } 5337 } 5338 list.add(pi); 5339 } 5340 } 5341 5342 @Override 5343 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5344 String[] permissions, int flags, int userId) { 5345 if (!sUserManager.exists(userId)) return null; 5346 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5347 5348 // writer 5349 synchronized (mPackages) { 5350 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5351 boolean[] tmpBools = new boolean[permissions.length]; 5352 if (listUninstalled) { 5353 for (PackageSetting ps : mSettings.mPackages.values()) { 5354 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5355 } 5356 } else { 5357 for (PackageParser.Package pkg : mPackages.values()) { 5358 PackageSetting ps = (PackageSetting)pkg.mExtras; 5359 if (ps != null) { 5360 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5361 userId); 5362 } 5363 } 5364 } 5365 5366 return new ParceledListSlice<PackageInfo>(list); 5367 } 5368 } 5369 5370 @Override 5371 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5372 if (!sUserManager.exists(userId)) return null; 5373 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5374 5375 // writer 5376 synchronized (mPackages) { 5377 ArrayList<ApplicationInfo> list; 5378 if (listUninstalled) { 5379 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5380 for (PackageSetting ps : mSettings.mPackages.values()) { 5381 ApplicationInfo ai; 5382 if (ps.pkg != null) { 5383 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5384 ps.readUserState(userId), userId); 5385 } else { 5386 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5387 } 5388 if (ai != null) { 5389 list.add(ai); 5390 } 5391 } 5392 } else { 5393 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5394 for (PackageParser.Package p : mPackages.values()) { 5395 if (p.mExtras != null) { 5396 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5397 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5398 if (ai != null) { 5399 list.add(ai); 5400 } 5401 } 5402 } 5403 } 5404 5405 return new ParceledListSlice<ApplicationInfo>(list); 5406 } 5407 } 5408 5409 public List<ApplicationInfo> getPersistentApplications(int flags) { 5410 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5411 5412 // reader 5413 synchronized (mPackages) { 5414 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5415 final int userId = UserHandle.getCallingUserId(); 5416 while (i.hasNext()) { 5417 final PackageParser.Package p = i.next(); 5418 if (p.applicationInfo != null 5419 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5420 && (!mSafeMode || isSystemApp(p))) { 5421 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5422 if (ps != null) { 5423 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5424 ps.readUserState(userId), userId); 5425 if (ai != null) { 5426 finalList.add(ai); 5427 } 5428 } 5429 } 5430 } 5431 } 5432 5433 return finalList; 5434 } 5435 5436 @Override 5437 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5438 if (!sUserManager.exists(userId)) return null; 5439 // reader 5440 synchronized (mPackages) { 5441 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5442 PackageSetting ps = provider != null 5443 ? mSettings.mPackages.get(provider.owner.packageName) 5444 : null; 5445 return ps != null 5446 && mSettings.isEnabledLPr(provider.info, flags, userId) 5447 && (!mSafeMode || (provider.info.applicationInfo.flags 5448 &ApplicationInfo.FLAG_SYSTEM) != 0) 5449 ? PackageParser.generateProviderInfo(provider, flags, 5450 ps.readUserState(userId), userId) 5451 : null; 5452 } 5453 } 5454 5455 /** 5456 * @deprecated 5457 */ 5458 @Deprecated 5459 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5460 // reader 5461 synchronized (mPackages) { 5462 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5463 .entrySet().iterator(); 5464 final int userId = UserHandle.getCallingUserId(); 5465 while (i.hasNext()) { 5466 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5467 PackageParser.Provider p = entry.getValue(); 5468 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5469 5470 if (ps != null && p.syncable 5471 && (!mSafeMode || (p.info.applicationInfo.flags 5472 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5473 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5474 ps.readUserState(userId), userId); 5475 if (info != null) { 5476 outNames.add(entry.getKey()); 5477 outInfo.add(info); 5478 } 5479 } 5480 } 5481 } 5482 } 5483 5484 @Override 5485 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5486 int uid, int flags) { 5487 ArrayList<ProviderInfo> finalList = null; 5488 // reader 5489 synchronized (mPackages) { 5490 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5491 final int userId = processName != null ? 5492 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5493 while (i.hasNext()) { 5494 final PackageParser.Provider p = i.next(); 5495 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5496 if (ps != null && p.info.authority != null 5497 && (processName == null 5498 || (p.info.processName.equals(processName) 5499 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5500 && mSettings.isEnabledLPr(p.info, flags, userId) 5501 && (!mSafeMode 5502 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5503 if (finalList == null) { 5504 finalList = new ArrayList<ProviderInfo>(3); 5505 } 5506 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5507 ps.readUserState(userId), userId); 5508 if (info != null) { 5509 finalList.add(info); 5510 } 5511 } 5512 } 5513 } 5514 5515 if (finalList != null) { 5516 Collections.sort(finalList, mProviderInitOrderSorter); 5517 return new ParceledListSlice<ProviderInfo>(finalList); 5518 } 5519 5520 return null; 5521 } 5522 5523 @Override 5524 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5525 int flags) { 5526 // reader 5527 synchronized (mPackages) { 5528 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5529 return PackageParser.generateInstrumentationInfo(i, flags); 5530 } 5531 } 5532 5533 @Override 5534 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5535 int flags) { 5536 ArrayList<InstrumentationInfo> finalList = 5537 new ArrayList<InstrumentationInfo>(); 5538 5539 // reader 5540 synchronized (mPackages) { 5541 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5542 while (i.hasNext()) { 5543 final PackageParser.Instrumentation p = i.next(); 5544 if (targetPackage == null 5545 || targetPackage.equals(p.info.targetPackage)) { 5546 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5547 flags); 5548 if (ii != null) { 5549 finalList.add(ii); 5550 } 5551 } 5552 } 5553 } 5554 5555 return finalList; 5556 } 5557 5558 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5559 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5560 if (overlays == null) { 5561 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5562 return; 5563 } 5564 for (PackageParser.Package opkg : overlays.values()) { 5565 // Not much to do if idmap fails: we already logged the error 5566 // and we certainly don't want to abort installation of pkg simply 5567 // because an overlay didn't fit properly. For these reasons, 5568 // ignore the return value of createIdmapForPackagePairLI. 5569 createIdmapForPackagePairLI(pkg, opkg); 5570 } 5571 } 5572 5573 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5574 PackageParser.Package opkg) { 5575 if (!opkg.mTrustedOverlay) { 5576 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5577 opkg.baseCodePath + ": overlay not trusted"); 5578 return false; 5579 } 5580 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5581 if (overlaySet == null) { 5582 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5583 opkg.baseCodePath + " but target package has no known overlays"); 5584 return false; 5585 } 5586 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5587 // TODO: generate idmap for split APKs 5588 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5589 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5590 + opkg.baseCodePath); 5591 return false; 5592 } 5593 PackageParser.Package[] overlayArray = 5594 overlaySet.values().toArray(new PackageParser.Package[0]); 5595 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5596 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5597 return p1.mOverlayPriority - p2.mOverlayPriority; 5598 } 5599 }; 5600 Arrays.sort(overlayArray, cmp); 5601 5602 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5603 int i = 0; 5604 for (PackageParser.Package p : overlayArray) { 5605 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5606 } 5607 return true; 5608 } 5609 5610 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5611 final File[] files = dir.listFiles(); 5612 if (ArrayUtils.isEmpty(files)) { 5613 Log.d(TAG, "No files in app dir " + dir); 5614 return; 5615 } 5616 5617 if (DEBUG_PACKAGE_SCANNING) { 5618 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5619 + " flags=0x" + Integer.toHexString(parseFlags)); 5620 } 5621 5622 for (File file : files) { 5623 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5624 && !PackageInstallerService.isStageName(file.getName()); 5625 if (!isPackage) { 5626 // Ignore entries which are not packages 5627 continue; 5628 } 5629 try { 5630 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5631 scanFlags, currentTime, null); 5632 } catch (PackageManagerException e) { 5633 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5634 5635 // Delete invalid userdata apps 5636 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5637 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5638 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5639 if (file.isDirectory()) { 5640 mInstaller.rmPackageDir(file.getAbsolutePath()); 5641 } else { 5642 file.delete(); 5643 } 5644 } 5645 } 5646 } 5647 } 5648 5649 private static File getSettingsProblemFile() { 5650 File dataDir = Environment.getDataDirectory(); 5651 File systemDir = new File(dataDir, "system"); 5652 File fname = new File(systemDir, "uiderrors.txt"); 5653 return fname; 5654 } 5655 5656 static void reportSettingsProblem(int priority, String msg) { 5657 logCriticalInfo(priority, msg); 5658 } 5659 5660 static void logCriticalInfo(int priority, String msg) { 5661 Slog.println(priority, TAG, msg); 5662 EventLogTags.writePmCriticalInfo(msg); 5663 try { 5664 File fname = getSettingsProblemFile(); 5665 FileOutputStream out = new FileOutputStream(fname, true); 5666 PrintWriter pw = new FastPrintWriter(out); 5667 SimpleDateFormat formatter = new SimpleDateFormat(); 5668 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5669 pw.println(dateString + ": " + msg); 5670 pw.close(); 5671 FileUtils.setPermissions( 5672 fname.toString(), 5673 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5674 -1, -1); 5675 } catch (java.io.IOException e) { 5676 } 5677 } 5678 5679 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5680 PackageParser.Package pkg, File srcFile, int parseFlags) 5681 throws PackageManagerException { 5682 if (ps != null 5683 && ps.codePath.equals(srcFile) 5684 && ps.timeStamp == srcFile.lastModified() 5685 && !isCompatSignatureUpdateNeeded(pkg) 5686 && !isRecoverSignatureUpdateNeeded(pkg)) { 5687 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5688 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5689 ArraySet<PublicKey> signingKs; 5690 synchronized (mPackages) { 5691 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5692 } 5693 if (ps.signatures.mSignatures != null 5694 && ps.signatures.mSignatures.length != 0 5695 && signingKs != null) { 5696 // Optimization: reuse the existing cached certificates 5697 // if the package appears to be unchanged. 5698 pkg.mSignatures = ps.signatures.mSignatures; 5699 pkg.mSigningKeys = signingKs; 5700 return; 5701 } 5702 5703 Slog.w(TAG, "PackageSetting for " + ps.name 5704 + " is missing signatures. Collecting certs again to recover them."); 5705 } else { 5706 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5707 } 5708 5709 try { 5710 pp.collectCertificates(pkg, parseFlags); 5711 pp.collectManifestDigest(pkg); 5712 } catch (PackageParserException e) { 5713 throw PackageManagerException.from(e); 5714 } 5715 } 5716 5717 /* 5718 * Scan a package and return the newly parsed package. 5719 * Returns null in case of errors and the error code is stored in mLastScanError 5720 */ 5721 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5722 long currentTime, UserHandle user) throws PackageManagerException { 5723 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5724 parseFlags |= mDefParseFlags; 5725 PackageParser pp = new PackageParser(); 5726 pp.setSeparateProcesses(mSeparateProcesses); 5727 pp.setOnlyCoreApps(mOnlyCore); 5728 pp.setDisplayMetrics(mMetrics); 5729 5730 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5731 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5732 } 5733 5734 final PackageParser.Package pkg; 5735 try { 5736 pkg = pp.parsePackage(scanFile, parseFlags); 5737 } catch (PackageParserException e) { 5738 throw PackageManagerException.from(e); 5739 } 5740 5741 PackageSetting ps = null; 5742 PackageSetting updatedPkg; 5743 // reader 5744 synchronized (mPackages) { 5745 // Look to see if we already know about this package. 5746 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5747 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5748 // This package has been renamed to its original name. Let's 5749 // use that. 5750 ps = mSettings.peekPackageLPr(oldName); 5751 } 5752 // If there was no original package, see one for the real package name. 5753 if (ps == null) { 5754 ps = mSettings.peekPackageLPr(pkg.packageName); 5755 } 5756 // Check to see if this package could be hiding/updating a system 5757 // package. Must look for it either under the original or real 5758 // package name depending on our state. 5759 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5760 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5761 } 5762 boolean updatedPkgBetter = false; 5763 // First check if this is a system package that may involve an update 5764 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5765 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5766 // it needs to drop FLAG_PRIVILEGED. 5767 if (locationIsPrivileged(scanFile)) { 5768 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5769 } else { 5770 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5771 } 5772 5773 if (ps != null && !ps.codePath.equals(scanFile)) { 5774 // The path has changed from what was last scanned... check the 5775 // version of the new path against what we have stored to determine 5776 // what to do. 5777 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5778 if (pkg.mVersionCode <= ps.versionCode) { 5779 // The system package has been updated and the code path does not match 5780 // Ignore entry. Skip it. 5781 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5782 + " ignored: updated version " + ps.versionCode 5783 + " better than this " + pkg.mVersionCode); 5784 if (!updatedPkg.codePath.equals(scanFile)) { 5785 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5786 + ps.name + " changing from " + updatedPkg.codePathString 5787 + " to " + scanFile); 5788 updatedPkg.codePath = scanFile; 5789 updatedPkg.codePathString = scanFile.toString(); 5790 updatedPkg.resourcePath = scanFile; 5791 updatedPkg.resourcePathString = scanFile.toString(); 5792 } 5793 updatedPkg.pkg = pkg; 5794 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5795 "Package " + ps.name + " at " + scanFile 5796 + " ignored: updated version " + ps.versionCode 5797 + " better than this " + pkg.mVersionCode); 5798 } else { 5799 // The current app on the system partition is better than 5800 // what we have updated to on the data partition; switch 5801 // back to the system partition version. 5802 // At this point, its safely assumed that package installation for 5803 // apps in system partition will go through. If not there won't be a working 5804 // version of the app 5805 // writer 5806 synchronized (mPackages) { 5807 // Just remove the loaded entries from package lists. 5808 mPackages.remove(ps.name); 5809 } 5810 5811 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5812 + " reverting from " + ps.codePathString 5813 + ": new version " + pkg.mVersionCode 5814 + " better than installed " + ps.versionCode); 5815 5816 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5817 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5818 synchronized (mInstallLock) { 5819 args.cleanUpResourcesLI(); 5820 } 5821 synchronized (mPackages) { 5822 mSettings.enableSystemPackageLPw(ps.name); 5823 } 5824 updatedPkgBetter = true; 5825 } 5826 } 5827 } 5828 5829 if (updatedPkg != null) { 5830 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5831 // initially 5832 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5833 5834 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5835 // flag set initially 5836 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5837 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5838 } 5839 } 5840 5841 // Verify certificates against what was last scanned 5842 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5843 5844 /* 5845 * A new system app appeared, but we already had a non-system one of the 5846 * same name installed earlier. 5847 */ 5848 boolean shouldHideSystemApp = false; 5849 if (updatedPkg == null && ps != null 5850 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5851 /* 5852 * Check to make sure the signatures match first. If they don't, 5853 * wipe the installed application and its data. 5854 */ 5855 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5856 != PackageManager.SIGNATURE_MATCH) { 5857 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5858 + " signatures don't match existing userdata copy; removing"); 5859 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5860 ps = null; 5861 } else { 5862 /* 5863 * If the newly-added system app is an older version than the 5864 * already installed version, hide it. It will be scanned later 5865 * and re-added like an update. 5866 */ 5867 if (pkg.mVersionCode <= ps.versionCode) { 5868 shouldHideSystemApp = true; 5869 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5870 + " but new version " + pkg.mVersionCode + " better than installed " 5871 + ps.versionCode + "; hiding system"); 5872 } else { 5873 /* 5874 * The newly found system app is a newer version that the 5875 * one previously installed. Simply remove the 5876 * already-installed application and replace it with our own 5877 * while keeping the application data. 5878 */ 5879 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5880 + " reverting from " + ps.codePathString + ": new version " 5881 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5882 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5883 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5884 synchronized (mInstallLock) { 5885 args.cleanUpResourcesLI(); 5886 } 5887 } 5888 } 5889 } 5890 5891 // The apk is forward locked (not public) if its code and resources 5892 // are kept in different files. (except for app in either system or 5893 // vendor path). 5894 // TODO grab this value from PackageSettings 5895 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5896 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5897 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5898 } 5899 } 5900 5901 // TODO: extend to support forward-locked splits 5902 String resourcePath = null; 5903 String baseResourcePath = null; 5904 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5905 if (ps != null && ps.resourcePathString != null) { 5906 resourcePath = ps.resourcePathString; 5907 baseResourcePath = ps.resourcePathString; 5908 } else { 5909 // Should not happen at all. Just log an error. 5910 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5911 } 5912 } else { 5913 resourcePath = pkg.codePath; 5914 baseResourcePath = pkg.baseCodePath; 5915 } 5916 5917 // Set application objects path explicitly. 5918 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5919 pkg.applicationInfo.setCodePath(pkg.codePath); 5920 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5921 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5922 pkg.applicationInfo.setResourcePath(resourcePath); 5923 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5924 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5925 5926 // Note that we invoke the following method only if we are about to unpack an application 5927 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5928 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5929 5930 /* 5931 * If the system app should be overridden by a previously installed 5932 * data, hide the system app now and let the /data/app scan pick it up 5933 * again. 5934 */ 5935 if (shouldHideSystemApp) { 5936 synchronized (mPackages) { 5937 mSettings.disableSystemPackageLPw(pkg.packageName); 5938 } 5939 } 5940 5941 return scannedPkg; 5942 } 5943 5944 private static String fixProcessName(String defProcessName, 5945 String processName, int uid) { 5946 if (processName == null) { 5947 return defProcessName; 5948 } 5949 return processName; 5950 } 5951 5952 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5953 throws PackageManagerException { 5954 if (pkgSetting.signatures.mSignatures != null) { 5955 // Already existing package. Make sure signatures match 5956 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5957 == PackageManager.SIGNATURE_MATCH; 5958 if (!match) { 5959 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5960 == PackageManager.SIGNATURE_MATCH; 5961 } 5962 if (!match) { 5963 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5964 == PackageManager.SIGNATURE_MATCH; 5965 } 5966 if (!match) { 5967 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5968 + pkg.packageName + " signatures do not match the " 5969 + "previously installed version; ignoring!"); 5970 } 5971 } 5972 5973 // Check for shared user signatures 5974 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5975 // Already existing package. Make sure signatures match 5976 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5977 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5978 if (!match) { 5979 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5980 == PackageManager.SIGNATURE_MATCH; 5981 } 5982 if (!match) { 5983 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5984 == PackageManager.SIGNATURE_MATCH; 5985 } 5986 if (!match) { 5987 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5988 "Package " + pkg.packageName 5989 + " has no signatures that match those in shared user " 5990 + pkgSetting.sharedUser.name + "; ignoring!"); 5991 } 5992 } 5993 } 5994 5995 /** 5996 * Enforces that only the system UID or root's UID can call a method exposed 5997 * via Binder. 5998 * 5999 * @param message used as message if SecurityException is thrown 6000 * @throws SecurityException if the caller is not system or root 6001 */ 6002 private static final void enforceSystemOrRoot(String message) { 6003 final int uid = Binder.getCallingUid(); 6004 if (uid != Process.SYSTEM_UID && uid != 0) { 6005 throw new SecurityException(message); 6006 } 6007 } 6008 6009 @Override 6010 public void performBootDexOpt() { 6011 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6012 6013 // Before everything else, see whether we need to fstrim. 6014 try { 6015 IMountService ms = PackageHelper.getMountService(); 6016 if (ms != null) { 6017 final boolean isUpgrade = isUpgrade(); 6018 boolean doTrim = isUpgrade; 6019 if (doTrim) { 6020 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6021 } else { 6022 final long interval = android.provider.Settings.Global.getLong( 6023 mContext.getContentResolver(), 6024 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6025 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6026 if (interval > 0) { 6027 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6028 if (timeSinceLast > interval) { 6029 doTrim = true; 6030 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6031 + "; running immediately"); 6032 } 6033 } 6034 } 6035 if (doTrim) { 6036 if (!isFirstBoot()) { 6037 try { 6038 ActivityManagerNative.getDefault().showBootMessage( 6039 mContext.getResources().getString( 6040 R.string.android_upgrading_fstrim), true); 6041 } catch (RemoteException e) { 6042 } 6043 } 6044 ms.runMaintenance(); 6045 } 6046 } else { 6047 Slog.e(TAG, "Mount service unavailable!"); 6048 } 6049 } catch (RemoteException e) { 6050 // Can't happen; MountService is local 6051 } 6052 6053 final ArraySet<PackageParser.Package> pkgs; 6054 synchronized (mPackages) { 6055 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6056 } 6057 6058 if (pkgs != null) { 6059 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6060 // in case the device runs out of space. 6061 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6062 // Give priority to core apps. 6063 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6064 PackageParser.Package pkg = it.next(); 6065 if (pkg.coreApp) { 6066 if (DEBUG_DEXOPT) { 6067 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6068 } 6069 sortedPkgs.add(pkg); 6070 it.remove(); 6071 } 6072 } 6073 // Give priority to system apps that listen for pre boot complete. 6074 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6075 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6076 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6077 PackageParser.Package pkg = it.next(); 6078 if (pkgNames.contains(pkg.packageName)) { 6079 if (DEBUG_DEXOPT) { 6080 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6081 } 6082 sortedPkgs.add(pkg); 6083 it.remove(); 6084 } 6085 } 6086 // Filter out packages that aren't recently used. 6087 filterRecentlyUsedApps(pkgs); 6088 // Add all remaining apps. 6089 for (PackageParser.Package pkg : pkgs) { 6090 if (DEBUG_DEXOPT) { 6091 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6092 } 6093 sortedPkgs.add(pkg); 6094 } 6095 6096 // If we want to be lazy, filter everything that wasn't recently used. 6097 if (mLazyDexOpt) { 6098 filterRecentlyUsedApps(sortedPkgs); 6099 } 6100 6101 int i = 0; 6102 int total = sortedPkgs.size(); 6103 File dataDir = Environment.getDataDirectory(); 6104 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6105 if (lowThreshold == 0) { 6106 throw new IllegalStateException("Invalid low memory threshold"); 6107 } 6108 for (PackageParser.Package pkg : sortedPkgs) { 6109 long usableSpace = dataDir.getUsableSpace(); 6110 if (usableSpace < lowThreshold) { 6111 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6112 break; 6113 } 6114 performBootDexOpt(pkg, ++i, total); 6115 } 6116 } 6117 } 6118 6119 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6120 // Filter out packages that aren't recently used. 6121 // 6122 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6123 // should do a full dexopt. 6124 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6125 int total = pkgs.size(); 6126 int skipped = 0; 6127 long now = System.currentTimeMillis(); 6128 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6129 PackageParser.Package pkg = i.next(); 6130 long then = pkg.mLastPackageUsageTimeInMills; 6131 if (then + mDexOptLRUThresholdInMills < now) { 6132 if (DEBUG_DEXOPT) { 6133 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6134 ((then == 0) ? "never" : new Date(then))); 6135 } 6136 i.remove(); 6137 skipped++; 6138 } 6139 } 6140 if (DEBUG_DEXOPT) { 6141 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6142 } 6143 } 6144 } 6145 6146 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6147 List<ResolveInfo> ris = null; 6148 try { 6149 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6150 intent, null, 0, UserHandle.USER_OWNER); 6151 } catch (RemoteException e) { 6152 } 6153 ArraySet<String> pkgNames = new ArraySet<String>(); 6154 if (ris != null) { 6155 for (ResolveInfo ri : ris) { 6156 pkgNames.add(ri.activityInfo.packageName); 6157 } 6158 } 6159 return pkgNames; 6160 } 6161 6162 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6163 if (DEBUG_DEXOPT) { 6164 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6165 } 6166 if (!isFirstBoot()) { 6167 try { 6168 ActivityManagerNative.getDefault().showBootMessage( 6169 mContext.getResources().getString(R.string.android_upgrading_apk, 6170 curr, total), true); 6171 } catch (RemoteException e) { 6172 } 6173 } 6174 PackageParser.Package p = pkg; 6175 synchronized (mInstallLock) { 6176 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6177 false /* force dex */, false /* defer */, true /* include dependencies */, 6178 false /* boot complete */); 6179 } 6180 } 6181 6182 @Override 6183 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6184 return performDexOpt(packageName, instructionSet, false); 6185 } 6186 6187 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6188 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6189 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6190 if (!dexopt && !updateUsage) { 6191 // We aren't going to dexopt or update usage, so bail early. 6192 return false; 6193 } 6194 PackageParser.Package p; 6195 final String targetInstructionSet; 6196 synchronized (mPackages) { 6197 p = mPackages.get(packageName); 6198 if (p == null) { 6199 return false; 6200 } 6201 if (updateUsage) { 6202 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6203 } 6204 mPackageUsage.write(false); 6205 if (!dexopt) { 6206 // We aren't going to dexopt, so bail early. 6207 return false; 6208 } 6209 6210 targetInstructionSet = instructionSet != null ? instructionSet : 6211 getPrimaryInstructionSet(p.applicationInfo); 6212 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6213 return false; 6214 } 6215 } 6216 long callingId = Binder.clearCallingIdentity(); 6217 try { 6218 synchronized (mInstallLock) { 6219 final String[] instructionSets = new String[] { targetInstructionSet }; 6220 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6221 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6222 true /* boot complete */); 6223 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6224 } 6225 } finally { 6226 Binder.restoreCallingIdentity(callingId); 6227 } 6228 } 6229 6230 public ArraySet<String> getPackagesThatNeedDexOpt() { 6231 ArraySet<String> pkgs = null; 6232 synchronized (mPackages) { 6233 for (PackageParser.Package p : mPackages.values()) { 6234 if (DEBUG_DEXOPT) { 6235 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6236 } 6237 if (!p.mDexOptPerformed.isEmpty()) { 6238 continue; 6239 } 6240 if (pkgs == null) { 6241 pkgs = new ArraySet<String>(); 6242 } 6243 pkgs.add(p.packageName); 6244 } 6245 } 6246 return pkgs; 6247 } 6248 6249 public void shutdown() { 6250 mPackageUsage.write(true); 6251 } 6252 6253 @Override 6254 public void forceDexOpt(String packageName) { 6255 enforceSystemOrRoot("forceDexOpt"); 6256 6257 PackageParser.Package pkg; 6258 synchronized (mPackages) { 6259 pkg = mPackages.get(packageName); 6260 if (pkg == null) { 6261 throw new IllegalArgumentException("Missing package: " + packageName); 6262 } 6263 } 6264 6265 synchronized (mInstallLock) { 6266 final String[] instructionSets = new String[] { 6267 getPrimaryInstructionSet(pkg.applicationInfo) }; 6268 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6269 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6270 true /* boot complete */); 6271 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6272 throw new IllegalStateException("Failed to dexopt: " + res); 6273 } 6274 } 6275 } 6276 6277 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6278 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6279 Slog.w(TAG, "Unable to update from " + oldPkg.name 6280 + " to " + newPkg.packageName 6281 + ": old package not in system partition"); 6282 return false; 6283 } else if (mPackages.get(oldPkg.name) != null) { 6284 Slog.w(TAG, "Unable to update from " + oldPkg.name 6285 + " to " + newPkg.packageName 6286 + ": old package still exists"); 6287 return false; 6288 } 6289 return true; 6290 } 6291 6292 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6293 int[] users = sUserManager.getUserIds(); 6294 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6295 if (res < 0) { 6296 return res; 6297 } 6298 for (int user : users) { 6299 if (user != 0) { 6300 res = mInstaller.createUserData(volumeUuid, packageName, 6301 UserHandle.getUid(user, uid), user, seinfo); 6302 if (res < 0) { 6303 return res; 6304 } 6305 } 6306 } 6307 return res; 6308 } 6309 6310 private int removeDataDirsLI(String volumeUuid, String packageName) { 6311 int[] users = sUserManager.getUserIds(); 6312 int res = 0; 6313 for (int user : users) { 6314 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6315 if (resInner < 0) { 6316 res = resInner; 6317 } 6318 } 6319 6320 return res; 6321 } 6322 6323 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6324 int[] users = sUserManager.getUserIds(); 6325 int res = 0; 6326 for (int user : users) { 6327 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6328 if (resInner < 0) { 6329 res = resInner; 6330 } 6331 } 6332 return res; 6333 } 6334 6335 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6336 PackageParser.Package changingLib) { 6337 if (file.path != null) { 6338 usesLibraryFiles.add(file.path); 6339 return; 6340 } 6341 PackageParser.Package p = mPackages.get(file.apk); 6342 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6343 // If we are doing this while in the middle of updating a library apk, 6344 // then we need to make sure to use that new apk for determining the 6345 // dependencies here. (We haven't yet finished committing the new apk 6346 // to the package manager state.) 6347 if (p == null || p.packageName.equals(changingLib.packageName)) { 6348 p = changingLib; 6349 } 6350 } 6351 if (p != null) { 6352 usesLibraryFiles.addAll(p.getAllCodePaths()); 6353 } 6354 } 6355 6356 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6357 PackageParser.Package changingLib) throws PackageManagerException { 6358 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6359 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6360 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6361 for (int i=0; i<N; i++) { 6362 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6363 if (file == null) { 6364 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6365 "Package " + pkg.packageName + " requires unavailable shared library " 6366 + pkg.usesLibraries.get(i) + "; failing!"); 6367 } 6368 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6369 } 6370 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6371 for (int i=0; i<N; i++) { 6372 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6373 if (file == null) { 6374 Slog.w(TAG, "Package " + pkg.packageName 6375 + " desires unavailable shared library " 6376 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6377 } else { 6378 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6379 } 6380 } 6381 N = usesLibraryFiles.size(); 6382 if (N > 0) { 6383 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6384 } else { 6385 pkg.usesLibraryFiles = null; 6386 } 6387 } 6388 } 6389 6390 private static boolean hasString(List<String> list, List<String> which) { 6391 if (list == null) { 6392 return false; 6393 } 6394 for (int i=list.size()-1; i>=0; i--) { 6395 for (int j=which.size()-1; j>=0; j--) { 6396 if (which.get(j).equals(list.get(i))) { 6397 return true; 6398 } 6399 } 6400 } 6401 return false; 6402 } 6403 6404 private void updateAllSharedLibrariesLPw() { 6405 for (PackageParser.Package pkg : mPackages.values()) { 6406 try { 6407 updateSharedLibrariesLPw(pkg, null); 6408 } catch (PackageManagerException e) { 6409 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6410 } 6411 } 6412 } 6413 6414 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6415 PackageParser.Package changingPkg) { 6416 ArrayList<PackageParser.Package> res = null; 6417 for (PackageParser.Package pkg : mPackages.values()) { 6418 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6419 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6420 if (res == null) { 6421 res = new ArrayList<PackageParser.Package>(); 6422 } 6423 res.add(pkg); 6424 try { 6425 updateSharedLibrariesLPw(pkg, changingPkg); 6426 } catch (PackageManagerException e) { 6427 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6428 } 6429 } 6430 } 6431 return res; 6432 } 6433 6434 /** 6435 * Derive the value of the {@code cpuAbiOverride} based on the provided 6436 * value and an optional stored value from the package settings. 6437 */ 6438 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6439 String cpuAbiOverride = null; 6440 6441 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6442 cpuAbiOverride = null; 6443 } else if (abiOverride != null) { 6444 cpuAbiOverride = abiOverride; 6445 } else if (settings != null) { 6446 cpuAbiOverride = settings.cpuAbiOverrideString; 6447 } 6448 6449 return cpuAbiOverride; 6450 } 6451 6452 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6453 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6454 boolean success = false; 6455 try { 6456 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6457 currentTime, user); 6458 success = true; 6459 return res; 6460 } finally { 6461 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6462 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6463 } 6464 } 6465 } 6466 6467 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6468 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6469 final File scanFile = new File(pkg.codePath); 6470 if (pkg.applicationInfo.getCodePath() == null || 6471 pkg.applicationInfo.getResourcePath() == null) { 6472 // Bail out. The resource and code paths haven't been set. 6473 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6474 "Code and resource paths haven't been set correctly"); 6475 } 6476 6477 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6478 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6479 } else { 6480 // Only allow system apps to be flagged as core apps. 6481 pkg.coreApp = false; 6482 } 6483 6484 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6485 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6486 } 6487 6488 if (mCustomResolverComponentName != null && 6489 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6490 setUpCustomResolverActivity(pkg); 6491 } 6492 6493 if (pkg.packageName.equals("android")) { 6494 synchronized (mPackages) { 6495 if (mAndroidApplication != null) { 6496 Slog.w(TAG, "*************************************************"); 6497 Slog.w(TAG, "Core android package being redefined. Skipping."); 6498 Slog.w(TAG, " file=" + scanFile); 6499 Slog.w(TAG, "*************************************************"); 6500 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6501 "Core android package being redefined. Skipping."); 6502 } 6503 6504 // Set up information for our fall-back user intent resolution activity. 6505 mPlatformPackage = pkg; 6506 pkg.mVersionCode = mSdkVersion; 6507 mAndroidApplication = pkg.applicationInfo; 6508 6509 if (!mResolverReplaced) { 6510 mResolveActivity.applicationInfo = mAndroidApplication; 6511 mResolveActivity.name = ResolverActivity.class.getName(); 6512 mResolveActivity.packageName = mAndroidApplication.packageName; 6513 mResolveActivity.processName = "system:ui"; 6514 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6515 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6516 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6517 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6518 mResolveActivity.exported = true; 6519 mResolveActivity.enabled = true; 6520 mResolveInfo.activityInfo = mResolveActivity; 6521 mResolveInfo.priority = 0; 6522 mResolveInfo.preferredOrder = 0; 6523 mResolveInfo.match = 0; 6524 mResolveComponentName = new ComponentName( 6525 mAndroidApplication.packageName, mResolveActivity.name); 6526 } 6527 } 6528 } 6529 6530 if (DEBUG_PACKAGE_SCANNING) { 6531 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6532 Log.d(TAG, "Scanning package " + pkg.packageName); 6533 } 6534 6535 if (mPackages.containsKey(pkg.packageName) 6536 || mSharedLibraries.containsKey(pkg.packageName)) { 6537 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6538 "Application package " + pkg.packageName 6539 + " already installed. Skipping duplicate."); 6540 } 6541 6542 // If we're only installing presumed-existing packages, require that the 6543 // scanned APK is both already known and at the path previously established 6544 // for it. Previously unknown packages we pick up normally, but if we have an 6545 // a priori expectation about this package's install presence, enforce it. 6546 // With a singular exception for new system packages. When an OTA contains 6547 // a new system package, we allow the codepath to change from a system location 6548 // to the user-installed location. If we don't allow this change, any newer, 6549 // user-installed version of the application will be ignored. 6550 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6551 if (mExpectingBetter.containsKey(pkg.packageName)) { 6552 logCriticalInfo(Log.WARN, 6553 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6554 } else { 6555 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6556 if (known != null) { 6557 if (DEBUG_PACKAGE_SCANNING) { 6558 Log.d(TAG, "Examining " + pkg.codePath 6559 + " and requiring known paths " + known.codePathString 6560 + " & " + known.resourcePathString); 6561 } 6562 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6563 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6564 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6565 "Application package " + pkg.packageName 6566 + " found at " + pkg.applicationInfo.getCodePath() 6567 + " but expected at " + known.codePathString + "; ignoring."); 6568 } 6569 } 6570 } 6571 } 6572 6573 // Initialize package source and resource directories 6574 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6575 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6576 6577 SharedUserSetting suid = null; 6578 PackageSetting pkgSetting = null; 6579 6580 if (!isSystemApp(pkg)) { 6581 // Only system apps can use these features. 6582 pkg.mOriginalPackages = null; 6583 pkg.mRealPackage = null; 6584 pkg.mAdoptPermissions = null; 6585 } 6586 6587 // writer 6588 synchronized (mPackages) { 6589 if (pkg.mSharedUserId != null) { 6590 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6591 if (suid == null) { 6592 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6593 "Creating application package " + pkg.packageName 6594 + " for shared user failed"); 6595 } 6596 if (DEBUG_PACKAGE_SCANNING) { 6597 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6598 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6599 + "): packages=" + suid.packages); 6600 } 6601 } 6602 6603 // Check if we are renaming from an original package name. 6604 PackageSetting origPackage = null; 6605 String realName = null; 6606 if (pkg.mOriginalPackages != null) { 6607 // This package may need to be renamed to a previously 6608 // installed name. Let's check on that... 6609 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6610 if (pkg.mOriginalPackages.contains(renamed)) { 6611 // This package had originally been installed as the 6612 // original name, and we have already taken care of 6613 // transitioning to the new one. Just update the new 6614 // one to continue using the old name. 6615 realName = pkg.mRealPackage; 6616 if (!pkg.packageName.equals(renamed)) { 6617 // Callers into this function may have already taken 6618 // care of renaming the package; only do it here if 6619 // it is not already done. 6620 pkg.setPackageName(renamed); 6621 } 6622 6623 } else { 6624 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6625 if ((origPackage = mSettings.peekPackageLPr( 6626 pkg.mOriginalPackages.get(i))) != null) { 6627 // We do have the package already installed under its 6628 // original name... should we use it? 6629 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6630 // New package is not compatible with original. 6631 origPackage = null; 6632 continue; 6633 } else if (origPackage.sharedUser != null) { 6634 // Make sure uid is compatible between packages. 6635 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6636 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6637 + " to " + pkg.packageName + ": old uid " 6638 + origPackage.sharedUser.name 6639 + " differs from " + pkg.mSharedUserId); 6640 origPackage = null; 6641 continue; 6642 } 6643 } else { 6644 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6645 + pkg.packageName + " to old name " + origPackage.name); 6646 } 6647 break; 6648 } 6649 } 6650 } 6651 } 6652 6653 if (mTransferedPackages.contains(pkg.packageName)) { 6654 Slog.w(TAG, "Package " + pkg.packageName 6655 + " was transferred to another, but its .apk remains"); 6656 } 6657 6658 // Just create the setting, don't add it yet. For already existing packages 6659 // the PkgSetting exists already and doesn't have to be created. 6660 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6661 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6662 pkg.applicationInfo.primaryCpuAbi, 6663 pkg.applicationInfo.secondaryCpuAbi, 6664 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6665 user, false); 6666 if (pkgSetting == null) { 6667 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6668 "Creating application package " + pkg.packageName + " failed"); 6669 } 6670 6671 if (pkgSetting.origPackage != null) { 6672 // If we are first transitioning from an original package, 6673 // fix up the new package's name now. We need to do this after 6674 // looking up the package under its new name, so getPackageLP 6675 // can take care of fiddling things correctly. 6676 pkg.setPackageName(origPackage.name); 6677 6678 // File a report about this. 6679 String msg = "New package " + pkgSetting.realName 6680 + " renamed to replace old package " + pkgSetting.name; 6681 reportSettingsProblem(Log.WARN, msg); 6682 6683 // Make a note of it. 6684 mTransferedPackages.add(origPackage.name); 6685 6686 // No longer need to retain this. 6687 pkgSetting.origPackage = null; 6688 } 6689 6690 if (realName != null) { 6691 // Make a note of it. 6692 mTransferedPackages.add(pkg.packageName); 6693 } 6694 6695 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6696 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6697 } 6698 6699 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6700 // Check all shared libraries and map to their actual file path. 6701 // We only do this here for apps not on a system dir, because those 6702 // are the only ones that can fail an install due to this. We 6703 // will take care of the system apps by updating all of their 6704 // library paths after the scan is done. 6705 updateSharedLibrariesLPw(pkg, null); 6706 } 6707 6708 if (mFoundPolicyFile) { 6709 SELinuxMMAC.assignSeinfoValue(pkg); 6710 } 6711 6712 pkg.applicationInfo.uid = pkgSetting.appId; 6713 pkg.mExtras = pkgSetting; 6714 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6715 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6716 // We just determined the app is signed correctly, so bring 6717 // over the latest parsed certs. 6718 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6719 } else { 6720 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6721 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6722 "Package " + pkg.packageName + " upgrade keys do not match the " 6723 + "previously installed version"); 6724 } else { 6725 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6726 String msg = "System package " + pkg.packageName 6727 + " signature changed; retaining data."; 6728 reportSettingsProblem(Log.WARN, msg); 6729 } 6730 } 6731 } else { 6732 try { 6733 verifySignaturesLP(pkgSetting, pkg); 6734 // We just determined the app is signed correctly, so bring 6735 // over the latest parsed certs. 6736 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6737 } catch (PackageManagerException e) { 6738 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6739 throw e; 6740 } 6741 // The signature has changed, but this package is in the system 6742 // image... let's recover! 6743 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6744 // However... if this package is part of a shared user, but it 6745 // doesn't match the signature of the shared user, let's fail. 6746 // What this means is that you can't change the signatures 6747 // associated with an overall shared user, which doesn't seem all 6748 // that unreasonable. 6749 if (pkgSetting.sharedUser != null) { 6750 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6751 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6752 throw new PackageManagerException( 6753 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6754 "Signature mismatch for shared user : " 6755 + pkgSetting.sharedUser); 6756 } 6757 } 6758 // File a report about this. 6759 String msg = "System package " + pkg.packageName 6760 + " signature changed; retaining data."; 6761 reportSettingsProblem(Log.WARN, msg); 6762 } 6763 } 6764 // Verify that this new package doesn't have any content providers 6765 // that conflict with existing packages. Only do this if the 6766 // package isn't already installed, since we don't want to break 6767 // things that are installed. 6768 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6769 final int N = pkg.providers.size(); 6770 int i; 6771 for (i=0; i<N; i++) { 6772 PackageParser.Provider p = pkg.providers.get(i); 6773 if (p.info.authority != null) { 6774 String names[] = p.info.authority.split(";"); 6775 for (int j = 0; j < names.length; j++) { 6776 if (mProvidersByAuthority.containsKey(names[j])) { 6777 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6778 final String otherPackageName = 6779 ((other != null && other.getComponentName() != null) ? 6780 other.getComponentName().getPackageName() : "?"); 6781 throw new PackageManagerException( 6782 INSTALL_FAILED_CONFLICTING_PROVIDER, 6783 "Can't install because provider name " + names[j] 6784 + " (in package " + pkg.applicationInfo.packageName 6785 + ") is already used by " + otherPackageName); 6786 } 6787 } 6788 } 6789 } 6790 } 6791 6792 if (pkg.mAdoptPermissions != null) { 6793 // This package wants to adopt ownership of permissions from 6794 // another package. 6795 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6796 final String origName = pkg.mAdoptPermissions.get(i); 6797 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6798 if (orig != null) { 6799 if (verifyPackageUpdateLPr(orig, pkg)) { 6800 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6801 + pkg.packageName); 6802 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6803 } 6804 } 6805 } 6806 } 6807 } 6808 6809 final String pkgName = pkg.packageName; 6810 6811 final long scanFileTime = scanFile.lastModified(); 6812 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6813 pkg.applicationInfo.processName = fixProcessName( 6814 pkg.applicationInfo.packageName, 6815 pkg.applicationInfo.processName, 6816 pkg.applicationInfo.uid); 6817 6818 File dataPath; 6819 if (mPlatformPackage == pkg) { 6820 // The system package is special. 6821 dataPath = new File(Environment.getDataDirectory(), "system"); 6822 6823 pkg.applicationInfo.dataDir = dataPath.getPath(); 6824 6825 } else { 6826 // This is a normal package, need to make its data directory. 6827 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6828 UserHandle.USER_OWNER, pkg.packageName); 6829 6830 boolean uidError = false; 6831 if (dataPath.exists()) { 6832 int currentUid = 0; 6833 try { 6834 StructStat stat = Os.stat(dataPath.getPath()); 6835 currentUid = stat.st_uid; 6836 } catch (ErrnoException e) { 6837 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6838 } 6839 6840 // If we have mismatched owners for the data path, we have a problem. 6841 if (currentUid != pkg.applicationInfo.uid) { 6842 boolean recovered = false; 6843 if (currentUid == 0) { 6844 // The directory somehow became owned by root. Wow. 6845 // This is probably because the system was stopped while 6846 // installd was in the middle of messing with its libs 6847 // directory. Ask installd to fix that. 6848 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6849 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6850 if (ret >= 0) { 6851 recovered = true; 6852 String msg = "Package " + pkg.packageName 6853 + " unexpectedly changed to uid 0; recovered to " + 6854 + pkg.applicationInfo.uid; 6855 reportSettingsProblem(Log.WARN, msg); 6856 } 6857 } 6858 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6859 || (scanFlags&SCAN_BOOTING) != 0)) { 6860 // If this is a system app, we can at least delete its 6861 // current data so the application will still work. 6862 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6863 if (ret >= 0) { 6864 // TODO: Kill the processes first 6865 // Old data gone! 6866 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6867 ? "System package " : "Third party package "; 6868 String msg = prefix + pkg.packageName 6869 + " has changed from uid: " 6870 + currentUid + " to " 6871 + pkg.applicationInfo.uid + "; old data erased"; 6872 reportSettingsProblem(Log.WARN, msg); 6873 recovered = true; 6874 6875 // And now re-install the app. 6876 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6877 pkg.applicationInfo.seinfo); 6878 if (ret == -1) { 6879 // Ack should not happen! 6880 msg = prefix + pkg.packageName 6881 + " could not have data directory re-created after delete."; 6882 reportSettingsProblem(Log.WARN, msg); 6883 throw new PackageManagerException( 6884 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6885 } 6886 } 6887 if (!recovered) { 6888 mHasSystemUidErrors = true; 6889 } 6890 } else if (!recovered) { 6891 // If we allow this install to proceed, we will be broken. 6892 // Abort, abort! 6893 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6894 "scanPackageLI"); 6895 } 6896 if (!recovered) { 6897 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6898 + pkg.applicationInfo.uid + "/fs_" 6899 + currentUid; 6900 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6901 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6902 String msg = "Package " + pkg.packageName 6903 + " has mismatched uid: " 6904 + currentUid + " on disk, " 6905 + pkg.applicationInfo.uid + " in settings"; 6906 // writer 6907 synchronized (mPackages) { 6908 mSettings.mReadMessages.append(msg); 6909 mSettings.mReadMessages.append('\n'); 6910 uidError = true; 6911 if (!pkgSetting.uidError) { 6912 reportSettingsProblem(Log.ERROR, msg); 6913 } 6914 } 6915 } 6916 } 6917 pkg.applicationInfo.dataDir = dataPath.getPath(); 6918 if (mShouldRestoreconData) { 6919 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6920 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6921 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6922 } 6923 } else { 6924 if (DEBUG_PACKAGE_SCANNING) { 6925 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6926 Log.v(TAG, "Want this data dir: " + dataPath); 6927 } 6928 //invoke installer to do the actual installation 6929 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6930 pkg.applicationInfo.seinfo); 6931 if (ret < 0) { 6932 // Error from installer 6933 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6934 "Unable to create data dirs [errorCode=" + ret + "]"); 6935 } 6936 6937 if (dataPath.exists()) { 6938 pkg.applicationInfo.dataDir = dataPath.getPath(); 6939 } else { 6940 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6941 pkg.applicationInfo.dataDir = null; 6942 } 6943 } 6944 6945 pkgSetting.uidError = uidError; 6946 } 6947 6948 final String path = scanFile.getPath(); 6949 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6950 6951 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6952 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6953 6954 // Some system apps still use directory structure for native libraries 6955 // in which case we might end up not detecting abi solely based on apk 6956 // structure. Try to detect abi based on directory structure. 6957 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6958 pkg.applicationInfo.primaryCpuAbi == null) { 6959 setBundledAppAbisAndRoots(pkg, pkgSetting); 6960 setNativeLibraryPaths(pkg); 6961 } 6962 6963 } else { 6964 if ((scanFlags & SCAN_MOVE) != 0) { 6965 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6966 // but we already have this packages package info in the PackageSetting. We just 6967 // use that and derive the native library path based on the new codepath. 6968 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6969 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6970 } 6971 6972 // Set native library paths again. For moves, the path will be updated based on the 6973 // ABIs we've determined above. For non-moves, the path will be updated based on the 6974 // ABIs we determined during compilation, but the path will depend on the final 6975 // package path (after the rename away from the stage path). 6976 setNativeLibraryPaths(pkg); 6977 } 6978 6979 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6980 final int[] userIds = sUserManager.getUserIds(); 6981 synchronized (mInstallLock) { 6982 // Make sure all user data directories are ready to roll; we're okay 6983 // if they already exist 6984 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6985 for (int userId : userIds) { 6986 if (userId != 0) { 6987 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6988 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6989 pkg.applicationInfo.seinfo); 6990 } 6991 } 6992 } 6993 6994 // Create a native library symlink only if we have native libraries 6995 // and if the native libraries are 32 bit libraries. We do not provide 6996 // this symlink for 64 bit libraries. 6997 if (pkg.applicationInfo.primaryCpuAbi != null && 6998 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6999 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7000 for (int userId : userIds) { 7001 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7002 nativeLibPath, userId) < 0) { 7003 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7004 "Failed linking native library dir (user=" + userId + ")"); 7005 } 7006 } 7007 } 7008 } 7009 7010 // This is a special case for the "system" package, where the ABI is 7011 // dictated by the zygote configuration (and init.rc). We should keep track 7012 // of this ABI so that we can deal with "normal" applications that run under 7013 // the same UID correctly. 7014 if (mPlatformPackage == pkg) { 7015 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7016 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7017 } 7018 7019 // If there's a mismatch between the abi-override in the package setting 7020 // and the abiOverride specified for the install. Warn about this because we 7021 // would've already compiled the app without taking the package setting into 7022 // account. 7023 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7024 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7025 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7026 " for package: " + pkg.packageName); 7027 } 7028 } 7029 7030 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7031 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7032 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7033 7034 // Copy the derived override back to the parsed package, so that we can 7035 // update the package settings accordingly. 7036 pkg.cpuAbiOverride = cpuAbiOverride; 7037 7038 if (DEBUG_ABI_SELECTION) { 7039 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7040 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7041 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7042 } 7043 7044 // Push the derived path down into PackageSettings so we know what to 7045 // clean up at uninstall time. 7046 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7047 7048 if (DEBUG_ABI_SELECTION) { 7049 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7050 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7051 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7052 } 7053 7054 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7055 // We don't do this here during boot because we can do it all 7056 // at once after scanning all existing packages. 7057 // 7058 // We also do this *before* we perform dexopt on this package, so that 7059 // we can avoid redundant dexopts, and also to make sure we've got the 7060 // code and package path correct. 7061 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7062 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7063 } 7064 7065 if ((scanFlags & SCAN_NO_DEX) == 0) { 7066 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7067 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7068 (scanFlags & SCAN_BOOTING) == 0); 7069 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7070 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7071 } 7072 } 7073 if (mFactoryTest && pkg.requestedPermissions.contains( 7074 android.Manifest.permission.FACTORY_TEST)) { 7075 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7076 } 7077 7078 ArrayList<PackageParser.Package> clientLibPkgs = null; 7079 7080 // writer 7081 synchronized (mPackages) { 7082 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7083 // Only system apps can add new shared libraries. 7084 if (pkg.libraryNames != null) { 7085 for (int i=0; i<pkg.libraryNames.size(); i++) { 7086 String name = pkg.libraryNames.get(i); 7087 boolean allowed = false; 7088 if (pkg.isUpdatedSystemApp()) { 7089 // New library entries can only be added through the 7090 // system image. This is important to get rid of a lot 7091 // of nasty edge cases: for example if we allowed a non- 7092 // system update of the app to add a library, then uninstalling 7093 // the update would make the library go away, and assumptions 7094 // we made such as through app install filtering would now 7095 // have allowed apps on the device which aren't compatible 7096 // with it. Better to just have the restriction here, be 7097 // conservative, and create many fewer cases that can negatively 7098 // impact the user experience. 7099 final PackageSetting sysPs = mSettings 7100 .getDisabledSystemPkgLPr(pkg.packageName); 7101 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7102 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7103 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7104 allowed = true; 7105 allowed = true; 7106 break; 7107 } 7108 } 7109 } 7110 } else { 7111 allowed = true; 7112 } 7113 if (allowed) { 7114 if (!mSharedLibraries.containsKey(name)) { 7115 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7116 } else if (!name.equals(pkg.packageName)) { 7117 Slog.w(TAG, "Package " + pkg.packageName + " library " 7118 + name + " already exists; skipping"); 7119 } 7120 } else { 7121 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7122 + name + " that is not declared on system image; skipping"); 7123 } 7124 } 7125 if ((scanFlags&SCAN_BOOTING) == 0) { 7126 // If we are not booting, we need to update any applications 7127 // that are clients of our shared library. If we are booting, 7128 // this will all be done once the scan is complete. 7129 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7130 } 7131 } 7132 } 7133 } 7134 7135 // We also need to dexopt any apps that are dependent on this library. Note that 7136 // if these fail, we should abort the install since installing the library will 7137 // result in some apps being broken. 7138 if (clientLibPkgs != null) { 7139 if ((scanFlags & SCAN_NO_DEX) == 0) { 7140 for (int i = 0; i < clientLibPkgs.size(); i++) { 7141 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7142 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7143 null /* instruction sets */, forceDex, 7144 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7145 (scanFlags & SCAN_BOOTING) == 0); 7146 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7147 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7148 "scanPackageLI failed to dexopt clientLibPkgs"); 7149 } 7150 } 7151 } 7152 } 7153 7154 // Request the ActivityManager to kill the process(only for existing packages) 7155 // so that we do not end up in a confused state while the user is still using the older 7156 // version of the application while the new one gets installed. 7157 if ((scanFlags & SCAN_REPLACING) != 0) { 7158 killApplication(pkg.applicationInfo.packageName, 7159 pkg.applicationInfo.uid, "replace pkg"); 7160 } 7161 7162 // Also need to kill any apps that are dependent on the library. 7163 if (clientLibPkgs != null) { 7164 for (int i=0; i<clientLibPkgs.size(); i++) { 7165 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7166 killApplication(clientPkg.applicationInfo.packageName, 7167 clientPkg.applicationInfo.uid, "update lib"); 7168 } 7169 } 7170 7171 // Make sure we're not adding any bogus keyset info 7172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7173 ksms.assertScannedPackageValid(pkg); 7174 7175 // writer 7176 synchronized (mPackages) { 7177 // We don't expect installation to fail beyond this point 7178 7179 // Add the new setting to mSettings 7180 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7181 // Add the new setting to mPackages 7182 mPackages.put(pkg.applicationInfo.packageName, pkg); 7183 // Make sure we don't accidentally delete its data. 7184 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7185 while (iter.hasNext()) { 7186 PackageCleanItem item = iter.next(); 7187 if (pkgName.equals(item.packageName)) { 7188 iter.remove(); 7189 } 7190 } 7191 7192 // Take care of first install / last update times. 7193 if (currentTime != 0) { 7194 if (pkgSetting.firstInstallTime == 0) { 7195 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7196 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7197 pkgSetting.lastUpdateTime = currentTime; 7198 } 7199 } else if (pkgSetting.firstInstallTime == 0) { 7200 // We need *something*. Take time time stamp of the file. 7201 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7202 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7203 if (scanFileTime != pkgSetting.timeStamp) { 7204 // A package on the system image has changed; consider this 7205 // to be an update. 7206 pkgSetting.lastUpdateTime = scanFileTime; 7207 } 7208 } 7209 7210 // Add the package's KeySets to the global KeySetManagerService 7211 ksms.addScannedPackageLPw(pkg); 7212 7213 int N = pkg.providers.size(); 7214 StringBuilder r = null; 7215 int i; 7216 for (i=0; i<N; i++) { 7217 PackageParser.Provider p = pkg.providers.get(i); 7218 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7219 p.info.processName, pkg.applicationInfo.uid); 7220 mProviders.addProvider(p); 7221 p.syncable = p.info.isSyncable; 7222 if (p.info.authority != null) { 7223 String names[] = p.info.authority.split(";"); 7224 p.info.authority = null; 7225 for (int j = 0; j < names.length; j++) { 7226 if (j == 1 && p.syncable) { 7227 // We only want the first authority for a provider to possibly be 7228 // syncable, so if we already added this provider using a different 7229 // authority clear the syncable flag. We copy the provider before 7230 // changing it because the mProviders object contains a reference 7231 // to a provider that we don't want to change. 7232 // Only do this for the second authority since the resulting provider 7233 // object can be the same for all future authorities for this provider. 7234 p = new PackageParser.Provider(p); 7235 p.syncable = false; 7236 } 7237 if (!mProvidersByAuthority.containsKey(names[j])) { 7238 mProvidersByAuthority.put(names[j], p); 7239 if (p.info.authority == null) { 7240 p.info.authority = names[j]; 7241 } else { 7242 p.info.authority = p.info.authority + ";" + names[j]; 7243 } 7244 if (DEBUG_PACKAGE_SCANNING) { 7245 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7246 Log.d(TAG, "Registered content provider: " + names[j] 7247 + ", className = " + p.info.name + ", isSyncable = " 7248 + p.info.isSyncable); 7249 } 7250 } else { 7251 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7252 Slog.w(TAG, "Skipping provider name " + names[j] + 7253 " (in package " + pkg.applicationInfo.packageName + 7254 "): name already used by " 7255 + ((other != null && other.getComponentName() != null) 7256 ? other.getComponentName().getPackageName() : "?")); 7257 } 7258 } 7259 } 7260 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7261 if (r == null) { 7262 r = new StringBuilder(256); 7263 } else { 7264 r.append(' '); 7265 } 7266 r.append(p.info.name); 7267 } 7268 } 7269 if (r != null) { 7270 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7271 } 7272 7273 N = pkg.services.size(); 7274 r = null; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Service s = pkg.services.get(i); 7277 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7278 s.info.processName, pkg.applicationInfo.uid); 7279 mServices.addService(s); 7280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7281 if (r == null) { 7282 r = new StringBuilder(256); 7283 } else { 7284 r.append(' '); 7285 } 7286 r.append(s.info.name); 7287 } 7288 } 7289 if (r != null) { 7290 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7291 } 7292 7293 N = pkg.receivers.size(); 7294 r = null; 7295 for (i=0; i<N; i++) { 7296 PackageParser.Activity a = pkg.receivers.get(i); 7297 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7298 a.info.processName, pkg.applicationInfo.uid); 7299 mReceivers.addActivity(a, "receiver"); 7300 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7301 if (r == null) { 7302 r = new StringBuilder(256); 7303 } else { 7304 r.append(' '); 7305 } 7306 r.append(a.info.name); 7307 } 7308 } 7309 if (r != null) { 7310 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7311 } 7312 7313 N = pkg.activities.size(); 7314 r = null; 7315 for (i=0; i<N; i++) { 7316 PackageParser.Activity a = pkg.activities.get(i); 7317 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7318 a.info.processName, pkg.applicationInfo.uid); 7319 mActivities.addActivity(a, "activity"); 7320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7321 if (r == null) { 7322 r = new StringBuilder(256); 7323 } else { 7324 r.append(' '); 7325 } 7326 r.append(a.info.name); 7327 } 7328 } 7329 if (r != null) { 7330 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7331 } 7332 7333 N = pkg.permissionGroups.size(); 7334 r = null; 7335 for (i=0; i<N; i++) { 7336 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7337 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7338 if (cur == null) { 7339 mPermissionGroups.put(pg.info.name, pg); 7340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7341 if (r == null) { 7342 r = new StringBuilder(256); 7343 } else { 7344 r.append(' '); 7345 } 7346 r.append(pg.info.name); 7347 } 7348 } else { 7349 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7350 + pg.info.packageName + " ignored: original from " 7351 + cur.info.packageName); 7352 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7353 if (r == null) { 7354 r = new StringBuilder(256); 7355 } else { 7356 r.append(' '); 7357 } 7358 r.append("DUP:"); 7359 r.append(pg.info.name); 7360 } 7361 } 7362 } 7363 if (r != null) { 7364 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7365 } 7366 7367 N = pkg.permissions.size(); 7368 r = null; 7369 for (i=0; i<N; i++) { 7370 PackageParser.Permission p = pkg.permissions.get(i); 7371 7372 // Assume by default that we did not install this permission into the system. 7373 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7374 7375 // Now that permission groups have a special meaning, we ignore permission 7376 // groups for legacy apps to prevent unexpected behavior. In particular, 7377 // permissions for one app being granted to someone just becuase they happen 7378 // to be in a group defined by another app (before this had no implications). 7379 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7380 p.group = mPermissionGroups.get(p.info.group); 7381 // Warn for a permission in an unknown group. 7382 if (p.info.group != null && p.group == null) { 7383 Slog.w(TAG, "Permission " + p.info.name + " from package " 7384 + p.info.packageName + " in an unknown group " + p.info.group); 7385 } 7386 } 7387 7388 ArrayMap<String, BasePermission> permissionMap = 7389 p.tree ? mSettings.mPermissionTrees 7390 : mSettings.mPermissions; 7391 BasePermission bp = permissionMap.get(p.info.name); 7392 7393 // Allow system apps to redefine non-system permissions 7394 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7395 final boolean currentOwnerIsSystem = (bp.perm != null 7396 && isSystemApp(bp.perm.owner)); 7397 if (isSystemApp(p.owner)) { 7398 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7399 // It's a built-in permission and no owner, take ownership now 7400 bp.packageSetting = pkgSetting; 7401 bp.perm = p; 7402 bp.uid = pkg.applicationInfo.uid; 7403 bp.sourcePackage = p.info.packageName; 7404 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7405 } else if (!currentOwnerIsSystem) { 7406 String msg = "New decl " + p.owner + " of permission " 7407 + p.info.name + " is system; overriding " + bp.sourcePackage; 7408 reportSettingsProblem(Log.WARN, msg); 7409 bp = null; 7410 } 7411 } 7412 } 7413 7414 if (bp == null) { 7415 bp = new BasePermission(p.info.name, p.info.packageName, 7416 BasePermission.TYPE_NORMAL); 7417 permissionMap.put(p.info.name, bp); 7418 } 7419 7420 if (bp.perm == null) { 7421 if (bp.sourcePackage == null 7422 || bp.sourcePackage.equals(p.info.packageName)) { 7423 BasePermission tree = findPermissionTreeLP(p.info.name); 7424 if (tree == null 7425 || tree.sourcePackage.equals(p.info.packageName)) { 7426 bp.packageSetting = pkgSetting; 7427 bp.perm = p; 7428 bp.uid = pkg.applicationInfo.uid; 7429 bp.sourcePackage = p.info.packageName; 7430 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7431 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7432 if (r == null) { 7433 r = new StringBuilder(256); 7434 } else { 7435 r.append(' '); 7436 } 7437 r.append(p.info.name); 7438 } 7439 } else { 7440 Slog.w(TAG, "Permission " + p.info.name + " from package " 7441 + p.info.packageName + " ignored: base tree " 7442 + tree.name + " is from package " 7443 + tree.sourcePackage); 7444 } 7445 } else { 7446 Slog.w(TAG, "Permission " + p.info.name + " from package " 7447 + p.info.packageName + " ignored: original from " 7448 + bp.sourcePackage); 7449 } 7450 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7451 if (r == null) { 7452 r = new StringBuilder(256); 7453 } else { 7454 r.append(' '); 7455 } 7456 r.append("DUP:"); 7457 r.append(p.info.name); 7458 } 7459 if (bp.perm == p) { 7460 bp.protectionLevel = p.info.protectionLevel; 7461 } 7462 } 7463 7464 if (r != null) { 7465 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7466 } 7467 7468 N = pkg.instrumentation.size(); 7469 r = null; 7470 for (i=0; i<N; i++) { 7471 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7472 a.info.packageName = pkg.applicationInfo.packageName; 7473 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7474 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7475 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7476 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7477 a.info.dataDir = pkg.applicationInfo.dataDir; 7478 7479 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7480 // need other information about the application, like the ABI and what not ? 7481 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7482 mInstrumentation.put(a.getComponentName(), a); 7483 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7484 if (r == null) { 7485 r = new StringBuilder(256); 7486 } else { 7487 r.append(' '); 7488 } 7489 r.append(a.info.name); 7490 } 7491 } 7492 if (r != null) { 7493 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7494 } 7495 7496 if (pkg.protectedBroadcasts != null) { 7497 N = pkg.protectedBroadcasts.size(); 7498 for (i=0; i<N; i++) { 7499 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7500 } 7501 } 7502 7503 pkgSetting.setTimeStamp(scanFileTime); 7504 7505 // Create idmap files for pairs of (packages, overlay packages). 7506 // Note: "android", ie framework-res.apk, is handled by native layers. 7507 if (pkg.mOverlayTarget != null) { 7508 // This is an overlay package. 7509 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7510 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7511 mOverlays.put(pkg.mOverlayTarget, 7512 new ArrayMap<String, PackageParser.Package>()); 7513 } 7514 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7515 map.put(pkg.packageName, pkg); 7516 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7517 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7518 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7519 "scanPackageLI failed to createIdmap"); 7520 } 7521 } 7522 } else if (mOverlays.containsKey(pkg.packageName) && 7523 !pkg.packageName.equals("android")) { 7524 // This is a regular package, with one or more known overlay packages. 7525 createIdmapsForPackageLI(pkg); 7526 } 7527 } 7528 7529 return pkg; 7530 } 7531 7532 /** 7533 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7534 * is derived purely on the basis of the contents of {@code scanFile} and 7535 * {@code cpuAbiOverride}. 7536 * 7537 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7538 */ 7539 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7540 String cpuAbiOverride, boolean extractLibs) 7541 throws PackageManagerException { 7542 // TODO: We can probably be smarter about this stuff. For installed apps, 7543 // we can calculate this information at install time once and for all. For 7544 // system apps, we can probably assume that this information doesn't change 7545 // after the first boot scan. As things stand, we do lots of unnecessary work. 7546 7547 // Give ourselves some initial paths; we'll come back for another 7548 // pass once we've determined ABI below. 7549 setNativeLibraryPaths(pkg); 7550 7551 // We would never need to extract libs for forward-locked and external packages, 7552 // since the container service will do it for us. We shouldn't attempt to 7553 // extract libs from system app when it was not updated. 7554 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7555 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7556 extractLibs = false; 7557 } 7558 7559 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7560 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7561 7562 NativeLibraryHelper.Handle handle = null; 7563 try { 7564 handle = NativeLibraryHelper.Handle.create(scanFile); 7565 // TODO(multiArch): This can be null for apps that didn't go through the 7566 // usual installation process. We can calculate it again, like we 7567 // do during install time. 7568 // 7569 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7570 // unnecessary. 7571 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7572 7573 // Null out the abis so that they can be recalculated. 7574 pkg.applicationInfo.primaryCpuAbi = null; 7575 pkg.applicationInfo.secondaryCpuAbi = null; 7576 if (isMultiArch(pkg.applicationInfo)) { 7577 // Warn if we've set an abiOverride for multi-lib packages.. 7578 // By definition, we need to copy both 32 and 64 bit libraries for 7579 // such packages. 7580 if (pkg.cpuAbiOverride != null 7581 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7582 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7583 } 7584 7585 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7586 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7587 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7588 if (extractLibs) { 7589 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7590 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7591 useIsaSpecificSubdirs); 7592 } else { 7593 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7594 } 7595 } 7596 7597 maybeThrowExceptionForMultiArchCopy( 7598 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7599 7600 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7601 if (extractLibs) { 7602 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7603 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7604 useIsaSpecificSubdirs); 7605 } else { 7606 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7607 } 7608 } 7609 7610 maybeThrowExceptionForMultiArchCopy( 7611 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7612 7613 if (abi64 >= 0) { 7614 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7615 } 7616 7617 if (abi32 >= 0) { 7618 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7619 if (abi64 >= 0) { 7620 pkg.applicationInfo.secondaryCpuAbi = abi; 7621 } else { 7622 pkg.applicationInfo.primaryCpuAbi = abi; 7623 } 7624 } 7625 } else { 7626 String[] abiList = (cpuAbiOverride != null) ? 7627 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7628 7629 // Enable gross and lame hacks for apps that are built with old 7630 // SDK tools. We must scan their APKs for renderscript bitcode and 7631 // not launch them if it's present. Don't bother checking on devices 7632 // that don't have 64 bit support. 7633 boolean needsRenderScriptOverride = false; 7634 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7635 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7636 abiList = Build.SUPPORTED_32_BIT_ABIS; 7637 needsRenderScriptOverride = true; 7638 } 7639 7640 final int copyRet; 7641 if (extractLibs) { 7642 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7643 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7644 } else { 7645 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7646 } 7647 7648 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7649 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7650 "Error unpackaging native libs for app, errorCode=" + copyRet); 7651 } 7652 7653 if (copyRet >= 0) { 7654 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7655 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7656 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7657 } else if (needsRenderScriptOverride) { 7658 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7659 } 7660 } 7661 } catch (IOException ioe) { 7662 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7663 } finally { 7664 IoUtils.closeQuietly(handle); 7665 } 7666 7667 // Now that we've calculated the ABIs and determined if it's an internal app, 7668 // we will go ahead and populate the nativeLibraryPath. 7669 setNativeLibraryPaths(pkg); 7670 } 7671 7672 /** 7673 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7674 * i.e, so that all packages can be run inside a single process if required. 7675 * 7676 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7677 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7678 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7679 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7680 * updating a package that belongs to a shared user. 7681 * 7682 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7683 * adds unnecessary complexity. 7684 */ 7685 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7686 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7687 boolean bootComplete) { 7688 String requiredInstructionSet = null; 7689 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7690 requiredInstructionSet = VMRuntime.getInstructionSet( 7691 scannedPackage.applicationInfo.primaryCpuAbi); 7692 } 7693 7694 PackageSetting requirer = null; 7695 for (PackageSetting ps : packagesForUser) { 7696 // If packagesForUser contains scannedPackage, we skip it. This will happen 7697 // when scannedPackage is an update of an existing package. Without this check, 7698 // we will never be able to change the ABI of any package belonging to a shared 7699 // user, even if it's compatible with other packages. 7700 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7701 if (ps.primaryCpuAbiString == null) { 7702 continue; 7703 } 7704 7705 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7706 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7707 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7708 // this but there's not much we can do. 7709 String errorMessage = "Instruction set mismatch, " 7710 + ((requirer == null) ? "[caller]" : requirer) 7711 + " requires " + requiredInstructionSet + " whereas " + ps 7712 + " requires " + instructionSet; 7713 Slog.w(TAG, errorMessage); 7714 } 7715 7716 if (requiredInstructionSet == null) { 7717 requiredInstructionSet = instructionSet; 7718 requirer = ps; 7719 } 7720 } 7721 } 7722 7723 if (requiredInstructionSet != null) { 7724 String adjustedAbi; 7725 if (requirer != null) { 7726 // requirer != null implies that either scannedPackage was null or that scannedPackage 7727 // did not require an ABI, in which case we have to adjust scannedPackage to match 7728 // the ABI of the set (which is the same as requirer's ABI) 7729 adjustedAbi = requirer.primaryCpuAbiString; 7730 if (scannedPackage != null) { 7731 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7732 } 7733 } else { 7734 // requirer == null implies that we're updating all ABIs in the set to 7735 // match scannedPackage. 7736 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7737 } 7738 7739 for (PackageSetting ps : packagesForUser) { 7740 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7741 if (ps.primaryCpuAbiString != null) { 7742 continue; 7743 } 7744 7745 ps.primaryCpuAbiString = adjustedAbi; 7746 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7747 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7748 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7749 7750 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7751 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7752 bootComplete); 7753 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7754 ps.primaryCpuAbiString = null; 7755 ps.pkg.applicationInfo.primaryCpuAbi = null; 7756 return; 7757 } else { 7758 mInstaller.rmdex(ps.codePathString, 7759 getDexCodeInstructionSet(getPreferredInstructionSet())); 7760 } 7761 } 7762 } 7763 } 7764 } 7765 } 7766 7767 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7768 synchronized (mPackages) { 7769 mResolverReplaced = true; 7770 // Set up information for custom user intent resolution activity. 7771 mResolveActivity.applicationInfo = pkg.applicationInfo; 7772 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7773 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7774 mResolveActivity.processName = pkg.applicationInfo.packageName; 7775 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7776 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7777 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7778 mResolveActivity.theme = 0; 7779 mResolveActivity.exported = true; 7780 mResolveActivity.enabled = true; 7781 mResolveInfo.activityInfo = mResolveActivity; 7782 mResolveInfo.priority = 0; 7783 mResolveInfo.preferredOrder = 0; 7784 mResolveInfo.match = 0; 7785 mResolveComponentName = mCustomResolverComponentName; 7786 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7787 mResolveComponentName); 7788 } 7789 } 7790 7791 private static String calculateBundledApkRoot(final String codePathString) { 7792 final File codePath = new File(codePathString); 7793 final File codeRoot; 7794 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7795 codeRoot = Environment.getRootDirectory(); 7796 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7797 codeRoot = Environment.getOemDirectory(); 7798 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7799 codeRoot = Environment.getVendorDirectory(); 7800 } else { 7801 // Unrecognized code path; take its top real segment as the apk root: 7802 // e.g. /something/app/blah.apk => /something 7803 try { 7804 File f = codePath.getCanonicalFile(); 7805 File parent = f.getParentFile(); // non-null because codePath is a file 7806 File tmp; 7807 while ((tmp = parent.getParentFile()) != null) { 7808 f = parent; 7809 parent = tmp; 7810 } 7811 codeRoot = f; 7812 Slog.w(TAG, "Unrecognized code path " 7813 + codePath + " - using " + codeRoot); 7814 } catch (IOException e) { 7815 // Can't canonicalize the code path -- shenanigans? 7816 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7817 return Environment.getRootDirectory().getPath(); 7818 } 7819 } 7820 return codeRoot.getPath(); 7821 } 7822 7823 /** 7824 * Derive and set the location of native libraries for the given package, 7825 * which varies depending on where and how the package was installed. 7826 */ 7827 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7828 final ApplicationInfo info = pkg.applicationInfo; 7829 final String codePath = pkg.codePath; 7830 final File codeFile = new File(codePath); 7831 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7832 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7833 7834 info.nativeLibraryRootDir = null; 7835 info.nativeLibraryRootRequiresIsa = false; 7836 info.nativeLibraryDir = null; 7837 info.secondaryNativeLibraryDir = null; 7838 7839 if (isApkFile(codeFile)) { 7840 // Monolithic install 7841 if (bundledApp) { 7842 // If "/system/lib64/apkname" exists, assume that is the per-package 7843 // native library directory to use; otherwise use "/system/lib/apkname". 7844 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7845 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7846 getPrimaryInstructionSet(info)); 7847 7848 // This is a bundled system app so choose the path based on the ABI. 7849 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7850 // is just the default path. 7851 final String apkName = deriveCodePathName(codePath); 7852 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7853 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7854 apkName).getAbsolutePath(); 7855 7856 if (info.secondaryCpuAbi != null) { 7857 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7858 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7859 secondaryLibDir, apkName).getAbsolutePath(); 7860 } 7861 } else if (asecApp) { 7862 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7863 .getAbsolutePath(); 7864 } else { 7865 final String apkName = deriveCodePathName(codePath); 7866 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7867 .getAbsolutePath(); 7868 } 7869 7870 info.nativeLibraryRootRequiresIsa = false; 7871 info.nativeLibraryDir = info.nativeLibraryRootDir; 7872 } else { 7873 // Cluster install 7874 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7875 info.nativeLibraryRootRequiresIsa = true; 7876 7877 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7878 getPrimaryInstructionSet(info)).getAbsolutePath(); 7879 7880 if (info.secondaryCpuAbi != null) { 7881 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7882 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7883 } 7884 } 7885 } 7886 7887 /** 7888 * Calculate the abis and roots for a bundled app. These can uniquely 7889 * be determined from the contents of the system partition, i.e whether 7890 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7891 * of this information, and instead assume that the system was built 7892 * sensibly. 7893 */ 7894 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7895 PackageSetting pkgSetting) { 7896 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7897 7898 // If "/system/lib64/apkname" exists, assume that is the per-package 7899 // native library directory to use; otherwise use "/system/lib/apkname". 7900 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7901 setBundledAppAbi(pkg, apkRoot, apkName); 7902 // pkgSetting might be null during rescan following uninstall of updates 7903 // to a bundled app, so accommodate that possibility. The settings in 7904 // that case will be established later from the parsed package. 7905 // 7906 // If the settings aren't null, sync them up with what we've just derived. 7907 // note that apkRoot isn't stored in the package settings. 7908 if (pkgSetting != null) { 7909 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7910 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7911 } 7912 } 7913 7914 /** 7915 * Deduces the ABI of a bundled app and sets the relevant fields on the 7916 * parsed pkg object. 7917 * 7918 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7919 * under which system libraries are installed. 7920 * @param apkName the name of the installed package. 7921 */ 7922 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7923 final File codeFile = new File(pkg.codePath); 7924 7925 final boolean has64BitLibs; 7926 final boolean has32BitLibs; 7927 if (isApkFile(codeFile)) { 7928 // Monolithic install 7929 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7930 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7931 } else { 7932 // Cluster install 7933 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7934 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7935 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7936 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7937 has64BitLibs = (new File(rootDir, isa)).exists(); 7938 } else { 7939 has64BitLibs = false; 7940 } 7941 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7942 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7943 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7944 has32BitLibs = (new File(rootDir, isa)).exists(); 7945 } else { 7946 has32BitLibs = false; 7947 } 7948 } 7949 7950 if (has64BitLibs && !has32BitLibs) { 7951 // The package has 64 bit libs, but not 32 bit libs. Its primary 7952 // ABI should be 64 bit. We can safely assume here that the bundled 7953 // native libraries correspond to the most preferred ABI in the list. 7954 7955 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7956 pkg.applicationInfo.secondaryCpuAbi = null; 7957 } else if (has32BitLibs && !has64BitLibs) { 7958 // The package has 32 bit libs but not 64 bit libs. Its primary 7959 // ABI should be 32 bit. 7960 7961 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7962 pkg.applicationInfo.secondaryCpuAbi = null; 7963 } else if (has32BitLibs && has64BitLibs) { 7964 // The application has both 64 and 32 bit bundled libraries. We check 7965 // here that the app declares multiArch support, and warn if it doesn't. 7966 // 7967 // We will be lenient here and record both ABIs. The primary will be the 7968 // ABI that's higher on the list, i.e, a device that's configured to prefer 7969 // 64 bit apps will see a 64 bit primary ABI, 7970 7971 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7972 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7973 } 7974 7975 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7976 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7977 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7978 } else { 7979 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7980 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7981 } 7982 } else { 7983 pkg.applicationInfo.primaryCpuAbi = null; 7984 pkg.applicationInfo.secondaryCpuAbi = null; 7985 } 7986 } 7987 7988 private void killApplication(String pkgName, int appId, String reason) { 7989 // Request the ActivityManager to kill the process(only for existing packages) 7990 // so that we do not end up in a confused state while the user is still using the older 7991 // version of the application while the new one gets installed. 7992 IActivityManager am = ActivityManagerNative.getDefault(); 7993 if (am != null) { 7994 try { 7995 am.killApplicationWithAppId(pkgName, appId, reason); 7996 } catch (RemoteException e) { 7997 } 7998 } 7999 } 8000 8001 void removePackageLI(PackageSetting ps, boolean chatty) { 8002 if (DEBUG_INSTALL) { 8003 if (chatty) 8004 Log.d(TAG, "Removing package " + ps.name); 8005 } 8006 8007 // writer 8008 synchronized (mPackages) { 8009 mPackages.remove(ps.name); 8010 final PackageParser.Package pkg = ps.pkg; 8011 if (pkg != null) { 8012 cleanPackageDataStructuresLILPw(pkg, chatty); 8013 } 8014 } 8015 } 8016 8017 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8018 if (DEBUG_INSTALL) { 8019 if (chatty) 8020 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8021 } 8022 8023 // writer 8024 synchronized (mPackages) { 8025 mPackages.remove(pkg.applicationInfo.packageName); 8026 cleanPackageDataStructuresLILPw(pkg, chatty); 8027 } 8028 } 8029 8030 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8031 int N = pkg.providers.size(); 8032 StringBuilder r = null; 8033 int i; 8034 for (i=0; i<N; i++) { 8035 PackageParser.Provider p = pkg.providers.get(i); 8036 mProviders.removeProvider(p); 8037 if (p.info.authority == null) { 8038 8039 /* There was another ContentProvider with this authority when 8040 * this app was installed so this authority is null, 8041 * Ignore it as we don't have to unregister the provider. 8042 */ 8043 continue; 8044 } 8045 String names[] = p.info.authority.split(";"); 8046 for (int j = 0; j < names.length; j++) { 8047 if (mProvidersByAuthority.get(names[j]) == p) { 8048 mProvidersByAuthority.remove(names[j]); 8049 if (DEBUG_REMOVE) { 8050 if (chatty) 8051 Log.d(TAG, "Unregistered content provider: " + names[j] 8052 + ", className = " + p.info.name + ", isSyncable = " 8053 + p.info.isSyncable); 8054 } 8055 } 8056 } 8057 if (DEBUG_REMOVE && chatty) { 8058 if (r == null) { 8059 r = new StringBuilder(256); 8060 } else { 8061 r.append(' '); 8062 } 8063 r.append(p.info.name); 8064 } 8065 } 8066 if (r != null) { 8067 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8068 } 8069 8070 N = pkg.services.size(); 8071 r = null; 8072 for (i=0; i<N; i++) { 8073 PackageParser.Service s = pkg.services.get(i); 8074 mServices.removeService(s); 8075 if (chatty) { 8076 if (r == null) { 8077 r = new StringBuilder(256); 8078 } else { 8079 r.append(' '); 8080 } 8081 r.append(s.info.name); 8082 } 8083 } 8084 if (r != null) { 8085 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8086 } 8087 8088 N = pkg.receivers.size(); 8089 r = null; 8090 for (i=0; i<N; i++) { 8091 PackageParser.Activity a = pkg.receivers.get(i); 8092 mReceivers.removeActivity(a, "receiver"); 8093 if (DEBUG_REMOVE && chatty) { 8094 if (r == null) { 8095 r = new StringBuilder(256); 8096 } else { 8097 r.append(' '); 8098 } 8099 r.append(a.info.name); 8100 } 8101 } 8102 if (r != null) { 8103 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8104 } 8105 8106 N = pkg.activities.size(); 8107 r = null; 8108 for (i=0; i<N; i++) { 8109 PackageParser.Activity a = pkg.activities.get(i); 8110 mActivities.removeActivity(a, "activity"); 8111 if (DEBUG_REMOVE && chatty) { 8112 if (r == null) { 8113 r = new StringBuilder(256); 8114 } else { 8115 r.append(' '); 8116 } 8117 r.append(a.info.name); 8118 } 8119 } 8120 if (r != null) { 8121 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8122 } 8123 8124 N = pkg.permissions.size(); 8125 r = null; 8126 for (i=0; i<N; i++) { 8127 PackageParser.Permission p = pkg.permissions.get(i); 8128 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8129 if (bp == null) { 8130 bp = mSettings.mPermissionTrees.get(p.info.name); 8131 } 8132 if (bp != null && bp.perm == p) { 8133 bp.perm = null; 8134 if (DEBUG_REMOVE && chatty) { 8135 if (r == null) { 8136 r = new StringBuilder(256); 8137 } else { 8138 r.append(' '); 8139 } 8140 r.append(p.info.name); 8141 } 8142 } 8143 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8144 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8145 if (appOpPerms != null) { 8146 appOpPerms.remove(pkg.packageName); 8147 } 8148 } 8149 } 8150 if (r != null) { 8151 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8152 } 8153 8154 N = pkg.requestedPermissions.size(); 8155 r = null; 8156 for (i=0; i<N; i++) { 8157 String perm = pkg.requestedPermissions.get(i); 8158 BasePermission bp = mSettings.mPermissions.get(perm); 8159 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8160 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8161 if (appOpPerms != null) { 8162 appOpPerms.remove(pkg.packageName); 8163 if (appOpPerms.isEmpty()) { 8164 mAppOpPermissionPackages.remove(perm); 8165 } 8166 } 8167 } 8168 } 8169 if (r != null) { 8170 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8171 } 8172 8173 N = pkg.instrumentation.size(); 8174 r = null; 8175 for (i=0; i<N; i++) { 8176 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8177 mInstrumentation.remove(a.getComponentName()); 8178 if (DEBUG_REMOVE && chatty) { 8179 if (r == null) { 8180 r = new StringBuilder(256); 8181 } else { 8182 r.append(' '); 8183 } 8184 r.append(a.info.name); 8185 } 8186 } 8187 if (r != null) { 8188 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8189 } 8190 8191 r = null; 8192 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8193 // Only system apps can hold shared libraries. 8194 if (pkg.libraryNames != null) { 8195 for (i=0; i<pkg.libraryNames.size(); i++) { 8196 String name = pkg.libraryNames.get(i); 8197 SharedLibraryEntry cur = mSharedLibraries.get(name); 8198 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8199 mSharedLibraries.remove(name); 8200 if (DEBUG_REMOVE && chatty) { 8201 if (r == null) { 8202 r = new StringBuilder(256); 8203 } else { 8204 r.append(' '); 8205 } 8206 r.append(name); 8207 } 8208 } 8209 } 8210 } 8211 } 8212 if (r != null) { 8213 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8214 } 8215 } 8216 8217 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8218 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8219 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8220 return true; 8221 } 8222 } 8223 return false; 8224 } 8225 8226 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8227 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8228 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8229 8230 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8231 int flags) { 8232 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8233 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8234 } 8235 8236 private void updatePermissionsLPw(String changingPkg, 8237 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8238 // Make sure there are no dangling permission trees. 8239 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8240 while (it.hasNext()) { 8241 final BasePermission bp = it.next(); 8242 if (bp.packageSetting == null) { 8243 // We may not yet have parsed the package, so just see if 8244 // we still know about its settings. 8245 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8246 } 8247 if (bp.packageSetting == null) { 8248 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8249 + " from package " + bp.sourcePackage); 8250 it.remove(); 8251 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8252 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8253 Slog.i(TAG, "Removing old permission tree: " + bp.name 8254 + " from package " + bp.sourcePackage); 8255 flags |= UPDATE_PERMISSIONS_ALL; 8256 it.remove(); 8257 } 8258 } 8259 } 8260 8261 // Make sure all dynamic permissions have been assigned to a package, 8262 // and make sure there are no dangling permissions. 8263 it = mSettings.mPermissions.values().iterator(); 8264 while (it.hasNext()) { 8265 final BasePermission bp = it.next(); 8266 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8267 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8268 + bp.name + " pkg=" + bp.sourcePackage 8269 + " info=" + bp.pendingInfo); 8270 if (bp.packageSetting == null && bp.pendingInfo != null) { 8271 final BasePermission tree = findPermissionTreeLP(bp.name); 8272 if (tree != null && tree.perm != null) { 8273 bp.packageSetting = tree.packageSetting; 8274 bp.perm = new PackageParser.Permission(tree.perm.owner, 8275 new PermissionInfo(bp.pendingInfo)); 8276 bp.perm.info.packageName = tree.perm.info.packageName; 8277 bp.perm.info.name = bp.name; 8278 bp.uid = tree.uid; 8279 } 8280 } 8281 } 8282 if (bp.packageSetting == null) { 8283 // We may not yet have parsed the package, so just see if 8284 // we still know about its settings. 8285 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8286 } 8287 if (bp.packageSetting == null) { 8288 Slog.w(TAG, "Removing dangling permission: " + bp.name 8289 + " from package " + bp.sourcePackage); 8290 it.remove(); 8291 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8292 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8293 Slog.i(TAG, "Removing old permission: " + bp.name 8294 + " from package " + bp.sourcePackage); 8295 flags |= UPDATE_PERMISSIONS_ALL; 8296 it.remove(); 8297 } 8298 } 8299 } 8300 8301 // Now update the permissions for all packages, in particular 8302 // replace the granted permissions of the system packages. 8303 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8304 for (PackageParser.Package pkg : mPackages.values()) { 8305 if (pkg != pkgInfo) { 8306 // Only replace for packages on requested volume 8307 final String volumeUuid = getVolumeUuidForPackage(pkg); 8308 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8309 && Objects.equals(replaceVolumeUuid, volumeUuid); 8310 grantPermissionsLPw(pkg, replace, changingPkg); 8311 } 8312 } 8313 } 8314 8315 if (pkgInfo != null) { 8316 // Only replace for packages on requested volume 8317 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8318 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8319 && Objects.equals(replaceVolumeUuid, volumeUuid); 8320 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8321 } 8322 } 8323 8324 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8325 String packageOfInterest) { 8326 // IMPORTANT: There are two types of permissions: install and runtime. 8327 // Install time permissions are granted when the app is installed to 8328 // all device users and users added in the future. Runtime permissions 8329 // are granted at runtime explicitly to specific users. Normal and signature 8330 // protected permissions are install time permissions. Dangerous permissions 8331 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8332 // otherwise they are runtime permissions. This function does not manage 8333 // runtime permissions except for the case an app targeting Lollipop MR1 8334 // being upgraded to target a newer SDK, in which case dangerous permissions 8335 // are transformed from install time to runtime ones. 8336 8337 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8338 if (ps == null) { 8339 return; 8340 } 8341 8342 PermissionsState permissionsState = ps.getPermissionsState(); 8343 PermissionsState origPermissions = permissionsState; 8344 8345 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8346 8347 boolean runtimePermissionsRevoked = false; 8348 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8349 8350 boolean changedInstallPermission = false; 8351 8352 if (replace) { 8353 ps.installPermissionsFixed = false; 8354 if (!ps.isSharedUser()) { 8355 origPermissions = new PermissionsState(permissionsState); 8356 permissionsState.reset(); 8357 } else { 8358 // We need to know only about runtime permission changes since the 8359 // calling code always writes the install permissions state but 8360 // the runtime ones are written only if changed. The only cases of 8361 // changed runtime permissions here are promotion of an install to 8362 // runtime and revocation of a runtime from a shared user. 8363 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8364 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8365 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8366 runtimePermissionsRevoked = true; 8367 } 8368 } 8369 } 8370 8371 permissionsState.setGlobalGids(mGlobalGids); 8372 8373 final int N = pkg.requestedPermissions.size(); 8374 for (int i=0; i<N; i++) { 8375 final String name = pkg.requestedPermissions.get(i); 8376 final BasePermission bp = mSettings.mPermissions.get(name); 8377 8378 if (DEBUG_INSTALL) { 8379 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8380 } 8381 8382 if (bp == null || bp.packageSetting == null) { 8383 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8384 Slog.w(TAG, "Unknown permission " + name 8385 + " in package " + pkg.packageName); 8386 } 8387 continue; 8388 } 8389 8390 final String perm = bp.name; 8391 boolean allowedSig = false; 8392 int grant = GRANT_DENIED; 8393 8394 // Keep track of app op permissions. 8395 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8396 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8397 if (pkgs == null) { 8398 pkgs = new ArraySet<>(); 8399 mAppOpPermissionPackages.put(bp.name, pkgs); 8400 } 8401 pkgs.add(pkg.packageName); 8402 } 8403 8404 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8405 switch (level) { 8406 case PermissionInfo.PROTECTION_NORMAL: { 8407 // For all apps normal permissions are install time ones. 8408 grant = GRANT_INSTALL; 8409 } break; 8410 8411 case PermissionInfo.PROTECTION_DANGEROUS: { 8412 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8413 // For legacy apps dangerous permissions are install time ones. 8414 grant = GRANT_INSTALL_LEGACY; 8415 } else if (origPermissions.hasInstallPermission(bp.name)) { 8416 // For legacy apps that became modern, install becomes runtime. 8417 grant = GRANT_UPGRADE; 8418 } else if (mPromoteSystemApps 8419 && isSystemApp(ps) 8420 && mExistingSystemPackages.contains(ps.name)) { 8421 // For legacy system apps, install becomes runtime. 8422 // We cannot check hasInstallPermission() for system apps since those 8423 // permissions were granted implicitly and not persisted pre-M. 8424 grant = GRANT_UPGRADE; 8425 } else { 8426 // For modern apps keep runtime permissions unchanged. 8427 grant = GRANT_RUNTIME; 8428 } 8429 } break; 8430 8431 case PermissionInfo.PROTECTION_SIGNATURE: { 8432 // For all apps signature permissions are install time ones. 8433 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8434 if (allowedSig) { 8435 grant = GRANT_INSTALL; 8436 } 8437 } break; 8438 } 8439 8440 if (DEBUG_INSTALL) { 8441 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8442 } 8443 8444 if (grant != GRANT_DENIED) { 8445 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8446 // If this is an existing, non-system package, then 8447 // we can't add any new permissions to it. 8448 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8449 // Except... if this is a permission that was added 8450 // to the platform (note: need to only do this when 8451 // updating the platform). 8452 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8453 grant = GRANT_DENIED; 8454 } 8455 } 8456 } 8457 8458 switch (grant) { 8459 case GRANT_INSTALL: { 8460 // Revoke this as runtime permission to handle the case of 8461 // a runtime permission being downgraded to an install one. 8462 for (int userId : UserManagerService.getInstance().getUserIds()) { 8463 if (origPermissions.getRuntimePermissionState( 8464 bp.name, userId) != null) { 8465 // Revoke the runtime permission and clear the flags. 8466 origPermissions.revokeRuntimePermission(bp, userId); 8467 origPermissions.updatePermissionFlags(bp, userId, 8468 PackageManager.MASK_PERMISSION_FLAGS, 0); 8469 // If we revoked a permission permission, we have to write. 8470 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8471 changedRuntimePermissionUserIds, userId); 8472 } 8473 } 8474 // Grant an install permission. 8475 if (permissionsState.grantInstallPermission(bp) != 8476 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8477 changedInstallPermission = true; 8478 } 8479 } break; 8480 8481 case GRANT_INSTALL_LEGACY: { 8482 // Grant an install permission. 8483 if (permissionsState.grantInstallPermission(bp) != 8484 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8485 changedInstallPermission = true; 8486 } 8487 } break; 8488 8489 case GRANT_RUNTIME: { 8490 // Grant previously granted runtime permissions. 8491 for (int userId : UserManagerService.getInstance().getUserIds()) { 8492 PermissionState permissionState = origPermissions 8493 .getRuntimePermissionState(bp.name, userId); 8494 final int flags = permissionState != null 8495 ? permissionState.getFlags() : 0; 8496 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8497 if (permissionsState.grantRuntimePermission(bp, userId) == 8498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8499 // If we cannot put the permission as it was, we have to write. 8500 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8501 changedRuntimePermissionUserIds, userId); 8502 } 8503 } 8504 // Propagate the permission flags. 8505 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8506 } 8507 } break; 8508 8509 case GRANT_UPGRADE: { 8510 // Grant runtime permissions for a previously held install permission. 8511 PermissionState permissionState = origPermissions 8512 .getInstallPermissionState(bp.name); 8513 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8514 8515 if (origPermissions.revokeInstallPermission(bp) 8516 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8517 // We will be transferring the permission flags, so clear them. 8518 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8519 PackageManager.MASK_PERMISSION_FLAGS, 0); 8520 changedInstallPermission = true; 8521 } 8522 8523 // If the permission is not to be promoted to runtime we ignore it and 8524 // also its other flags as they are not applicable to install permissions. 8525 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8526 for (int userId : currentUserIds) { 8527 if (permissionsState.grantRuntimePermission(bp, userId) != 8528 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8529 // Transfer the permission flags. 8530 permissionsState.updatePermissionFlags(bp, userId, 8531 flags, flags); 8532 // If we granted the permission, we have to write. 8533 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8534 changedRuntimePermissionUserIds, userId); 8535 } 8536 } 8537 } 8538 } break; 8539 8540 default: { 8541 if (packageOfInterest == null 8542 || packageOfInterest.equals(pkg.packageName)) { 8543 Slog.w(TAG, "Not granting permission " + perm 8544 + " to package " + pkg.packageName 8545 + " because it was previously installed without"); 8546 } 8547 } break; 8548 } 8549 } else { 8550 if (permissionsState.revokeInstallPermission(bp) != 8551 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8552 // Also drop the permission flags. 8553 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8554 PackageManager.MASK_PERMISSION_FLAGS, 0); 8555 changedInstallPermission = true; 8556 Slog.i(TAG, "Un-granting permission " + perm 8557 + " from package " + pkg.packageName 8558 + " (protectionLevel=" + bp.protectionLevel 8559 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8560 + ")"); 8561 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8562 // Don't print warning for app op permissions, since it is fine for them 8563 // not to be granted, there is a UI for the user to decide. 8564 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8565 Slog.w(TAG, "Not granting permission " + perm 8566 + " to package " + pkg.packageName 8567 + " (protectionLevel=" + bp.protectionLevel 8568 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8569 + ")"); 8570 } 8571 } 8572 } 8573 } 8574 8575 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8576 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8577 // This is the first that we have heard about this package, so the 8578 // permissions we have now selected are fixed until explicitly 8579 // changed. 8580 ps.installPermissionsFixed = true; 8581 } 8582 8583 // Persist the runtime permissions state for users with changes. If permissions 8584 // were revoked because no app in the shared user declares them we have to 8585 // write synchronously to avoid losing runtime permissions state. 8586 for (int userId : changedRuntimePermissionUserIds) { 8587 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8588 } 8589 } 8590 8591 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8592 boolean allowed = false; 8593 final int NP = PackageParser.NEW_PERMISSIONS.length; 8594 for (int ip=0; ip<NP; ip++) { 8595 final PackageParser.NewPermissionInfo npi 8596 = PackageParser.NEW_PERMISSIONS[ip]; 8597 if (npi.name.equals(perm) 8598 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8599 allowed = true; 8600 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8601 + pkg.packageName); 8602 break; 8603 } 8604 } 8605 return allowed; 8606 } 8607 8608 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8609 BasePermission bp, PermissionsState origPermissions) { 8610 boolean allowed; 8611 allowed = (compareSignatures( 8612 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8613 == PackageManager.SIGNATURE_MATCH) 8614 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8615 == PackageManager.SIGNATURE_MATCH); 8616 if (!allowed && (bp.protectionLevel 8617 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8618 if (isSystemApp(pkg)) { 8619 // For updated system applications, a system permission 8620 // is granted only if it had been defined by the original application. 8621 if (pkg.isUpdatedSystemApp()) { 8622 final PackageSetting sysPs = mSettings 8623 .getDisabledSystemPkgLPr(pkg.packageName); 8624 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8625 // If the original was granted this permission, we take 8626 // that grant decision as read and propagate it to the 8627 // update. 8628 if (sysPs.isPrivileged()) { 8629 allowed = true; 8630 } 8631 } else { 8632 // The system apk may have been updated with an older 8633 // version of the one on the data partition, but which 8634 // granted a new system permission that it didn't have 8635 // before. In this case we do want to allow the app to 8636 // now get the new permission if the ancestral apk is 8637 // privileged to get it. 8638 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8639 for (int j=0; 8640 j<sysPs.pkg.requestedPermissions.size(); j++) { 8641 if (perm.equals( 8642 sysPs.pkg.requestedPermissions.get(j))) { 8643 allowed = true; 8644 break; 8645 } 8646 } 8647 } 8648 } 8649 } else { 8650 allowed = isPrivilegedApp(pkg); 8651 } 8652 } 8653 } 8654 if (!allowed) { 8655 if (!allowed && (bp.protectionLevel 8656 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8657 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8658 // If this was a previously normal/dangerous permission that got moved 8659 // to a system permission as part of the runtime permission redesign, then 8660 // we still want to blindly grant it to old apps. 8661 allowed = true; 8662 } 8663 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8664 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8665 // If this permission is to be granted to the system installer and 8666 // this app is an installer, then it gets the permission. 8667 allowed = true; 8668 } 8669 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8670 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8671 // If this permission is to be granted to the system verifier and 8672 // this app is a verifier, then it gets the permission. 8673 allowed = true; 8674 } 8675 if (!allowed && (bp.protectionLevel 8676 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8677 && isSystemApp(pkg)) { 8678 // Any pre-installed system app is allowed to get this permission. 8679 allowed = true; 8680 } 8681 if (!allowed && (bp.protectionLevel 8682 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8683 // For development permissions, a development permission 8684 // is granted only if it was already granted. 8685 allowed = origPermissions.hasInstallPermission(perm); 8686 } 8687 } 8688 return allowed; 8689 } 8690 8691 final class ActivityIntentResolver 8692 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8693 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8694 boolean defaultOnly, int userId) { 8695 if (!sUserManager.exists(userId)) return null; 8696 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8697 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8698 } 8699 8700 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8701 int userId) { 8702 if (!sUserManager.exists(userId)) return null; 8703 mFlags = flags; 8704 return super.queryIntent(intent, resolvedType, 8705 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8706 } 8707 8708 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8709 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8710 if (!sUserManager.exists(userId)) return null; 8711 if (packageActivities == null) { 8712 return null; 8713 } 8714 mFlags = flags; 8715 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8716 final int N = packageActivities.size(); 8717 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8718 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8719 8720 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8721 for (int i = 0; i < N; ++i) { 8722 intentFilters = packageActivities.get(i).intents; 8723 if (intentFilters != null && intentFilters.size() > 0) { 8724 PackageParser.ActivityIntentInfo[] array = 8725 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8726 intentFilters.toArray(array); 8727 listCut.add(array); 8728 } 8729 } 8730 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8731 } 8732 8733 public final void addActivity(PackageParser.Activity a, String type) { 8734 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8735 mActivities.put(a.getComponentName(), a); 8736 if (DEBUG_SHOW_INFO) 8737 Log.v( 8738 TAG, " " + type + " " + 8739 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8740 if (DEBUG_SHOW_INFO) 8741 Log.v(TAG, " Class=" + a.info.name); 8742 final int NI = a.intents.size(); 8743 for (int j=0; j<NI; j++) { 8744 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8745 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8746 intent.setPriority(0); 8747 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8748 + a.className + " with priority > 0, forcing to 0"); 8749 } 8750 if (DEBUG_SHOW_INFO) { 8751 Log.v(TAG, " IntentFilter:"); 8752 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8753 } 8754 if (!intent.debugCheck()) { 8755 Log.w(TAG, "==> For Activity " + a.info.name); 8756 } 8757 addFilter(intent); 8758 } 8759 } 8760 8761 public final void removeActivity(PackageParser.Activity a, String type) { 8762 mActivities.remove(a.getComponentName()); 8763 if (DEBUG_SHOW_INFO) { 8764 Log.v(TAG, " " + type + " " 8765 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8766 : a.info.name) + ":"); 8767 Log.v(TAG, " Class=" + a.info.name); 8768 } 8769 final int NI = a.intents.size(); 8770 for (int j=0; j<NI; j++) { 8771 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8772 if (DEBUG_SHOW_INFO) { 8773 Log.v(TAG, " IntentFilter:"); 8774 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8775 } 8776 removeFilter(intent); 8777 } 8778 } 8779 8780 @Override 8781 protected boolean allowFilterResult( 8782 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8783 ActivityInfo filterAi = filter.activity.info; 8784 for (int i=dest.size()-1; i>=0; i--) { 8785 ActivityInfo destAi = dest.get(i).activityInfo; 8786 if (destAi.name == filterAi.name 8787 && destAi.packageName == filterAi.packageName) { 8788 return false; 8789 } 8790 } 8791 return true; 8792 } 8793 8794 @Override 8795 protected ActivityIntentInfo[] newArray(int size) { 8796 return new ActivityIntentInfo[size]; 8797 } 8798 8799 @Override 8800 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8801 if (!sUserManager.exists(userId)) return true; 8802 PackageParser.Package p = filter.activity.owner; 8803 if (p != null) { 8804 PackageSetting ps = (PackageSetting)p.mExtras; 8805 if (ps != null) { 8806 // System apps are never considered stopped for purposes of 8807 // filtering, because there may be no way for the user to 8808 // actually re-launch them. 8809 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8810 && ps.getStopped(userId); 8811 } 8812 } 8813 return false; 8814 } 8815 8816 @Override 8817 protected boolean isPackageForFilter(String packageName, 8818 PackageParser.ActivityIntentInfo info) { 8819 return packageName.equals(info.activity.owner.packageName); 8820 } 8821 8822 @Override 8823 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8824 int match, int userId) { 8825 if (!sUserManager.exists(userId)) return null; 8826 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8827 return null; 8828 } 8829 final PackageParser.Activity activity = info.activity; 8830 if (mSafeMode && (activity.info.applicationInfo.flags 8831 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8832 return null; 8833 } 8834 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8835 if (ps == null) { 8836 return null; 8837 } 8838 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8839 ps.readUserState(userId), userId); 8840 if (ai == null) { 8841 return null; 8842 } 8843 final ResolveInfo res = new ResolveInfo(); 8844 res.activityInfo = ai; 8845 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8846 res.filter = info; 8847 } 8848 if (info != null) { 8849 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8850 } 8851 res.priority = info.getPriority(); 8852 res.preferredOrder = activity.owner.mPreferredOrder; 8853 //System.out.println("Result: " + res.activityInfo.className + 8854 // " = " + res.priority); 8855 res.match = match; 8856 res.isDefault = info.hasDefault; 8857 res.labelRes = info.labelRes; 8858 res.nonLocalizedLabel = info.nonLocalizedLabel; 8859 if (userNeedsBadging(userId)) { 8860 res.noResourceId = true; 8861 } else { 8862 res.icon = info.icon; 8863 } 8864 res.iconResourceId = info.icon; 8865 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8866 return res; 8867 } 8868 8869 @Override 8870 protected void sortResults(List<ResolveInfo> results) { 8871 Collections.sort(results, mResolvePrioritySorter); 8872 } 8873 8874 @Override 8875 protected void dumpFilter(PrintWriter out, String prefix, 8876 PackageParser.ActivityIntentInfo filter) { 8877 out.print(prefix); out.print( 8878 Integer.toHexString(System.identityHashCode(filter.activity))); 8879 out.print(' '); 8880 filter.activity.printComponentShortName(out); 8881 out.print(" filter "); 8882 out.println(Integer.toHexString(System.identityHashCode(filter))); 8883 } 8884 8885 @Override 8886 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8887 return filter.activity; 8888 } 8889 8890 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8891 PackageParser.Activity activity = (PackageParser.Activity)label; 8892 out.print(prefix); out.print( 8893 Integer.toHexString(System.identityHashCode(activity))); 8894 out.print(' '); 8895 activity.printComponentShortName(out); 8896 if (count > 1) { 8897 out.print(" ("); out.print(count); out.print(" filters)"); 8898 } 8899 out.println(); 8900 } 8901 8902// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8903// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8904// final List<ResolveInfo> retList = Lists.newArrayList(); 8905// while (i.hasNext()) { 8906// final ResolveInfo resolveInfo = i.next(); 8907// if (isEnabledLP(resolveInfo.activityInfo)) { 8908// retList.add(resolveInfo); 8909// } 8910// } 8911// return retList; 8912// } 8913 8914 // Keys are String (activity class name), values are Activity. 8915 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8916 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8917 private int mFlags; 8918 } 8919 8920 private final class ServiceIntentResolver 8921 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8923 boolean defaultOnly, int userId) { 8924 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8925 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8926 } 8927 8928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8929 int userId) { 8930 if (!sUserManager.exists(userId)) return null; 8931 mFlags = flags; 8932 return super.queryIntent(intent, resolvedType, 8933 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8934 } 8935 8936 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8937 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8938 if (!sUserManager.exists(userId)) return null; 8939 if (packageServices == null) { 8940 return null; 8941 } 8942 mFlags = flags; 8943 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8944 final int N = packageServices.size(); 8945 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8946 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8947 8948 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8949 for (int i = 0; i < N; ++i) { 8950 intentFilters = packageServices.get(i).intents; 8951 if (intentFilters != null && intentFilters.size() > 0) { 8952 PackageParser.ServiceIntentInfo[] array = 8953 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8954 intentFilters.toArray(array); 8955 listCut.add(array); 8956 } 8957 } 8958 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8959 } 8960 8961 public final void addService(PackageParser.Service s) { 8962 mServices.put(s.getComponentName(), s); 8963 if (DEBUG_SHOW_INFO) { 8964 Log.v(TAG, " " 8965 + (s.info.nonLocalizedLabel != null 8966 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8967 Log.v(TAG, " Class=" + s.info.name); 8968 } 8969 final int NI = s.intents.size(); 8970 int j; 8971 for (j=0; j<NI; j++) { 8972 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8973 if (DEBUG_SHOW_INFO) { 8974 Log.v(TAG, " IntentFilter:"); 8975 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8976 } 8977 if (!intent.debugCheck()) { 8978 Log.w(TAG, "==> For Service " + s.info.name); 8979 } 8980 addFilter(intent); 8981 } 8982 } 8983 8984 public final void removeService(PackageParser.Service s) { 8985 mServices.remove(s.getComponentName()); 8986 if (DEBUG_SHOW_INFO) { 8987 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8988 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8989 Log.v(TAG, " Class=" + s.info.name); 8990 } 8991 final int NI = s.intents.size(); 8992 int j; 8993 for (j=0; j<NI; j++) { 8994 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8995 if (DEBUG_SHOW_INFO) { 8996 Log.v(TAG, " IntentFilter:"); 8997 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8998 } 8999 removeFilter(intent); 9000 } 9001 } 9002 9003 @Override 9004 protected boolean allowFilterResult( 9005 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9006 ServiceInfo filterSi = filter.service.info; 9007 for (int i=dest.size()-1; i>=0; i--) { 9008 ServiceInfo destAi = dest.get(i).serviceInfo; 9009 if (destAi.name == filterSi.name 9010 && destAi.packageName == filterSi.packageName) { 9011 return false; 9012 } 9013 } 9014 return true; 9015 } 9016 9017 @Override 9018 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9019 return new PackageParser.ServiceIntentInfo[size]; 9020 } 9021 9022 @Override 9023 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9024 if (!sUserManager.exists(userId)) return true; 9025 PackageParser.Package p = filter.service.owner; 9026 if (p != null) { 9027 PackageSetting ps = (PackageSetting)p.mExtras; 9028 if (ps != null) { 9029 // System apps are never considered stopped for purposes of 9030 // filtering, because there may be no way for the user to 9031 // actually re-launch them. 9032 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9033 && ps.getStopped(userId); 9034 } 9035 } 9036 return false; 9037 } 9038 9039 @Override 9040 protected boolean isPackageForFilter(String packageName, 9041 PackageParser.ServiceIntentInfo info) { 9042 return packageName.equals(info.service.owner.packageName); 9043 } 9044 9045 @Override 9046 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9047 int match, int userId) { 9048 if (!sUserManager.exists(userId)) return null; 9049 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9050 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9051 return null; 9052 } 9053 final PackageParser.Service service = info.service; 9054 if (mSafeMode && (service.info.applicationInfo.flags 9055 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9056 return null; 9057 } 9058 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9059 if (ps == null) { 9060 return null; 9061 } 9062 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9063 ps.readUserState(userId), userId); 9064 if (si == null) { 9065 return null; 9066 } 9067 final ResolveInfo res = new ResolveInfo(); 9068 res.serviceInfo = si; 9069 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9070 res.filter = filter; 9071 } 9072 res.priority = info.getPriority(); 9073 res.preferredOrder = service.owner.mPreferredOrder; 9074 res.match = match; 9075 res.isDefault = info.hasDefault; 9076 res.labelRes = info.labelRes; 9077 res.nonLocalizedLabel = info.nonLocalizedLabel; 9078 res.icon = info.icon; 9079 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9080 return res; 9081 } 9082 9083 @Override 9084 protected void sortResults(List<ResolveInfo> results) { 9085 Collections.sort(results, mResolvePrioritySorter); 9086 } 9087 9088 @Override 9089 protected void dumpFilter(PrintWriter out, String prefix, 9090 PackageParser.ServiceIntentInfo filter) { 9091 out.print(prefix); out.print( 9092 Integer.toHexString(System.identityHashCode(filter.service))); 9093 out.print(' '); 9094 filter.service.printComponentShortName(out); 9095 out.print(" filter "); 9096 out.println(Integer.toHexString(System.identityHashCode(filter))); 9097 } 9098 9099 @Override 9100 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9101 return filter.service; 9102 } 9103 9104 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9105 PackageParser.Service service = (PackageParser.Service)label; 9106 out.print(prefix); out.print( 9107 Integer.toHexString(System.identityHashCode(service))); 9108 out.print(' '); 9109 service.printComponentShortName(out); 9110 if (count > 1) { 9111 out.print(" ("); out.print(count); out.print(" filters)"); 9112 } 9113 out.println(); 9114 } 9115 9116// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9117// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9118// final List<ResolveInfo> retList = Lists.newArrayList(); 9119// while (i.hasNext()) { 9120// final ResolveInfo resolveInfo = (ResolveInfo) i; 9121// if (isEnabledLP(resolveInfo.serviceInfo)) { 9122// retList.add(resolveInfo); 9123// } 9124// } 9125// return retList; 9126// } 9127 9128 // Keys are String (activity class name), values are Activity. 9129 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9130 = new ArrayMap<ComponentName, PackageParser.Service>(); 9131 private int mFlags; 9132 }; 9133 9134 private final class ProviderIntentResolver 9135 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9136 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9137 boolean defaultOnly, int userId) { 9138 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9139 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9140 } 9141 9142 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9143 int userId) { 9144 if (!sUserManager.exists(userId)) 9145 return null; 9146 mFlags = flags; 9147 return super.queryIntent(intent, resolvedType, 9148 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9149 } 9150 9151 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9152 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9153 if (!sUserManager.exists(userId)) 9154 return null; 9155 if (packageProviders == null) { 9156 return null; 9157 } 9158 mFlags = flags; 9159 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9160 final int N = packageProviders.size(); 9161 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9162 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9163 9164 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9165 for (int i = 0; i < N; ++i) { 9166 intentFilters = packageProviders.get(i).intents; 9167 if (intentFilters != null && intentFilters.size() > 0) { 9168 PackageParser.ProviderIntentInfo[] array = 9169 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9170 intentFilters.toArray(array); 9171 listCut.add(array); 9172 } 9173 } 9174 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9175 } 9176 9177 public final void addProvider(PackageParser.Provider p) { 9178 if (mProviders.containsKey(p.getComponentName())) { 9179 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9180 return; 9181 } 9182 9183 mProviders.put(p.getComponentName(), p); 9184 if (DEBUG_SHOW_INFO) { 9185 Log.v(TAG, " " 9186 + (p.info.nonLocalizedLabel != null 9187 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9188 Log.v(TAG, " Class=" + p.info.name); 9189 } 9190 final int NI = p.intents.size(); 9191 int j; 9192 for (j = 0; j < NI; j++) { 9193 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9194 if (DEBUG_SHOW_INFO) { 9195 Log.v(TAG, " IntentFilter:"); 9196 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9197 } 9198 if (!intent.debugCheck()) { 9199 Log.w(TAG, "==> For Provider " + p.info.name); 9200 } 9201 addFilter(intent); 9202 } 9203 } 9204 9205 public final void removeProvider(PackageParser.Provider p) { 9206 mProviders.remove(p.getComponentName()); 9207 if (DEBUG_SHOW_INFO) { 9208 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9209 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9210 Log.v(TAG, " Class=" + p.info.name); 9211 } 9212 final int NI = p.intents.size(); 9213 int j; 9214 for (j = 0; j < NI; j++) { 9215 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9216 if (DEBUG_SHOW_INFO) { 9217 Log.v(TAG, " IntentFilter:"); 9218 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9219 } 9220 removeFilter(intent); 9221 } 9222 } 9223 9224 @Override 9225 protected boolean allowFilterResult( 9226 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9227 ProviderInfo filterPi = filter.provider.info; 9228 for (int i = dest.size() - 1; i >= 0; i--) { 9229 ProviderInfo destPi = dest.get(i).providerInfo; 9230 if (destPi.name == filterPi.name 9231 && destPi.packageName == filterPi.packageName) { 9232 return false; 9233 } 9234 } 9235 return true; 9236 } 9237 9238 @Override 9239 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9240 return new PackageParser.ProviderIntentInfo[size]; 9241 } 9242 9243 @Override 9244 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9245 if (!sUserManager.exists(userId)) 9246 return true; 9247 PackageParser.Package p = filter.provider.owner; 9248 if (p != null) { 9249 PackageSetting ps = (PackageSetting) p.mExtras; 9250 if (ps != null) { 9251 // System apps are never considered stopped for purposes of 9252 // filtering, because there may be no way for the user to 9253 // actually re-launch them. 9254 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9255 && ps.getStopped(userId); 9256 } 9257 } 9258 return false; 9259 } 9260 9261 @Override 9262 protected boolean isPackageForFilter(String packageName, 9263 PackageParser.ProviderIntentInfo info) { 9264 return packageName.equals(info.provider.owner.packageName); 9265 } 9266 9267 @Override 9268 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9269 int match, int userId) { 9270 if (!sUserManager.exists(userId)) 9271 return null; 9272 final PackageParser.ProviderIntentInfo info = filter; 9273 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9274 return null; 9275 } 9276 final PackageParser.Provider provider = info.provider; 9277 if (mSafeMode && (provider.info.applicationInfo.flags 9278 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9279 return null; 9280 } 9281 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9282 if (ps == null) { 9283 return null; 9284 } 9285 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9286 ps.readUserState(userId), userId); 9287 if (pi == null) { 9288 return null; 9289 } 9290 final ResolveInfo res = new ResolveInfo(); 9291 res.providerInfo = pi; 9292 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9293 res.filter = filter; 9294 } 9295 res.priority = info.getPriority(); 9296 res.preferredOrder = provider.owner.mPreferredOrder; 9297 res.match = match; 9298 res.isDefault = info.hasDefault; 9299 res.labelRes = info.labelRes; 9300 res.nonLocalizedLabel = info.nonLocalizedLabel; 9301 res.icon = info.icon; 9302 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9303 return res; 9304 } 9305 9306 @Override 9307 protected void sortResults(List<ResolveInfo> results) { 9308 Collections.sort(results, mResolvePrioritySorter); 9309 } 9310 9311 @Override 9312 protected void dumpFilter(PrintWriter out, String prefix, 9313 PackageParser.ProviderIntentInfo filter) { 9314 out.print(prefix); 9315 out.print( 9316 Integer.toHexString(System.identityHashCode(filter.provider))); 9317 out.print(' '); 9318 filter.provider.printComponentShortName(out); 9319 out.print(" filter "); 9320 out.println(Integer.toHexString(System.identityHashCode(filter))); 9321 } 9322 9323 @Override 9324 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9325 return filter.provider; 9326 } 9327 9328 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9329 PackageParser.Provider provider = (PackageParser.Provider)label; 9330 out.print(prefix); out.print( 9331 Integer.toHexString(System.identityHashCode(provider))); 9332 out.print(' '); 9333 provider.printComponentShortName(out); 9334 if (count > 1) { 9335 out.print(" ("); out.print(count); out.print(" filters)"); 9336 } 9337 out.println(); 9338 } 9339 9340 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9341 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9342 private int mFlags; 9343 }; 9344 9345 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9346 new Comparator<ResolveInfo>() { 9347 public int compare(ResolveInfo r1, ResolveInfo r2) { 9348 int v1 = r1.priority; 9349 int v2 = r2.priority; 9350 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9351 if (v1 != v2) { 9352 return (v1 > v2) ? -1 : 1; 9353 } 9354 v1 = r1.preferredOrder; 9355 v2 = r2.preferredOrder; 9356 if (v1 != v2) { 9357 return (v1 > v2) ? -1 : 1; 9358 } 9359 if (r1.isDefault != r2.isDefault) { 9360 return r1.isDefault ? -1 : 1; 9361 } 9362 v1 = r1.match; 9363 v2 = r2.match; 9364 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9365 if (v1 != v2) { 9366 return (v1 > v2) ? -1 : 1; 9367 } 9368 if (r1.system != r2.system) { 9369 return r1.system ? -1 : 1; 9370 } 9371 return 0; 9372 } 9373 }; 9374 9375 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9376 new Comparator<ProviderInfo>() { 9377 public int compare(ProviderInfo p1, ProviderInfo p2) { 9378 final int v1 = p1.initOrder; 9379 final int v2 = p2.initOrder; 9380 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9381 } 9382 }; 9383 9384 final void sendPackageBroadcast(final String action, final String pkg, 9385 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9386 final int[] userIds) { 9387 mHandler.post(new Runnable() { 9388 @Override 9389 public void run() { 9390 try { 9391 final IActivityManager am = ActivityManagerNative.getDefault(); 9392 if (am == null) return; 9393 final int[] resolvedUserIds; 9394 if (userIds == null) { 9395 resolvedUserIds = am.getRunningUserIds(); 9396 } else { 9397 resolvedUserIds = userIds; 9398 } 9399 for (int id : resolvedUserIds) { 9400 final Intent intent = new Intent(action, 9401 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9402 if (extras != null) { 9403 intent.putExtras(extras); 9404 } 9405 if (targetPkg != null) { 9406 intent.setPackage(targetPkg); 9407 } 9408 // Modify the UID when posting to other users 9409 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9410 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9411 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9412 intent.putExtra(Intent.EXTRA_UID, uid); 9413 } 9414 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9415 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9416 if (DEBUG_BROADCASTS) { 9417 RuntimeException here = new RuntimeException("here"); 9418 here.fillInStackTrace(); 9419 Slog.d(TAG, "Sending to user " + id + ": " 9420 + intent.toShortString(false, true, false, false) 9421 + " " + intent.getExtras(), here); 9422 } 9423 am.broadcastIntent(null, intent, null, finishedReceiver, 9424 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9425 null, finishedReceiver != null, false, id); 9426 } 9427 } catch (RemoteException ex) { 9428 } 9429 } 9430 }); 9431 } 9432 9433 /** 9434 * Check if the external storage media is available. This is true if there 9435 * is a mounted external storage medium or if the external storage is 9436 * emulated. 9437 */ 9438 private boolean isExternalMediaAvailable() { 9439 return mMediaMounted || Environment.isExternalStorageEmulated(); 9440 } 9441 9442 @Override 9443 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9444 // writer 9445 synchronized (mPackages) { 9446 if (!isExternalMediaAvailable()) { 9447 // If the external storage is no longer mounted at this point, 9448 // the caller may not have been able to delete all of this 9449 // packages files and can not delete any more. Bail. 9450 return null; 9451 } 9452 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9453 if (lastPackage != null) { 9454 pkgs.remove(lastPackage); 9455 } 9456 if (pkgs.size() > 0) { 9457 return pkgs.get(0); 9458 } 9459 } 9460 return null; 9461 } 9462 9463 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9464 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9465 userId, andCode ? 1 : 0, packageName); 9466 if (mSystemReady) { 9467 msg.sendToTarget(); 9468 } else { 9469 if (mPostSystemReadyMessages == null) { 9470 mPostSystemReadyMessages = new ArrayList<>(); 9471 } 9472 mPostSystemReadyMessages.add(msg); 9473 } 9474 } 9475 9476 void startCleaningPackages() { 9477 // reader 9478 synchronized (mPackages) { 9479 if (!isExternalMediaAvailable()) { 9480 return; 9481 } 9482 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9483 return; 9484 } 9485 } 9486 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9487 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9488 IActivityManager am = ActivityManagerNative.getDefault(); 9489 if (am != null) { 9490 try { 9491 am.startService(null, intent, null, mContext.getOpPackageName(), 9492 UserHandle.USER_OWNER); 9493 } catch (RemoteException e) { 9494 } 9495 } 9496 } 9497 9498 @Override 9499 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9500 int installFlags, String installerPackageName, VerificationParams verificationParams, 9501 String packageAbiOverride) { 9502 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9503 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9504 } 9505 9506 @Override 9507 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9508 int installFlags, String installerPackageName, VerificationParams verificationParams, 9509 String packageAbiOverride, int userId) { 9510 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9511 9512 final int callingUid = Binder.getCallingUid(); 9513 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9514 9515 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9516 try { 9517 if (observer != null) { 9518 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9519 } 9520 } catch (RemoteException re) { 9521 } 9522 return; 9523 } 9524 9525 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9526 installFlags |= PackageManager.INSTALL_FROM_ADB; 9527 9528 } else { 9529 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9530 // about installerPackageName. 9531 9532 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9533 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9534 } 9535 9536 UserHandle user; 9537 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9538 user = UserHandle.ALL; 9539 } else { 9540 user = new UserHandle(userId); 9541 } 9542 9543 // Only system components can circumvent runtime permissions when installing. 9544 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9545 && mContext.checkCallingOrSelfPermission(Manifest.permission 9546 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9547 throw new SecurityException("You need the " 9548 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9549 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9550 } 9551 9552 verificationParams.setInstallerUid(callingUid); 9553 9554 final File originFile = new File(originPath); 9555 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9556 9557 final Message msg = mHandler.obtainMessage(INIT_COPY); 9558 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9559 null, verificationParams, user, packageAbiOverride, null); 9560 mHandler.sendMessage(msg); 9561 } 9562 9563 void installStage(String packageName, File stagedDir, String stagedCid, 9564 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9565 String installerPackageName, int installerUid, UserHandle user) { 9566 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9567 params.referrerUri, installerUid, null); 9568 verifParams.setInstallerUid(installerUid); 9569 9570 final OriginInfo origin; 9571 if (stagedDir != null) { 9572 origin = OriginInfo.fromStagedFile(stagedDir); 9573 } else { 9574 origin = OriginInfo.fromStagedContainer(stagedCid); 9575 } 9576 9577 final Message msg = mHandler.obtainMessage(INIT_COPY); 9578 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9579 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9580 params.grantedRuntimePermissions); 9581 mHandler.sendMessage(msg); 9582 } 9583 9584 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9585 Bundle extras = new Bundle(1); 9586 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9587 9588 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9589 packageName, extras, null, null, new int[] {userId}); 9590 try { 9591 IActivityManager am = ActivityManagerNative.getDefault(); 9592 final boolean isSystem = 9593 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9594 if (isSystem && am.isUserRunning(userId, false)) { 9595 // The just-installed/enabled app is bundled on the system, so presumed 9596 // to be able to run automatically without needing an explicit launch. 9597 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9598 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9599 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9600 .setPackage(packageName); 9601 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9602 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9603 } 9604 } catch (RemoteException e) { 9605 // shouldn't happen 9606 Slog.w(TAG, "Unable to bootstrap installed package", e); 9607 } 9608 } 9609 9610 @Override 9611 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9612 int userId) { 9613 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9614 PackageSetting pkgSetting; 9615 final int uid = Binder.getCallingUid(); 9616 enforceCrossUserPermission(uid, userId, true, true, 9617 "setApplicationHiddenSetting for user " + userId); 9618 9619 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9620 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9621 return false; 9622 } 9623 9624 long callingId = Binder.clearCallingIdentity(); 9625 try { 9626 boolean sendAdded = false; 9627 boolean sendRemoved = false; 9628 // writer 9629 synchronized (mPackages) { 9630 pkgSetting = mSettings.mPackages.get(packageName); 9631 if (pkgSetting == null) { 9632 return false; 9633 } 9634 if (pkgSetting.getHidden(userId) != hidden) { 9635 pkgSetting.setHidden(hidden, userId); 9636 mSettings.writePackageRestrictionsLPr(userId); 9637 if (hidden) { 9638 sendRemoved = true; 9639 } else { 9640 sendAdded = true; 9641 } 9642 } 9643 } 9644 if (sendAdded) { 9645 sendPackageAddedForUser(packageName, pkgSetting, userId); 9646 return true; 9647 } 9648 if (sendRemoved) { 9649 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9650 "hiding pkg"); 9651 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9652 return true; 9653 } 9654 } finally { 9655 Binder.restoreCallingIdentity(callingId); 9656 } 9657 return false; 9658 } 9659 9660 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9661 int userId) { 9662 final PackageRemovedInfo info = new PackageRemovedInfo(); 9663 info.removedPackage = packageName; 9664 info.removedUsers = new int[] {userId}; 9665 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9666 info.sendBroadcast(false, false, false); 9667 } 9668 9669 /** 9670 * Returns true if application is not found or there was an error. Otherwise it returns 9671 * the hidden state of the package for the given user. 9672 */ 9673 @Override 9674 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9676 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9677 false, "getApplicationHidden for user " + userId); 9678 PackageSetting pkgSetting; 9679 long callingId = Binder.clearCallingIdentity(); 9680 try { 9681 // writer 9682 synchronized (mPackages) { 9683 pkgSetting = mSettings.mPackages.get(packageName); 9684 if (pkgSetting == null) { 9685 return true; 9686 } 9687 return pkgSetting.getHidden(userId); 9688 } 9689 } finally { 9690 Binder.restoreCallingIdentity(callingId); 9691 } 9692 } 9693 9694 /** 9695 * @hide 9696 */ 9697 @Override 9698 public int installExistingPackageAsUser(String packageName, int userId) { 9699 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9700 null); 9701 PackageSetting pkgSetting; 9702 final int uid = Binder.getCallingUid(); 9703 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9704 + userId); 9705 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9706 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9707 } 9708 9709 long callingId = Binder.clearCallingIdentity(); 9710 try { 9711 boolean sendAdded = false; 9712 9713 // writer 9714 synchronized (mPackages) { 9715 pkgSetting = mSettings.mPackages.get(packageName); 9716 if (pkgSetting == null) { 9717 return PackageManager.INSTALL_FAILED_INVALID_URI; 9718 } 9719 if (!pkgSetting.getInstalled(userId)) { 9720 pkgSetting.setInstalled(true, userId); 9721 pkgSetting.setHidden(false, userId); 9722 mSettings.writePackageRestrictionsLPr(userId); 9723 sendAdded = true; 9724 } 9725 } 9726 9727 if (sendAdded) { 9728 sendPackageAddedForUser(packageName, pkgSetting, userId); 9729 } 9730 } finally { 9731 Binder.restoreCallingIdentity(callingId); 9732 } 9733 9734 return PackageManager.INSTALL_SUCCEEDED; 9735 } 9736 9737 boolean isUserRestricted(int userId, String restrictionKey) { 9738 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9739 if (restrictions.getBoolean(restrictionKey, false)) { 9740 Log.w(TAG, "User is restricted: " + restrictionKey); 9741 return true; 9742 } 9743 return false; 9744 } 9745 9746 @Override 9747 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9748 mContext.enforceCallingOrSelfPermission( 9749 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9750 "Only package verification agents can verify applications"); 9751 9752 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9753 final PackageVerificationResponse response = new PackageVerificationResponse( 9754 verificationCode, Binder.getCallingUid()); 9755 msg.arg1 = id; 9756 msg.obj = response; 9757 mHandler.sendMessage(msg); 9758 } 9759 9760 @Override 9761 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9762 long millisecondsToDelay) { 9763 mContext.enforceCallingOrSelfPermission( 9764 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9765 "Only package verification agents can extend verification timeouts"); 9766 9767 final PackageVerificationState state = mPendingVerification.get(id); 9768 final PackageVerificationResponse response = new PackageVerificationResponse( 9769 verificationCodeAtTimeout, Binder.getCallingUid()); 9770 9771 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9772 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9773 } 9774 if (millisecondsToDelay < 0) { 9775 millisecondsToDelay = 0; 9776 } 9777 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9778 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9779 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9780 } 9781 9782 if ((state != null) && !state.timeoutExtended()) { 9783 state.extendTimeout(); 9784 9785 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9786 msg.arg1 = id; 9787 msg.obj = response; 9788 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9789 } 9790 } 9791 9792 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9793 int verificationCode, UserHandle user) { 9794 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9795 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9796 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9797 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9798 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9799 9800 mContext.sendBroadcastAsUser(intent, user, 9801 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9802 } 9803 9804 private ComponentName matchComponentForVerifier(String packageName, 9805 List<ResolveInfo> receivers) { 9806 ActivityInfo targetReceiver = null; 9807 9808 final int NR = receivers.size(); 9809 for (int i = 0; i < NR; i++) { 9810 final ResolveInfo info = receivers.get(i); 9811 if (info.activityInfo == null) { 9812 continue; 9813 } 9814 9815 if (packageName.equals(info.activityInfo.packageName)) { 9816 targetReceiver = info.activityInfo; 9817 break; 9818 } 9819 } 9820 9821 if (targetReceiver == null) { 9822 return null; 9823 } 9824 9825 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9826 } 9827 9828 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9829 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9830 if (pkgInfo.verifiers.length == 0) { 9831 return null; 9832 } 9833 9834 final int N = pkgInfo.verifiers.length; 9835 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9836 for (int i = 0; i < N; i++) { 9837 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9838 9839 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9840 receivers); 9841 if (comp == null) { 9842 continue; 9843 } 9844 9845 final int verifierUid = getUidForVerifier(verifierInfo); 9846 if (verifierUid == -1) { 9847 continue; 9848 } 9849 9850 if (DEBUG_VERIFY) { 9851 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9852 + " with the correct signature"); 9853 } 9854 sufficientVerifiers.add(comp); 9855 verificationState.addSufficientVerifier(verifierUid); 9856 } 9857 9858 return sufficientVerifiers; 9859 } 9860 9861 private int getUidForVerifier(VerifierInfo verifierInfo) { 9862 synchronized (mPackages) { 9863 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9864 if (pkg == null) { 9865 return -1; 9866 } else if (pkg.mSignatures.length != 1) { 9867 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9868 + " has more than one signature; ignoring"); 9869 return -1; 9870 } 9871 9872 /* 9873 * If the public key of the package's signature does not match 9874 * our expected public key, then this is a different package and 9875 * we should skip. 9876 */ 9877 9878 final byte[] expectedPublicKey; 9879 try { 9880 final Signature verifierSig = pkg.mSignatures[0]; 9881 final PublicKey publicKey = verifierSig.getPublicKey(); 9882 expectedPublicKey = publicKey.getEncoded(); 9883 } catch (CertificateException e) { 9884 return -1; 9885 } 9886 9887 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9888 9889 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9890 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9891 + " does not have the expected public key; ignoring"); 9892 return -1; 9893 } 9894 9895 return pkg.applicationInfo.uid; 9896 } 9897 } 9898 9899 @Override 9900 public void finishPackageInstall(int token) { 9901 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9902 9903 if (DEBUG_INSTALL) { 9904 Slog.v(TAG, "BM finishing package install for " + token); 9905 } 9906 9907 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9908 mHandler.sendMessage(msg); 9909 } 9910 9911 /** 9912 * Get the verification agent timeout. 9913 * 9914 * @return verification timeout in milliseconds 9915 */ 9916 private long getVerificationTimeout() { 9917 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9918 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9919 DEFAULT_VERIFICATION_TIMEOUT); 9920 } 9921 9922 /** 9923 * Get the default verification agent response code. 9924 * 9925 * @return default verification response code 9926 */ 9927 private int getDefaultVerificationResponse() { 9928 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9929 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9930 DEFAULT_VERIFICATION_RESPONSE); 9931 } 9932 9933 /** 9934 * Check whether or not package verification has been enabled. 9935 * 9936 * @return true if verification should be performed 9937 */ 9938 private boolean isVerificationEnabled(int userId, int installFlags) { 9939 if (!DEFAULT_VERIFY_ENABLE) { 9940 return false; 9941 } 9942 9943 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9944 9945 // Check if installing from ADB 9946 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9947 // Do not run verification in a test harness environment 9948 if (ActivityManager.isRunningInTestHarness()) { 9949 return false; 9950 } 9951 if (ensureVerifyAppsEnabled) { 9952 return true; 9953 } 9954 // Check if the developer does not want package verification for ADB installs 9955 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9956 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9957 return false; 9958 } 9959 } 9960 9961 if (ensureVerifyAppsEnabled) { 9962 return true; 9963 } 9964 9965 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9966 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9967 } 9968 9969 @Override 9970 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9971 throws RemoteException { 9972 mContext.enforceCallingOrSelfPermission( 9973 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9974 "Only intentfilter verification agents can verify applications"); 9975 9976 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9977 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9978 Binder.getCallingUid(), verificationCode, failedDomains); 9979 msg.arg1 = id; 9980 msg.obj = response; 9981 mHandler.sendMessage(msg); 9982 } 9983 9984 @Override 9985 public int getIntentVerificationStatus(String packageName, int userId) { 9986 synchronized (mPackages) { 9987 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9988 } 9989 } 9990 9991 @Override 9992 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9993 mContext.enforceCallingOrSelfPermission( 9994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9995 9996 boolean result = false; 9997 synchronized (mPackages) { 9998 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9999 } 10000 if (result) { 10001 scheduleWritePackageRestrictionsLocked(userId); 10002 } 10003 return result; 10004 } 10005 10006 @Override 10007 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10008 synchronized (mPackages) { 10009 return mSettings.getIntentFilterVerificationsLPr(packageName); 10010 } 10011 } 10012 10013 @Override 10014 public List<IntentFilter> getAllIntentFilters(String packageName) { 10015 if (TextUtils.isEmpty(packageName)) { 10016 return Collections.<IntentFilter>emptyList(); 10017 } 10018 synchronized (mPackages) { 10019 PackageParser.Package pkg = mPackages.get(packageName); 10020 if (pkg == null || pkg.activities == null) { 10021 return Collections.<IntentFilter>emptyList(); 10022 } 10023 final int count = pkg.activities.size(); 10024 ArrayList<IntentFilter> result = new ArrayList<>(); 10025 for (int n=0; n<count; n++) { 10026 PackageParser.Activity activity = pkg.activities.get(n); 10027 if (activity.intents != null || activity.intents.size() > 0) { 10028 result.addAll(activity.intents); 10029 } 10030 } 10031 return result; 10032 } 10033 } 10034 10035 @Override 10036 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10037 mContext.enforceCallingOrSelfPermission( 10038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10039 10040 synchronized (mPackages) { 10041 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10042 if (packageName != null) { 10043 result |= updateIntentVerificationStatus(packageName, 10044 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10045 userId); 10046 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10047 packageName, userId); 10048 } 10049 return result; 10050 } 10051 } 10052 10053 @Override 10054 public String getDefaultBrowserPackageName(int userId) { 10055 synchronized (mPackages) { 10056 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10057 } 10058 } 10059 10060 /** 10061 * Get the "allow unknown sources" setting. 10062 * 10063 * @return the current "allow unknown sources" setting 10064 */ 10065 private int getUnknownSourcesSettings() { 10066 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10067 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10068 -1); 10069 } 10070 10071 @Override 10072 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10073 final int uid = Binder.getCallingUid(); 10074 // writer 10075 synchronized (mPackages) { 10076 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10077 if (targetPackageSetting == null) { 10078 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10079 } 10080 10081 PackageSetting installerPackageSetting; 10082 if (installerPackageName != null) { 10083 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10084 if (installerPackageSetting == null) { 10085 throw new IllegalArgumentException("Unknown installer package: " 10086 + installerPackageName); 10087 } 10088 } else { 10089 installerPackageSetting = null; 10090 } 10091 10092 Signature[] callerSignature; 10093 Object obj = mSettings.getUserIdLPr(uid); 10094 if (obj != null) { 10095 if (obj instanceof SharedUserSetting) { 10096 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10097 } else if (obj instanceof PackageSetting) { 10098 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10099 } else { 10100 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10101 } 10102 } else { 10103 throw new SecurityException("Unknown calling uid " + uid); 10104 } 10105 10106 // Verify: can't set installerPackageName to a package that is 10107 // not signed with the same cert as the caller. 10108 if (installerPackageSetting != null) { 10109 if (compareSignatures(callerSignature, 10110 installerPackageSetting.signatures.mSignatures) 10111 != PackageManager.SIGNATURE_MATCH) { 10112 throw new SecurityException( 10113 "Caller does not have same cert as new installer package " 10114 + installerPackageName); 10115 } 10116 } 10117 10118 // Verify: if target already has an installer package, it must 10119 // be signed with the same cert as the caller. 10120 if (targetPackageSetting.installerPackageName != null) { 10121 PackageSetting setting = mSettings.mPackages.get( 10122 targetPackageSetting.installerPackageName); 10123 // If the currently set package isn't valid, then it's always 10124 // okay to change it. 10125 if (setting != null) { 10126 if (compareSignatures(callerSignature, 10127 setting.signatures.mSignatures) 10128 != PackageManager.SIGNATURE_MATCH) { 10129 throw new SecurityException( 10130 "Caller does not have same cert as old installer package " 10131 + targetPackageSetting.installerPackageName); 10132 } 10133 } 10134 } 10135 10136 // Okay! 10137 targetPackageSetting.installerPackageName = installerPackageName; 10138 scheduleWriteSettingsLocked(); 10139 } 10140 } 10141 10142 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10143 // Queue up an async operation since the package installation may take a little while. 10144 mHandler.post(new Runnable() { 10145 public void run() { 10146 mHandler.removeCallbacks(this); 10147 // Result object to be returned 10148 PackageInstalledInfo res = new PackageInstalledInfo(); 10149 res.returnCode = currentStatus; 10150 res.uid = -1; 10151 res.pkg = null; 10152 res.removedInfo = new PackageRemovedInfo(); 10153 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10154 args.doPreInstall(res.returnCode); 10155 synchronized (mInstallLock) { 10156 installPackageLI(args, res); 10157 } 10158 args.doPostInstall(res.returnCode, res.uid); 10159 } 10160 10161 // A restore should be performed at this point if (a) the install 10162 // succeeded, (b) the operation is not an update, and (c) the new 10163 // package has not opted out of backup participation. 10164 final boolean update = res.removedInfo.removedPackage != null; 10165 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10166 boolean doRestore = !update 10167 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10168 10169 // Set up the post-install work request bookkeeping. This will be used 10170 // and cleaned up by the post-install event handling regardless of whether 10171 // there's a restore pass performed. Token values are >= 1. 10172 int token; 10173 if (mNextInstallToken < 0) mNextInstallToken = 1; 10174 token = mNextInstallToken++; 10175 10176 PostInstallData data = new PostInstallData(args, res); 10177 mRunningInstalls.put(token, data); 10178 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10179 10180 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10181 // Pass responsibility to the Backup Manager. It will perform a 10182 // restore if appropriate, then pass responsibility back to the 10183 // Package Manager to run the post-install observer callbacks 10184 // and broadcasts. 10185 IBackupManager bm = IBackupManager.Stub.asInterface( 10186 ServiceManager.getService(Context.BACKUP_SERVICE)); 10187 if (bm != null) { 10188 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10189 + " to BM for possible restore"); 10190 try { 10191 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10192 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10193 } else { 10194 doRestore = false; 10195 } 10196 } catch (RemoteException e) { 10197 // can't happen; the backup manager is local 10198 } catch (Exception e) { 10199 Slog.e(TAG, "Exception trying to enqueue restore", e); 10200 doRestore = false; 10201 } 10202 } else { 10203 Slog.e(TAG, "Backup Manager not found!"); 10204 doRestore = false; 10205 } 10206 } 10207 10208 if (!doRestore) { 10209 // No restore possible, or the Backup Manager was mysteriously not 10210 // available -- just fire the post-install work request directly. 10211 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10212 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10213 mHandler.sendMessage(msg); 10214 } 10215 } 10216 }); 10217 } 10218 10219 private abstract class HandlerParams { 10220 private static final int MAX_RETRIES = 4; 10221 10222 /** 10223 * Number of times startCopy() has been attempted and had a non-fatal 10224 * error. 10225 */ 10226 private int mRetries = 0; 10227 10228 /** User handle for the user requesting the information or installation. */ 10229 private final UserHandle mUser; 10230 10231 HandlerParams(UserHandle user) { 10232 mUser = user; 10233 } 10234 10235 UserHandle getUser() { 10236 return mUser; 10237 } 10238 10239 final boolean startCopy() { 10240 boolean res; 10241 try { 10242 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10243 10244 if (++mRetries > MAX_RETRIES) { 10245 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10246 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10247 handleServiceError(); 10248 return false; 10249 } else { 10250 handleStartCopy(); 10251 res = true; 10252 } 10253 } catch (RemoteException e) { 10254 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10255 mHandler.sendEmptyMessage(MCS_RECONNECT); 10256 res = false; 10257 } 10258 handleReturnCode(); 10259 return res; 10260 } 10261 10262 final void serviceError() { 10263 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10264 handleServiceError(); 10265 handleReturnCode(); 10266 } 10267 10268 abstract void handleStartCopy() throws RemoteException; 10269 abstract void handleServiceError(); 10270 abstract void handleReturnCode(); 10271 } 10272 10273 class MeasureParams extends HandlerParams { 10274 private final PackageStats mStats; 10275 private boolean mSuccess; 10276 10277 private final IPackageStatsObserver mObserver; 10278 10279 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10280 super(new UserHandle(stats.userHandle)); 10281 mObserver = observer; 10282 mStats = stats; 10283 } 10284 10285 @Override 10286 public String toString() { 10287 return "MeasureParams{" 10288 + Integer.toHexString(System.identityHashCode(this)) 10289 + " " + mStats.packageName + "}"; 10290 } 10291 10292 @Override 10293 void handleStartCopy() throws RemoteException { 10294 synchronized (mInstallLock) { 10295 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10296 } 10297 10298 if (mSuccess) { 10299 final boolean mounted; 10300 if (Environment.isExternalStorageEmulated()) { 10301 mounted = true; 10302 } else { 10303 final String status = Environment.getExternalStorageState(); 10304 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10305 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10306 } 10307 10308 if (mounted) { 10309 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10310 10311 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10312 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10313 10314 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10315 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10316 10317 // Always subtract cache size, since it's a subdirectory 10318 mStats.externalDataSize -= mStats.externalCacheSize; 10319 10320 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10321 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10322 10323 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10324 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10325 } 10326 } 10327 } 10328 10329 @Override 10330 void handleReturnCode() { 10331 if (mObserver != null) { 10332 try { 10333 mObserver.onGetStatsCompleted(mStats, mSuccess); 10334 } catch (RemoteException e) { 10335 Slog.i(TAG, "Observer no longer exists."); 10336 } 10337 } 10338 } 10339 10340 @Override 10341 void handleServiceError() { 10342 Slog.e(TAG, "Could not measure application " + mStats.packageName 10343 + " external storage"); 10344 } 10345 } 10346 10347 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10348 throws RemoteException { 10349 long result = 0; 10350 for (File path : paths) { 10351 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10352 } 10353 return result; 10354 } 10355 10356 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10357 for (File path : paths) { 10358 try { 10359 mcs.clearDirectory(path.getAbsolutePath()); 10360 } catch (RemoteException e) { 10361 } 10362 } 10363 } 10364 10365 static class OriginInfo { 10366 /** 10367 * Location where install is coming from, before it has been 10368 * copied/renamed into place. This could be a single monolithic APK 10369 * file, or a cluster directory. This location may be untrusted. 10370 */ 10371 final File file; 10372 final String cid; 10373 10374 /** 10375 * Flag indicating that {@link #file} or {@link #cid} has already been 10376 * staged, meaning downstream users don't need to defensively copy the 10377 * contents. 10378 */ 10379 final boolean staged; 10380 10381 /** 10382 * Flag indicating that {@link #file} or {@link #cid} is an already 10383 * installed app that is being moved. 10384 */ 10385 final boolean existing; 10386 10387 final String resolvedPath; 10388 final File resolvedFile; 10389 10390 static OriginInfo fromNothing() { 10391 return new OriginInfo(null, null, false, false); 10392 } 10393 10394 static OriginInfo fromUntrustedFile(File file) { 10395 return new OriginInfo(file, null, false, false); 10396 } 10397 10398 static OriginInfo fromExistingFile(File file) { 10399 return new OriginInfo(file, null, false, true); 10400 } 10401 10402 static OriginInfo fromStagedFile(File file) { 10403 return new OriginInfo(file, null, true, false); 10404 } 10405 10406 static OriginInfo fromStagedContainer(String cid) { 10407 return new OriginInfo(null, cid, true, false); 10408 } 10409 10410 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10411 this.file = file; 10412 this.cid = cid; 10413 this.staged = staged; 10414 this.existing = existing; 10415 10416 if (cid != null) { 10417 resolvedPath = PackageHelper.getSdDir(cid); 10418 resolvedFile = new File(resolvedPath); 10419 } else if (file != null) { 10420 resolvedPath = file.getAbsolutePath(); 10421 resolvedFile = file; 10422 } else { 10423 resolvedPath = null; 10424 resolvedFile = null; 10425 } 10426 } 10427 } 10428 10429 class MoveInfo { 10430 final int moveId; 10431 final String fromUuid; 10432 final String toUuid; 10433 final String packageName; 10434 final String dataAppName; 10435 final int appId; 10436 final String seinfo; 10437 10438 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10439 String dataAppName, int appId, String seinfo) { 10440 this.moveId = moveId; 10441 this.fromUuid = fromUuid; 10442 this.toUuid = toUuid; 10443 this.packageName = packageName; 10444 this.dataAppName = dataAppName; 10445 this.appId = appId; 10446 this.seinfo = seinfo; 10447 } 10448 } 10449 10450 class InstallParams extends HandlerParams { 10451 final OriginInfo origin; 10452 final MoveInfo move; 10453 final IPackageInstallObserver2 observer; 10454 int installFlags; 10455 final String installerPackageName; 10456 final String volumeUuid; 10457 final VerificationParams verificationParams; 10458 private InstallArgs mArgs; 10459 private int mRet; 10460 final String packageAbiOverride; 10461 final String[] grantedRuntimePermissions; 10462 10463 10464 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10465 int installFlags, String installerPackageName, String volumeUuid, 10466 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10467 String[] grantedPermissions) { 10468 super(user); 10469 this.origin = origin; 10470 this.move = move; 10471 this.observer = observer; 10472 this.installFlags = installFlags; 10473 this.installerPackageName = installerPackageName; 10474 this.volumeUuid = volumeUuid; 10475 this.verificationParams = verificationParams; 10476 this.packageAbiOverride = packageAbiOverride; 10477 this.grantedRuntimePermissions = grantedPermissions; 10478 } 10479 10480 @Override 10481 public String toString() { 10482 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10483 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10484 } 10485 10486 public ManifestDigest getManifestDigest() { 10487 if (verificationParams == null) { 10488 return null; 10489 } 10490 return verificationParams.getManifestDigest(); 10491 } 10492 10493 private int installLocationPolicy(PackageInfoLite pkgLite) { 10494 String packageName = pkgLite.packageName; 10495 int installLocation = pkgLite.installLocation; 10496 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10497 // reader 10498 synchronized (mPackages) { 10499 PackageParser.Package pkg = mPackages.get(packageName); 10500 if (pkg != null) { 10501 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10502 // Check for downgrading. 10503 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10504 try { 10505 checkDowngrade(pkg, pkgLite); 10506 } catch (PackageManagerException e) { 10507 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10508 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10509 } 10510 } 10511 // Check for updated system application. 10512 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10513 if (onSd) { 10514 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10515 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10516 } 10517 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10518 } else { 10519 if (onSd) { 10520 // Install flag overrides everything. 10521 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10522 } 10523 // If current upgrade specifies particular preference 10524 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10525 // Application explicitly specified internal. 10526 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10527 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10528 // App explictly prefers external. Let policy decide 10529 } else { 10530 // Prefer previous location 10531 if (isExternal(pkg)) { 10532 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10533 } 10534 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10535 } 10536 } 10537 } else { 10538 // Invalid install. Return error code 10539 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10540 } 10541 } 10542 } 10543 // All the special cases have been taken care of. 10544 // Return result based on recommended install location. 10545 if (onSd) { 10546 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10547 } 10548 return pkgLite.recommendedInstallLocation; 10549 } 10550 10551 /* 10552 * Invoke remote method to get package information and install 10553 * location values. Override install location based on default 10554 * policy if needed and then create install arguments based 10555 * on the install location. 10556 */ 10557 public void handleStartCopy() throws RemoteException { 10558 int ret = PackageManager.INSTALL_SUCCEEDED; 10559 10560 // If we're already staged, we've firmly committed to an install location 10561 if (origin.staged) { 10562 if (origin.file != null) { 10563 installFlags |= PackageManager.INSTALL_INTERNAL; 10564 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10565 } else if (origin.cid != null) { 10566 installFlags |= PackageManager.INSTALL_EXTERNAL; 10567 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10568 } else { 10569 throw new IllegalStateException("Invalid stage location"); 10570 } 10571 } 10572 10573 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10574 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10575 10576 PackageInfoLite pkgLite = null; 10577 10578 if (onInt && onSd) { 10579 // Check if both bits are set. 10580 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10581 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10582 } else { 10583 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10584 packageAbiOverride); 10585 10586 /* 10587 * If we have too little free space, try to free cache 10588 * before giving up. 10589 */ 10590 if (!origin.staged && pkgLite.recommendedInstallLocation 10591 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10592 // TODO: focus freeing disk space on the target device 10593 final StorageManager storage = StorageManager.from(mContext); 10594 final long lowThreshold = storage.getStorageLowBytes( 10595 Environment.getDataDirectory()); 10596 10597 final long sizeBytes = mContainerService.calculateInstalledSize( 10598 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10599 10600 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10601 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10602 installFlags, packageAbiOverride); 10603 } 10604 10605 /* 10606 * The cache free must have deleted the file we 10607 * downloaded to install. 10608 * 10609 * TODO: fix the "freeCache" call to not delete 10610 * the file we care about. 10611 */ 10612 if (pkgLite.recommendedInstallLocation 10613 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10614 pkgLite.recommendedInstallLocation 10615 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10616 } 10617 } 10618 } 10619 10620 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10621 int loc = pkgLite.recommendedInstallLocation; 10622 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10623 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10624 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10625 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10626 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10627 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10629 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10631 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10632 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10633 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10634 } else { 10635 // Override with defaults if needed. 10636 loc = installLocationPolicy(pkgLite); 10637 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10638 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10639 } else if (!onSd && !onInt) { 10640 // Override install location with flags 10641 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10642 // Set the flag to install on external media. 10643 installFlags |= PackageManager.INSTALL_EXTERNAL; 10644 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10645 } else { 10646 // Make sure the flag for installing on external 10647 // media is unset 10648 installFlags |= PackageManager.INSTALL_INTERNAL; 10649 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10650 } 10651 } 10652 } 10653 } 10654 10655 final InstallArgs args = createInstallArgs(this); 10656 mArgs = args; 10657 10658 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10659 /* 10660 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10661 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10662 */ 10663 int userIdentifier = getUser().getIdentifier(); 10664 if (userIdentifier == UserHandle.USER_ALL 10665 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10666 userIdentifier = UserHandle.USER_OWNER; 10667 } 10668 10669 /* 10670 * Determine if we have any installed package verifiers. If we 10671 * do, then we'll defer to them to verify the packages. 10672 */ 10673 final int requiredUid = mRequiredVerifierPackage == null ? -1 10674 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10675 if (!origin.existing && requiredUid != -1 10676 && isVerificationEnabled(userIdentifier, installFlags)) { 10677 final Intent verification = new Intent( 10678 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10679 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10680 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10681 PACKAGE_MIME_TYPE); 10682 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10683 10684 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10685 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10686 0 /* TODO: Which userId? */); 10687 10688 if (DEBUG_VERIFY) { 10689 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10690 + verification.toString() + " with " + pkgLite.verifiers.length 10691 + " optional verifiers"); 10692 } 10693 10694 final int verificationId = mPendingVerificationToken++; 10695 10696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10697 10698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10699 installerPackageName); 10700 10701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10702 installFlags); 10703 10704 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10705 pkgLite.packageName); 10706 10707 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10708 pkgLite.versionCode); 10709 10710 if (verificationParams != null) { 10711 if (verificationParams.getVerificationURI() != null) { 10712 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10713 verificationParams.getVerificationURI()); 10714 } 10715 if (verificationParams.getOriginatingURI() != null) { 10716 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10717 verificationParams.getOriginatingURI()); 10718 } 10719 if (verificationParams.getReferrer() != null) { 10720 verification.putExtra(Intent.EXTRA_REFERRER, 10721 verificationParams.getReferrer()); 10722 } 10723 if (verificationParams.getOriginatingUid() >= 0) { 10724 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10725 verificationParams.getOriginatingUid()); 10726 } 10727 if (verificationParams.getInstallerUid() >= 0) { 10728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10729 verificationParams.getInstallerUid()); 10730 } 10731 } 10732 10733 final PackageVerificationState verificationState = new PackageVerificationState( 10734 requiredUid, args); 10735 10736 mPendingVerification.append(verificationId, verificationState); 10737 10738 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10739 receivers, verificationState); 10740 10741 // Apps installed for "all" users use the device owner to verify the app 10742 UserHandle verifierUser = getUser(); 10743 if (verifierUser == UserHandle.ALL) { 10744 verifierUser = UserHandle.OWNER; 10745 } 10746 10747 /* 10748 * If any sufficient verifiers were listed in the package 10749 * manifest, attempt to ask them. 10750 */ 10751 if (sufficientVerifiers != null) { 10752 final int N = sufficientVerifiers.size(); 10753 if (N == 0) { 10754 Slog.i(TAG, "Additional verifiers required, but none installed."); 10755 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10756 } else { 10757 for (int i = 0; i < N; i++) { 10758 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10759 10760 final Intent sufficientIntent = new Intent(verification); 10761 sufficientIntent.setComponent(verifierComponent); 10762 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10763 } 10764 } 10765 } 10766 10767 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10768 mRequiredVerifierPackage, receivers); 10769 if (ret == PackageManager.INSTALL_SUCCEEDED 10770 && mRequiredVerifierPackage != null) { 10771 /* 10772 * Send the intent to the required verification agent, 10773 * but only start the verification timeout after the 10774 * target BroadcastReceivers have run. 10775 */ 10776 verification.setComponent(requiredVerifierComponent); 10777 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10778 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10779 new BroadcastReceiver() { 10780 @Override 10781 public void onReceive(Context context, Intent intent) { 10782 final Message msg = mHandler 10783 .obtainMessage(CHECK_PENDING_VERIFICATION); 10784 msg.arg1 = verificationId; 10785 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10786 } 10787 }, null, 0, null, null); 10788 10789 /* 10790 * We don't want the copy to proceed until verification 10791 * succeeds, so null out this field. 10792 */ 10793 mArgs = null; 10794 } 10795 } else { 10796 /* 10797 * No package verification is enabled, so immediately start 10798 * the remote call to initiate copy using temporary file. 10799 */ 10800 ret = args.copyApk(mContainerService, true); 10801 } 10802 } 10803 10804 mRet = ret; 10805 } 10806 10807 @Override 10808 void handleReturnCode() { 10809 // If mArgs is null, then MCS couldn't be reached. When it 10810 // reconnects, it will try again to install. At that point, this 10811 // will succeed. 10812 if (mArgs != null) { 10813 processPendingInstall(mArgs, mRet); 10814 } 10815 } 10816 10817 @Override 10818 void handleServiceError() { 10819 mArgs = createInstallArgs(this); 10820 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10821 } 10822 10823 public boolean isForwardLocked() { 10824 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10825 } 10826 } 10827 10828 /** 10829 * Used during creation of InstallArgs 10830 * 10831 * @param installFlags package installation flags 10832 * @return true if should be installed on external storage 10833 */ 10834 private static boolean installOnExternalAsec(int installFlags) { 10835 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10836 return false; 10837 } 10838 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10839 return true; 10840 } 10841 return false; 10842 } 10843 10844 /** 10845 * Used during creation of InstallArgs 10846 * 10847 * @param installFlags package installation flags 10848 * @return true if should be installed as forward locked 10849 */ 10850 private static boolean installForwardLocked(int installFlags) { 10851 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10852 } 10853 10854 private InstallArgs createInstallArgs(InstallParams params) { 10855 if (params.move != null) { 10856 return new MoveInstallArgs(params); 10857 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10858 return new AsecInstallArgs(params); 10859 } else { 10860 return new FileInstallArgs(params); 10861 } 10862 } 10863 10864 /** 10865 * Create args that describe an existing installed package. Typically used 10866 * when cleaning up old installs, or used as a move source. 10867 */ 10868 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10869 String resourcePath, String[] instructionSets) { 10870 final boolean isInAsec; 10871 if (installOnExternalAsec(installFlags)) { 10872 /* Apps on SD card are always in ASEC containers. */ 10873 isInAsec = true; 10874 } else if (installForwardLocked(installFlags) 10875 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10876 /* 10877 * Forward-locked apps are only in ASEC containers if they're the 10878 * new style 10879 */ 10880 isInAsec = true; 10881 } else { 10882 isInAsec = false; 10883 } 10884 10885 if (isInAsec) { 10886 return new AsecInstallArgs(codePath, instructionSets, 10887 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10888 } else { 10889 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10890 } 10891 } 10892 10893 static abstract class InstallArgs { 10894 /** @see InstallParams#origin */ 10895 final OriginInfo origin; 10896 /** @see InstallParams#move */ 10897 final MoveInfo move; 10898 10899 final IPackageInstallObserver2 observer; 10900 // Always refers to PackageManager flags only 10901 final int installFlags; 10902 final String installerPackageName; 10903 final String volumeUuid; 10904 final ManifestDigest manifestDigest; 10905 final UserHandle user; 10906 final String abiOverride; 10907 final String[] installGrantPermissions; 10908 10909 // The list of instruction sets supported by this app. This is currently 10910 // only used during the rmdex() phase to clean up resources. We can get rid of this 10911 // if we move dex files under the common app path. 10912 /* nullable */ String[] instructionSets; 10913 10914 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10915 int installFlags, String installerPackageName, String volumeUuid, 10916 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10917 String abiOverride, String[] installGrantPermissions) { 10918 this.origin = origin; 10919 this.move = move; 10920 this.installFlags = installFlags; 10921 this.observer = observer; 10922 this.installerPackageName = installerPackageName; 10923 this.volumeUuid = volumeUuid; 10924 this.manifestDigest = manifestDigest; 10925 this.user = user; 10926 this.instructionSets = instructionSets; 10927 this.abiOverride = abiOverride; 10928 this.installGrantPermissions = installGrantPermissions; 10929 } 10930 10931 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10932 abstract int doPreInstall(int status); 10933 10934 /** 10935 * Rename package into final resting place. All paths on the given 10936 * scanned package should be updated to reflect the rename. 10937 */ 10938 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10939 abstract int doPostInstall(int status, int uid); 10940 10941 /** @see PackageSettingBase#codePathString */ 10942 abstract String getCodePath(); 10943 /** @see PackageSettingBase#resourcePathString */ 10944 abstract String getResourcePath(); 10945 10946 // Need installer lock especially for dex file removal. 10947 abstract void cleanUpResourcesLI(); 10948 abstract boolean doPostDeleteLI(boolean delete); 10949 10950 /** 10951 * Called before the source arguments are copied. This is used mostly 10952 * for MoveParams when it needs to read the source file to put it in the 10953 * destination. 10954 */ 10955 int doPreCopy() { 10956 return PackageManager.INSTALL_SUCCEEDED; 10957 } 10958 10959 /** 10960 * Called after the source arguments are copied. This is used mostly for 10961 * MoveParams when it needs to read the source file to put it in the 10962 * destination. 10963 * 10964 * @return 10965 */ 10966 int doPostCopy(int uid) { 10967 return PackageManager.INSTALL_SUCCEEDED; 10968 } 10969 10970 protected boolean isFwdLocked() { 10971 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10972 } 10973 10974 protected boolean isExternalAsec() { 10975 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10976 } 10977 10978 UserHandle getUser() { 10979 return user; 10980 } 10981 } 10982 10983 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10984 if (!allCodePaths.isEmpty()) { 10985 if (instructionSets == null) { 10986 throw new IllegalStateException("instructionSet == null"); 10987 } 10988 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10989 for (String codePath : allCodePaths) { 10990 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10991 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10992 if (retCode < 0) { 10993 Slog.w(TAG, "Couldn't remove dex file for package: " 10994 + " at location " + codePath + ", retcode=" + retCode); 10995 // we don't consider this to be a failure of the core package deletion 10996 } 10997 } 10998 } 10999 } 11000 } 11001 11002 /** 11003 * Logic to handle installation of non-ASEC applications, including copying 11004 * and renaming logic. 11005 */ 11006 class FileInstallArgs extends InstallArgs { 11007 private File codeFile; 11008 private File resourceFile; 11009 11010 // Example topology: 11011 // /data/app/com.example/base.apk 11012 // /data/app/com.example/split_foo.apk 11013 // /data/app/com.example/lib/arm/libfoo.so 11014 // /data/app/com.example/lib/arm64/libfoo.so 11015 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11016 11017 /** New install */ 11018 FileInstallArgs(InstallParams params) { 11019 super(params.origin, params.move, params.observer, params.installFlags, 11020 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11021 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11022 params.grantedRuntimePermissions); 11023 if (isFwdLocked()) { 11024 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11025 } 11026 } 11027 11028 /** Existing install */ 11029 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11030 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11031 null, null); 11032 this.codeFile = (codePath != null) ? new File(codePath) : null; 11033 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11034 } 11035 11036 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11037 if (origin.staged) { 11038 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11039 codeFile = origin.file; 11040 resourceFile = origin.file; 11041 return PackageManager.INSTALL_SUCCEEDED; 11042 } 11043 11044 try { 11045 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11046 codeFile = tempDir; 11047 resourceFile = tempDir; 11048 } catch (IOException e) { 11049 Slog.w(TAG, "Failed to create copy file: " + e); 11050 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11051 } 11052 11053 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11054 @Override 11055 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11056 if (!FileUtils.isValidExtFilename(name)) { 11057 throw new IllegalArgumentException("Invalid filename: " + name); 11058 } 11059 try { 11060 final File file = new File(codeFile, name); 11061 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11062 O_RDWR | O_CREAT, 0644); 11063 Os.chmod(file.getAbsolutePath(), 0644); 11064 return new ParcelFileDescriptor(fd); 11065 } catch (ErrnoException e) { 11066 throw new RemoteException("Failed to open: " + e.getMessage()); 11067 } 11068 } 11069 }; 11070 11071 int ret = PackageManager.INSTALL_SUCCEEDED; 11072 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11073 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11074 Slog.e(TAG, "Failed to copy package"); 11075 return ret; 11076 } 11077 11078 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11079 NativeLibraryHelper.Handle handle = null; 11080 try { 11081 handle = NativeLibraryHelper.Handle.create(codeFile); 11082 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11083 abiOverride); 11084 } catch (IOException e) { 11085 Slog.e(TAG, "Copying native libraries failed", e); 11086 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11087 } finally { 11088 IoUtils.closeQuietly(handle); 11089 } 11090 11091 return ret; 11092 } 11093 11094 int doPreInstall(int status) { 11095 if (status != PackageManager.INSTALL_SUCCEEDED) { 11096 cleanUp(); 11097 } 11098 return status; 11099 } 11100 11101 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11102 if (status != PackageManager.INSTALL_SUCCEEDED) { 11103 cleanUp(); 11104 return false; 11105 } 11106 11107 final File targetDir = codeFile.getParentFile(); 11108 final File beforeCodeFile = codeFile; 11109 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11110 11111 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11112 try { 11113 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11114 } catch (ErrnoException e) { 11115 Slog.w(TAG, "Failed to rename", e); 11116 return false; 11117 } 11118 11119 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11120 Slog.w(TAG, "Failed to restorecon"); 11121 return false; 11122 } 11123 11124 // Reflect the rename internally 11125 codeFile = afterCodeFile; 11126 resourceFile = afterCodeFile; 11127 11128 // Reflect the rename in scanned details 11129 pkg.codePath = afterCodeFile.getAbsolutePath(); 11130 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11131 pkg.baseCodePath); 11132 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11133 pkg.splitCodePaths); 11134 11135 // Reflect the rename in app info 11136 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11137 pkg.applicationInfo.setCodePath(pkg.codePath); 11138 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11139 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11140 pkg.applicationInfo.setResourcePath(pkg.codePath); 11141 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11142 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11143 11144 return true; 11145 } 11146 11147 int doPostInstall(int status, int uid) { 11148 if (status != PackageManager.INSTALL_SUCCEEDED) { 11149 cleanUp(); 11150 } 11151 return status; 11152 } 11153 11154 @Override 11155 String getCodePath() { 11156 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11157 } 11158 11159 @Override 11160 String getResourcePath() { 11161 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11162 } 11163 11164 private boolean cleanUp() { 11165 if (codeFile == null || !codeFile.exists()) { 11166 return false; 11167 } 11168 11169 if (codeFile.isDirectory()) { 11170 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11171 } else { 11172 codeFile.delete(); 11173 } 11174 11175 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11176 resourceFile.delete(); 11177 } 11178 11179 return true; 11180 } 11181 11182 void cleanUpResourcesLI() { 11183 // Try enumerating all code paths before deleting 11184 List<String> allCodePaths = Collections.EMPTY_LIST; 11185 if (codeFile != null && codeFile.exists()) { 11186 try { 11187 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11188 allCodePaths = pkg.getAllCodePaths(); 11189 } catch (PackageParserException e) { 11190 // Ignored; we tried our best 11191 } 11192 } 11193 11194 cleanUp(); 11195 removeDexFiles(allCodePaths, instructionSets); 11196 } 11197 11198 boolean doPostDeleteLI(boolean delete) { 11199 // XXX err, shouldn't we respect the delete flag? 11200 cleanUpResourcesLI(); 11201 return true; 11202 } 11203 } 11204 11205 private boolean isAsecExternal(String cid) { 11206 final String asecPath = PackageHelper.getSdFilesystem(cid); 11207 return !asecPath.startsWith(mAsecInternalPath); 11208 } 11209 11210 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11211 PackageManagerException { 11212 if (copyRet < 0) { 11213 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11214 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11215 throw new PackageManagerException(copyRet, message); 11216 } 11217 } 11218 } 11219 11220 /** 11221 * Extract the MountService "container ID" from the full code path of an 11222 * .apk. 11223 */ 11224 static String cidFromCodePath(String fullCodePath) { 11225 int eidx = fullCodePath.lastIndexOf("/"); 11226 String subStr1 = fullCodePath.substring(0, eidx); 11227 int sidx = subStr1.lastIndexOf("/"); 11228 return subStr1.substring(sidx+1, eidx); 11229 } 11230 11231 /** 11232 * Logic to handle installation of ASEC applications, including copying and 11233 * renaming logic. 11234 */ 11235 class AsecInstallArgs extends InstallArgs { 11236 static final String RES_FILE_NAME = "pkg.apk"; 11237 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11238 11239 String cid; 11240 String packagePath; 11241 String resourcePath; 11242 11243 /** New install */ 11244 AsecInstallArgs(InstallParams params) { 11245 super(params.origin, params.move, params.observer, params.installFlags, 11246 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11247 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11248 params.grantedRuntimePermissions); 11249 } 11250 11251 /** Existing install */ 11252 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11253 boolean isExternal, boolean isForwardLocked) { 11254 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11255 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11256 instructionSets, null, null); 11257 // Hackily pretend we're still looking at a full code path 11258 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11259 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11260 } 11261 11262 // Extract cid from fullCodePath 11263 int eidx = fullCodePath.lastIndexOf("/"); 11264 String subStr1 = fullCodePath.substring(0, eidx); 11265 int sidx = subStr1.lastIndexOf("/"); 11266 cid = subStr1.substring(sidx+1, eidx); 11267 setMountPath(subStr1); 11268 } 11269 11270 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11271 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11272 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11273 instructionSets, null, null); 11274 this.cid = cid; 11275 setMountPath(PackageHelper.getSdDir(cid)); 11276 } 11277 11278 void createCopyFile() { 11279 cid = mInstallerService.allocateExternalStageCidLegacy(); 11280 } 11281 11282 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11283 if (origin.staged) { 11284 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11285 cid = origin.cid; 11286 setMountPath(PackageHelper.getSdDir(cid)); 11287 return PackageManager.INSTALL_SUCCEEDED; 11288 } 11289 11290 if (temp) { 11291 createCopyFile(); 11292 } else { 11293 /* 11294 * Pre-emptively destroy the container since it's destroyed if 11295 * copying fails due to it existing anyway. 11296 */ 11297 PackageHelper.destroySdDir(cid); 11298 } 11299 11300 final String newMountPath = imcs.copyPackageToContainer( 11301 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11302 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11303 11304 if (newMountPath != null) { 11305 setMountPath(newMountPath); 11306 return PackageManager.INSTALL_SUCCEEDED; 11307 } else { 11308 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11309 } 11310 } 11311 11312 @Override 11313 String getCodePath() { 11314 return packagePath; 11315 } 11316 11317 @Override 11318 String getResourcePath() { 11319 return resourcePath; 11320 } 11321 11322 int doPreInstall(int status) { 11323 if (status != PackageManager.INSTALL_SUCCEEDED) { 11324 // Destroy container 11325 PackageHelper.destroySdDir(cid); 11326 } else { 11327 boolean mounted = PackageHelper.isContainerMounted(cid); 11328 if (!mounted) { 11329 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11330 Process.SYSTEM_UID); 11331 if (newMountPath != null) { 11332 setMountPath(newMountPath); 11333 } else { 11334 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11335 } 11336 } 11337 } 11338 return status; 11339 } 11340 11341 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11342 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11343 String newMountPath = null; 11344 if (PackageHelper.isContainerMounted(cid)) { 11345 // Unmount the container 11346 if (!PackageHelper.unMountSdDir(cid)) { 11347 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11348 return false; 11349 } 11350 } 11351 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11352 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11353 " which might be stale. Will try to clean up."); 11354 // Clean up the stale container and proceed to recreate. 11355 if (!PackageHelper.destroySdDir(newCacheId)) { 11356 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11357 return false; 11358 } 11359 // Successfully cleaned up stale container. Try to rename again. 11360 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11361 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11362 + " inspite of cleaning it up."); 11363 return false; 11364 } 11365 } 11366 if (!PackageHelper.isContainerMounted(newCacheId)) { 11367 Slog.w(TAG, "Mounting container " + newCacheId); 11368 newMountPath = PackageHelper.mountSdDir(newCacheId, 11369 getEncryptKey(), Process.SYSTEM_UID); 11370 } else { 11371 newMountPath = PackageHelper.getSdDir(newCacheId); 11372 } 11373 if (newMountPath == null) { 11374 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11375 return false; 11376 } 11377 Log.i(TAG, "Succesfully renamed " + cid + 11378 " to " + newCacheId + 11379 " at new path: " + newMountPath); 11380 cid = newCacheId; 11381 11382 final File beforeCodeFile = new File(packagePath); 11383 setMountPath(newMountPath); 11384 final File afterCodeFile = new File(packagePath); 11385 11386 // Reflect the rename in scanned details 11387 pkg.codePath = afterCodeFile.getAbsolutePath(); 11388 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11389 pkg.baseCodePath); 11390 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11391 pkg.splitCodePaths); 11392 11393 // Reflect the rename in app info 11394 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11395 pkg.applicationInfo.setCodePath(pkg.codePath); 11396 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11397 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11398 pkg.applicationInfo.setResourcePath(pkg.codePath); 11399 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11400 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11401 11402 return true; 11403 } 11404 11405 private void setMountPath(String mountPath) { 11406 final File mountFile = new File(mountPath); 11407 11408 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11409 if (monolithicFile.exists()) { 11410 packagePath = monolithicFile.getAbsolutePath(); 11411 if (isFwdLocked()) { 11412 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11413 } else { 11414 resourcePath = packagePath; 11415 } 11416 } else { 11417 packagePath = mountFile.getAbsolutePath(); 11418 resourcePath = packagePath; 11419 } 11420 } 11421 11422 int doPostInstall(int status, int uid) { 11423 if (status != PackageManager.INSTALL_SUCCEEDED) { 11424 cleanUp(); 11425 } else { 11426 final int groupOwner; 11427 final String protectedFile; 11428 if (isFwdLocked()) { 11429 groupOwner = UserHandle.getSharedAppGid(uid); 11430 protectedFile = RES_FILE_NAME; 11431 } else { 11432 groupOwner = -1; 11433 protectedFile = null; 11434 } 11435 11436 if (uid < Process.FIRST_APPLICATION_UID 11437 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11438 Slog.e(TAG, "Failed to finalize " + cid); 11439 PackageHelper.destroySdDir(cid); 11440 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11441 } 11442 11443 boolean mounted = PackageHelper.isContainerMounted(cid); 11444 if (!mounted) { 11445 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11446 } 11447 } 11448 return status; 11449 } 11450 11451 private void cleanUp() { 11452 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11453 11454 // Destroy secure container 11455 PackageHelper.destroySdDir(cid); 11456 } 11457 11458 private List<String> getAllCodePaths() { 11459 final File codeFile = new File(getCodePath()); 11460 if (codeFile != null && codeFile.exists()) { 11461 try { 11462 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11463 return pkg.getAllCodePaths(); 11464 } catch (PackageParserException e) { 11465 // Ignored; we tried our best 11466 } 11467 } 11468 return Collections.EMPTY_LIST; 11469 } 11470 11471 void cleanUpResourcesLI() { 11472 // Enumerate all code paths before deleting 11473 cleanUpResourcesLI(getAllCodePaths()); 11474 } 11475 11476 private void cleanUpResourcesLI(List<String> allCodePaths) { 11477 cleanUp(); 11478 removeDexFiles(allCodePaths, instructionSets); 11479 } 11480 11481 String getPackageName() { 11482 return getAsecPackageName(cid); 11483 } 11484 11485 boolean doPostDeleteLI(boolean delete) { 11486 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11487 final List<String> allCodePaths = getAllCodePaths(); 11488 boolean mounted = PackageHelper.isContainerMounted(cid); 11489 if (mounted) { 11490 // Unmount first 11491 if (PackageHelper.unMountSdDir(cid)) { 11492 mounted = false; 11493 } 11494 } 11495 if (!mounted && delete) { 11496 cleanUpResourcesLI(allCodePaths); 11497 } 11498 return !mounted; 11499 } 11500 11501 @Override 11502 int doPreCopy() { 11503 if (isFwdLocked()) { 11504 if (!PackageHelper.fixSdPermissions(cid, 11505 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11506 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11507 } 11508 } 11509 11510 return PackageManager.INSTALL_SUCCEEDED; 11511 } 11512 11513 @Override 11514 int doPostCopy(int uid) { 11515 if (isFwdLocked()) { 11516 if (uid < Process.FIRST_APPLICATION_UID 11517 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11518 RES_FILE_NAME)) { 11519 Slog.e(TAG, "Failed to finalize " + cid); 11520 PackageHelper.destroySdDir(cid); 11521 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11522 } 11523 } 11524 11525 return PackageManager.INSTALL_SUCCEEDED; 11526 } 11527 } 11528 11529 /** 11530 * Logic to handle movement of existing installed applications. 11531 */ 11532 class MoveInstallArgs extends InstallArgs { 11533 private File codeFile; 11534 private File resourceFile; 11535 11536 /** New install */ 11537 MoveInstallArgs(InstallParams params) { 11538 super(params.origin, params.move, params.observer, params.installFlags, 11539 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11540 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11541 params.grantedRuntimePermissions); 11542 } 11543 11544 int copyApk(IMediaContainerService imcs, boolean temp) { 11545 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11546 + move.fromUuid + " to " + move.toUuid); 11547 synchronized (mInstaller) { 11548 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11549 move.dataAppName, move.appId, move.seinfo) != 0) { 11550 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11551 } 11552 } 11553 11554 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11555 resourceFile = codeFile; 11556 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11557 11558 return PackageManager.INSTALL_SUCCEEDED; 11559 } 11560 11561 int doPreInstall(int status) { 11562 if (status != PackageManager.INSTALL_SUCCEEDED) { 11563 cleanUp(move.toUuid); 11564 } 11565 return status; 11566 } 11567 11568 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11569 if (status != PackageManager.INSTALL_SUCCEEDED) { 11570 cleanUp(move.toUuid); 11571 return false; 11572 } 11573 11574 // Reflect the move in app info 11575 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11576 pkg.applicationInfo.setCodePath(pkg.codePath); 11577 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11578 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11579 pkg.applicationInfo.setResourcePath(pkg.codePath); 11580 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11581 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11582 11583 return true; 11584 } 11585 11586 int doPostInstall(int status, int uid) { 11587 if (status == PackageManager.INSTALL_SUCCEEDED) { 11588 cleanUp(move.fromUuid); 11589 } else { 11590 cleanUp(move.toUuid); 11591 } 11592 return status; 11593 } 11594 11595 @Override 11596 String getCodePath() { 11597 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11598 } 11599 11600 @Override 11601 String getResourcePath() { 11602 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11603 } 11604 11605 private boolean cleanUp(String volumeUuid) { 11606 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11607 move.dataAppName); 11608 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11609 synchronized (mInstallLock) { 11610 // Clean up both app data and code 11611 removeDataDirsLI(volumeUuid, move.packageName); 11612 if (codeFile.isDirectory()) { 11613 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11614 } else { 11615 codeFile.delete(); 11616 } 11617 } 11618 return true; 11619 } 11620 11621 void cleanUpResourcesLI() { 11622 throw new UnsupportedOperationException(); 11623 } 11624 11625 boolean doPostDeleteLI(boolean delete) { 11626 throw new UnsupportedOperationException(); 11627 } 11628 } 11629 11630 static String getAsecPackageName(String packageCid) { 11631 int idx = packageCid.lastIndexOf("-"); 11632 if (idx == -1) { 11633 return packageCid; 11634 } 11635 return packageCid.substring(0, idx); 11636 } 11637 11638 // Utility method used to create code paths based on package name and available index. 11639 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11640 String idxStr = ""; 11641 int idx = 1; 11642 // Fall back to default value of idx=1 if prefix is not 11643 // part of oldCodePath 11644 if (oldCodePath != null) { 11645 String subStr = oldCodePath; 11646 // Drop the suffix right away 11647 if (suffix != null && subStr.endsWith(suffix)) { 11648 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11649 } 11650 // If oldCodePath already contains prefix find out the 11651 // ending index to either increment or decrement. 11652 int sidx = subStr.lastIndexOf(prefix); 11653 if (sidx != -1) { 11654 subStr = subStr.substring(sidx + prefix.length()); 11655 if (subStr != null) { 11656 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11657 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11658 } 11659 try { 11660 idx = Integer.parseInt(subStr); 11661 if (idx <= 1) { 11662 idx++; 11663 } else { 11664 idx--; 11665 } 11666 } catch(NumberFormatException e) { 11667 } 11668 } 11669 } 11670 } 11671 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11672 return prefix + idxStr; 11673 } 11674 11675 private File getNextCodePath(File targetDir, String packageName) { 11676 int suffix = 1; 11677 File result; 11678 do { 11679 result = new File(targetDir, packageName + "-" + suffix); 11680 suffix++; 11681 } while (result.exists()); 11682 return result; 11683 } 11684 11685 // Utility method that returns the relative package path with respect 11686 // to the installation directory. Like say for /data/data/com.test-1.apk 11687 // string com.test-1 is returned. 11688 static String deriveCodePathName(String codePath) { 11689 if (codePath == null) { 11690 return null; 11691 } 11692 final File codeFile = new File(codePath); 11693 final String name = codeFile.getName(); 11694 if (codeFile.isDirectory()) { 11695 return name; 11696 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11697 final int lastDot = name.lastIndexOf('.'); 11698 return name.substring(0, lastDot); 11699 } else { 11700 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11701 return null; 11702 } 11703 } 11704 11705 class PackageInstalledInfo { 11706 String name; 11707 int uid; 11708 // The set of users that originally had this package installed. 11709 int[] origUsers; 11710 // The set of users that now have this package installed. 11711 int[] newUsers; 11712 PackageParser.Package pkg; 11713 int returnCode; 11714 String returnMsg; 11715 PackageRemovedInfo removedInfo; 11716 11717 public void setError(int code, String msg) { 11718 returnCode = code; 11719 returnMsg = msg; 11720 Slog.w(TAG, msg); 11721 } 11722 11723 public void setError(String msg, PackageParserException e) { 11724 returnCode = e.error; 11725 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11726 Slog.w(TAG, msg, e); 11727 } 11728 11729 public void setError(String msg, PackageManagerException e) { 11730 returnCode = e.error; 11731 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11732 Slog.w(TAG, msg, e); 11733 } 11734 11735 // In some error cases we want to convey more info back to the observer 11736 String origPackage; 11737 String origPermission; 11738 } 11739 11740 /* 11741 * Install a non-existing package. 11742 */ 11743 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11744 UserHandle user, String installerPackageName, String volumeUuid, 11745 PackageInstalledInfo res) { 11746 // Remember this for later, in case we need to rollback this install 11747 String pkgName = pkg.packageName; 11748 11749 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11750 final boolean dataDirExists = Environment 11751 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11752 synchronized(mPackages) { 11753 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11754 // A package with the same name is already installed, though 11755 // it has been renamed to an older name. The package we 11756 // are trying to install should be installed as an update to 11757 // the existing one, but that has not been requested, so bail. 11758 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11759 + " without first uninstalling package running as " 11760 + mSettings.mRenamedPackages.get(pkgName)); 11761 return; 11762 } 11763 if (mPackages.containsKey(pkgName)) { 11764 // Don't allow installation over an existing package with the same name. 11765 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11766 + " without first uninstalling."); 11767 return; 11768 } 11769 } 11770 11771 try { 11772 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11773 System.currentTimeMillis(), user); 11774 11775 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11776 // delete the partially installed application. the data directory will have to be 11777 // restored if it was already existing 11778 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11779 // remove package from internal structures. Note that we want deletePackageX to 11780 // delete the package data and cache directories that it created in 11781 // scanPackageLocked, unless those directories existed before we even tried to 11782 // install. 11783 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11784 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11785 res.removedInfo, true); 11786 } 11787 11788 } catch (PackageManagerException e) { 11789 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11790 } 11791 } 11792 11793 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11794 // Can't rotate keys during boot or if sharedUser. 11795 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11796 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11797 return false; 11798 } 11799 // app is using upgradeKeySets; make sure all are valid 11800 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11801 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11802 for (int i = 0; i < upgradeKeySets.length; i++) { 11803 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11804 Slog.wtf(TAG, "Package " 11805 + (oldPs.name != null ? oldPs.name : "<null>") 11806 + " contains upgrade-key-set reference to unknown key-set: " 11807 + upgradeKeySets[i] 11808 + " reverting to signatures check."); 11809 return false; 11810 } 11811 } 11812 return true; 11813 } 11814 11815 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11816 // Upgrade keysets are being used. Determine if new package has a superset of the 11817 // required keys. 11818 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11819 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11820 for (int i = 0; i < upgradeKeySets.length; i++) { 11821 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11822 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11823 return true; 11824 } 11825 } 11826 return false; 11827 } 11828 11829 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11830 UserHandle user, String installerPackageName, String volumeUuid, 11831 PackageInstalledInfo res) { 11832 final PackageParser.Package oldPackage; 11833 final String pkgName = pkg.packageName; 11834 final int[] allUsers; 11835 final boolean[] perUserInstalled; 11836 11837 // First find the old package info and check signatures 11838 synchronized(mPackages) { 11839 oldPackage = mPackages.get(pkgName); 11840 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11841 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11842 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11843 if(!checkUpgradeKeySetLP(ps, pkg)) { 11844 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11845 "New package not signed by keys specified by upgrade-keysets: " 11846 + pkgName); 11847 return; 11848 } 11849 } else { 11850 // default to original signature matching 11851 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11852 != PackageManager.SIGNATURE_MATCH) { 11853 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11854 "New package has a different signature: " + pkgName); 11855 return; 11856 } 11857 } 11858 11859 // In case of rollback, remember per-user/profile install state 11860 allUsers = sUserManager.getUserIds(); 11861 perUserInstalled = new boolean[allUsers.length]; 11862 for (int i = 0; i < allUsers.length; i++) { 11863 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11864 } 11865 } 11866 11867 boolean sysPkg = (isSystemApp(oldPackage)); 11868 if (sysPkg) { 11869 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11870 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11871 } else { 11872 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11873 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11874 } 11875 } 11876 11877 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11878 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11879 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11880 String volumeUuid, PackageInstalledInfo res) { 11881 String pkgName = deletedPackage.packageName; 11882 boolean deletedPkg = true; 11883 boolean updatedSettings = false; 11884 11885 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11886 + deletedPackage); 11887 long origUpdateTime; 11888 if (pkg.mExtras != null) { 11889 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11890 } else { 11891 origUpdateTime = 0; 11892 } 11893 11894 // First delete the existing package while retaining the data directory 11895 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11896 res.removedInfo, true)) { 11897 // If the existing package wasn't successfully deleted 11898 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11899 deletedPkg = false; 11900 } else { 11901 // Successfully deleted the old package; proceed with replace. 11902 11903 // If deleted package lived in a container, give users a chance to 11904 // relinquish resources before killing. 11905 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11906 if (DEBUG_INSTALL) { 11907 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11908 } 11909 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11910 final ArrayList<String> pkgList = new ArrayList<String>(1); 11911 pkgList.add(deletedPackage.applicationInfo.packageName); 11912 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11913 } 11914 11915 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11916 try { 11917 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11918 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11919 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11920 perUserInstalled, res, user); 11921 updatedSettings = true; 11922 } catch (PackageManagerException e) { 11923 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11924 } 11925 } 11926 11927 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11928 // remove package from internal structures. Note that we want deletePackageX to 11929 // delete the package data and cache directories that it created in 11930 // scanPackageLocked, unless those directories existed before we even tried to 11931 // install. 11932 if(updatedSettings) { 11933 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11934 deletePackageLI( 11935 pkgName, null, true, allUsers, perUserInstalled, 11936 PackageManager.DELETE_KEEP_DATA, 11937 res.removedInfo, true); 11938 } 11939 // Since we failed to install the new package we need to restore the old 11940 // package that we deleted. 11941 if (deletedPkg) { 11942 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11943 File restoreFile = new File(deletedPackage.codePath); 11944 // Parse old package 11945 boolean oldExternal = isExternal(deletedPackage); 11946 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11947 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11948 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11949 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11950 try { 11951 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11952 } catch (PackageManagerException e) { 11953 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11954 + e.getMessage()); 11955 return; 11956 } 11957 // Restore of old package succeeded. Update permissions. 11958 // writer 11959 synchronized (mPackages) { 11960 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11961 UPDATE_PERMISSIONS_ALL); 11962 // can downgrade to reader 11963 mSettings.writeLPr(); 11964 } 11965 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11966 } 11967 } 11968 } 11969 11970 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11971 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11972 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11973 String volumeUuid, PackageInstalledInfo res) { 11974 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11975 + ", old=" + deletedPackage); 11976 boolean disabledSystem = false; 11977 boolean updatedSettings = false; 11978 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11979 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11980 != 0) { 11981 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11982 } 11983 String packageName = deletedPackage.packageName; 11984 if (packageName == null) { 11985 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11986 "Attempt to delete null packageName."); 11987 return; 11988 } 11989 PackageParser.Package oldPkg; 11990 PackageSetting oldPkgSetting; 11991 // reader 11992 synchronized (mPackages) { 11993 oldPkg = mPackages.get(packageName); 11994 oldPkgSetting = mSettings.mPackages.get(packageName); 11995 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11996 (oldPkgSetting == null)) { 11997 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11998 "Couldn't find package:" + packageName + " information"); 11999 return; 12000 } 12001 } 12002 12003 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12004 12005 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12006 res.removedInfo.removedPackage = packageName; 12007 // Remove existing system package 12008 removePackageLI(oldPkgSetting, true); 12009 // writer 12010 synchronized (mPackages) { 12011 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12012 if (!disabledSystem && deletedPackage != null) { 12013 // We didn't need to disable the .apk as a current system package, 12014 // which means we are replacing another update that is already 12015 // installed. We need to make sure to delete the older one's .apk. 12016 res.removedInfo.args = createInstallArgsForExisting(0, 12017 deletedPackage.applicationInfo.getCodePath(), 12018 deletedPackage.applicationInfo.getResourcePath(), 12019 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12020 } else { 12021 res.removedInfo.args = null; 12022 } 12023 } 12024 12025 // Successfully disabled the old package. Now proceed with re-installation 12026 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12027 12028 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12029 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12030 12031 PackageParser.Package newPackage = null; 12032 try { 12033 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 12034 if (newPackage.mExtras != null) { 12035 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12036 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12037 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12038 12039 // is the update attempting to change shared user? that isn't going to work... 12040 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12041 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12042 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12043 + " to " + newPkgSetting.sharedUser); 12044 updatedSettings = true; 12045 } 12046 } 12047 12048 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12049 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12050 perUserInstalled, res, user); 12051 updatedSettings = true; 12052 } 12053 12054 } catch (PackageManagerException e) { 12055 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12056 } 12057 12058 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12059 // Re installation failed. Restore old information 12060 // Remove new pkg information 12061 if (newPackage != null) { 12062 removeInstalledPackageLI(newPackage, true); 12063 } 12064 // Add back the old system package 12065 try { 12066 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12067 } catch (PackageManagerException e) { 12068 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12069 } 12070 // Restore the old system information in Settings 12071 synchronized (mPackages) { 12072 if (disabledSystem) { 12073 mSettings.enableSystemPackageLPw(packageName); 12074 } 12075 if (updatedSettings) { 12076 mSettings.setInstallerPackageName(packageName, 12077 oldPkgSetting.installerPackageName); 12078 } 12079 mSettings.writeLPr(); 12080 } 12081 } 12082 } 12083 12084 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12085 // Collect all used permissions in the UID 12086 ArraySet<String> usedPermissions = new ArraySet<>(); 12087 final int packageCount = su.packages.size(); 12088 for (int i = 0; i < packageCount; i++) { 12089 PackageSetting ps = su.packages.valueAt(i); 12090 if (ps.pkg == null) { 12091 continue; 12092 } 12093 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12094 for (int j = 0; j < requestedPermCount; j++) { 12095 String permission = ps.pkg.requestedPermissions.get(j); 12096 BasePermission bp = mSettings.mPermissions.get(permission); 12097 if (bp != null) { 12098 usedPermissions.add(permission); 12099 } 12100 } 12101 } 12102 12103 PermissionsState permissionsState = su.getPermissionsState(); 12104 // Prune install permissions 12105 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12106 final int installPermCount = installPermStates.size(); 12107 for (int i = installPermCount - 1; i >= 0; i--) { 12108 PermissionState permissionState = installPermStates.get(i); 12109 if (!usedPermissions.contains(permissionState.getName())) { 12110 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12111 if (bp != null) { 12112 permissionsState.revokeInstallPermission(bp); 12113 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12114 PackageManager.MASK_PERMISSION_FLAGS, 0); 12115 } 12116 } 12117 } 12118 12119 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12120 12121 // Prune runtime permissions 12122 for (int userId : allUserIds) { 12123 List<PermissionState> runtimePermStates = permissionsState 12124 .getRuntimePermissionStates(userId); 12125 final int runtimePermCount = runtimePermStates.size(); 12126 for (int i = runtimePermCount - 1; i >= 0; i--) { 12127 PermissionState permissionState = runtimePermStates.get(i); 12128 if (!usedPermissions.contains(permissionState.getName())) { 12129 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12130 if (bp != null) { 12131 permissionsState.revokeRuntimePermission(bp, userId); 12132 permissionsState.updatePermissionFlags(bp, userId, 12133 PackageManager.MASK_PERMISSION_FLAGS, 0); 12134 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12135 runtimePermissionChangedUserIds, userId); 12136 } 12137 } 12138 } 12139 } 12140 12141 return runtimePermissionChangedUserIds; 12142 } 12143 12144 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12145 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12146 UserHandle user) { 12147 String pkgName = newPackage.packageName; 12148 synchronized (mPackages) { 12149 //write settings. the installStatus will be incomplete at this stage. 12150 //note that the new package setting would have already been 12151 //added to mPackages. It hasn't been persisted yet. 12152 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12153 mSettings.writeLPr(); 12154 } 12155 12156 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12157 12158 synchronized (mPackages) { 12159 updatePermissionsLPw(newPackage.packageName, newPackage, 12160 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12161 ? UPDATE_PERMISSIONS_ALL : 0)); 12162 // For system-bundled packages, we assume that installing an upgraded version 12163 // of the package implies that the user actually wants to run that new code, 12164 // so we enable the package. 12165 PackageSetting ps = mSettings.mPackages.get(pkgName); 12166 if (ps != null) { 12167 if (isSystemApp(newPackage)) { 12168 // NB: implicit assumption that system package upgrades apply to all users 12169 if (DEBUG_INSTALL) { 12170 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12171 } 12172 if (res.origUsers != null) { 12173 for (int userHandle : res.origUsers) { 12174 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12175 userHandle, installerPackageName); 12176 } 12177 } 12178 // Also convey the prior install/uninstall state 12179 if (allUsers != null && perUserInstalled != null) { 12180 for (int i = 0; i < allUsers.length; i++) { 12181 if (DEBUG_INSTALL) { 12182 Slog.d(TAG, " user " + allUsers[i] 12183 + " => " + perUserInstalled[i]); 12184 } 12185 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12186 } 12187 // these install state changes will be persisted in the 12188 // upcoming call to mSettings.writeLPr(). 12189 } 12190 } 12191 // It's implied that when a user requests installation, they want the app to be 12192 // installed and enabled. 12193 int userId = user.getIdentifier(); 12194 if (userId != UserHandle.USER_ALL) { 12195 ps.setInstalled(true, userId); 12196 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12197 } 12198 } 12199 res.name = pkgName; 12200 res.uid = newPackage.applicationInfo.uid; 12201 res.pkg = newPackage; 12202 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12203 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12204 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12205 //to update install status 12206 mSettings.writeLPr(); 12207 } 12208 } 12209 12210 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12211 final int installFlags = args.installFlags; 12212 final String installerPackageName = args.installerPackageName; 12213 final String volumeUuid = args.volumeUuid; 12214 final File tmpPackageFile = new File(args.getCodePath()); 12215 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12216 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12217 || (args.volumeUuid != null)); 12218 boolean replace = false; 12219 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12220 if (args.move != null) { 12221 // moving a complete application; perfom an initial scan on the new install location 12222 scanFlags |= SCAN_INITIAL; 12223 } 12224 // Result object to be returned 12225 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12226 12227 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12228 // Retrieve PackageSettings and parse package 12229 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12230 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12231 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12232 PackageParser pp = new PackageParser(); 12233 pp.setSeparateProcesses(mSeparateProcesses); 12234 pp.setDisplayMetrics(mMetrics); 12235 12236 final PackageParser.Package pkg; 12237 try { 12238 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12239 } catch (PackageParserException e) { 12240 res.setError("Failed parse during installPackageLI", e); 12241 return; 12242 } 12243 12244 // Mark that we have an install time CPU ABI override. 12245 pkg.cpuAbiOverride = args.abiOverride; 12246 12247 String pkgName = res.name = pkg.packageName; 12248 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12249 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12250 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12251 return; 12252 } 12253 } 12254 12255 try { 12256 pp.collectCertificates(pkg, parseFlags); 12257 pp.collectManifestDigest(pkg); 12258 } catch (PackageParserException e) { 12259 res.setError("Failed collect during installPackageLI", e); 12260 return; 12261 } 12262 12263 /* If the installer passed in a manifest digest, compare it now. */ 12264 if (args.manifestDigest != null) { 12265 if (DEBUG_INSTALL) { 12266 final String parsedManifest = pkg.manifestDigest == null ? "null" 12267 : pkg.manifestDigest.toString(); 12268 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12269 + parsedManifest); 12270 } 12271 12272 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12273 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12274 return; 12275 } 12276 } else if (DEBUG_INSTALL) { 12277 final String parsedManifest = pkg.manifestDigest == null 12278 ? "null" : pkg.manifestDigest.toString(); 12279 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12280 } 12281 12282 // Get rid of all references to package scan path via parser. 12283 pp = null; 12284 String oldCodePath = null; 12285 boolean systemApp = false; 12286 synchronized (mPackages) { 12287 // Check if installing already existing package 12288 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12289 String oldName = mSettings.mRenamedPackages.get(pkgName); 12290 if (pkg.mOriginalPackages != null 12291 && pkg.mOriginalPackages.contains(oldName) 12292 && mPackages.containsKey(oldName)) { 12293 // This package is derived from an original package, 12294 // and this device has been updating from that original 12295 // name. We must continue using the original name, so 12296 // rename the new package here. 12297 pkg.setPackageName(oldName); 12298 pkgName = pkg.packageName; 12299 replace = true; 12300 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12301 + oldName + " pkgName=" + pkgName); 12302 } else if (mPackages.containsKey(pkgName)) { 12303 // This package, under its official name, already exists 12304 // on the device; we should replace it. 12305 replace = true; 12306 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12307 } 12308 12309 // Prevent apps opting out from runtime permissions 12310 if (replace) { 12311 PackageParser.Package oldPackage = mPackages.get(pkgName); 12312 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12313 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12314 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12315 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12316 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12317 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12318 + " doesn't support runtime permissions but the old" 12319 + " target SDK " + oldTargetSdk + " does."); 12320 return; 12321 } 12322 } 12323 } 12324 12325 PackageSetting ps = mSettings.mPackages.get(pkgName); 12326 if (ps != null) { 12327 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12328 12329 // Quick sanity check that we're signed correctly if updating; 12330 // we'll check this again later when scanning, but we want to 12331 // bail early here before tripping over redefined permissions. 12332 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12333 if (!checkUpgradeKeySetLP(ps, pkg)) { 12334 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12335 + pkg.packageName + " upgrade keys do not match the " 12336 + "previously installed version"); 12337 return; 12338 } 12339 } else { 12340 try { 12341 verifySignaturesLP(ps, pkg); 12342 } catch (PackageManagerException e) { 12343 res.setError(e.error, e.getMessage()); 12344 return; 12345 } 12346 } 12347 12348 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12349 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12350 systemApp = (ps.pkg.applicationInfo.flags & 12351 ApplicationInfo.FLAG_SYSTEM) != 0; 12352 } 12353 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12354 } 12355 12356 // Check whether the newly-scanned package wants to define an already-defined perm 12357 int N = pkg.permissions.size(); 12358 for (int i = N-1; i >= 0; i--) { 12359 PackageParser.Permission perm = pkg.permissions.get(i); 12360 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12361 if (bp != null) { 12362 // If the defining package is signed with our cert, it's okay. This 12363 // also includes the "updating the same package" case, of course. 12364 // "updating same package" could also involve key-rotation. 12365 final boolean sigsOk; 12366 if (bp.sourcePackage.equals(pkg.packageName) 12367 && (bp.packageSetting instanceof PackageSetting) 12368 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12369 scanFlags))) { 12370 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12371 } else { 12372 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12373 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12374 } 12375 if (!sigsOk) { 12376 // If the owning package is the system itself, we log but allow 12377 // install to proceed; we fail the install on all other permission 12378 // redefinitions. 12379 if (!bp.sourcePackage.equals("android")) { 12380 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12381 + pkg.packageName + " attempting to redeclare permission " 12382 + perm.info.name + " already owned by " + bp.sourcePackage); 12383 res.origPermission = perm.info.name; 12384 res.origPackage = bp.sourcePackage; 12385 return; 12386 } else { 12387 Slog.w(TAG, "Package " + pkg.packageName 12388 + " attempting to redeclare system permission " 12389 + perm.info.name + "; ignoring new declaration"); 12390 pkg.permissions.remove(i); 12391 } 12392 } 12393 } 12394 } 12395 12396 } 12397 12398 if (systemApp && onExternal) { 12399 // Disable updates to system apps on sdcard 12400 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12401 "Cannot install updates to system apps on sdcard"); 12402 return; 12403 } 12404 12405 if (args.move != null) { 12406 // We did an in-place move, so dex is ready to roll 12407 scanFlags |= SCAN_NO_DEX; 12408 scanFlags |= SCAN_MOVE; 12409 12410 synchronized (mPackages) { 12411 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12412 if (ps == null) { 12413 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12414 "Missing settings for moved package " + pkgName); 12415 } 12416 12417 // We moved the entire application as-is, so bring over the 12418 // previously derived ABI information. 12419 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12420 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12421 } 12422 12423 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12424 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12425 scanFlags |= SCAN_NO_DEX; 12426 12427 try { 12428 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12429 true /* extract libs */); 12430 } catch (PackageManagerException pme) { 12431 Slog.e(TAG, "Error deriving application ABI", pme); 12432 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12433 return; 12434 } 12435 12436 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12437 int result = mPackageDexOptimizer 12438 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12439 false /* defer */, false /* inclDependencies */, 12440 true /* boot complete */); 12441 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12442 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12443 return; 12444 } 12445 } 12446 12447 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12448 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12449 return; 12450 } 12451 12452 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12453 12454 if (replace) { 12455 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12456 installerPackageName, volumeUuid, res); 12457 } else { 12458 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12459 args.user, installerPackageName, volumeUuid, res); 12460 } 12461 synchronized (mPackages) { 12462 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12463 if (ps != null) { 12464 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12465 } 12466 } 12467 } 12468 12469 private void startIntentFilterVerifications(int userId, boolean replacing, 12470 PackageParser.Package pkg) { 12471 if (mIntentFilterVerifierComponent == null) { 12472 Slog.w(TAG, "No IntentFilter verification will not be done as " 12473 + "there is no IntentFilterVerifier available!"); 12474 return; 12475 } 12476 12477 final int verifierUid = getPackageUid( 12478 mIntentFilterVerifierComponent.getPackageName(), 12479 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12480 12481 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12482 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12483 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12484 mHandler.sendMessage(msg); 12485 } 12486 12487 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12488 PackageParser.Package pkg) { 12489 int size = pkg.activities.size(); 12490 if (size == 0) { 12491 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12492 "No activity, so no need to verify any IntentFilter!"); 12493 return; 12494 } 12495 12496 final boolean hasDomainURLs = hasDomainURLs(pkg); 12497 if (!hasDomainURLs) { 12498 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12499 "No domain URLs, so no need to verify any IntentFilter!"); 12500 return; 12501 } 12502 12503 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12504 + " if any IntentFilter from the " + size 12505 + " Activities needs verification ..."); 12506 12507 int count = 0; 12508 final String packageName = pkg.packageName; 12509 12510 synchronized (mPackages) { 12511 // If this is a new install and we see that we've already run verification for this 12512 // package, we have nothing to do: it means the state was restored from backup. 12513 if (!replacing) { 12514 IntentFilterVerificationInfo ivi = 12515 mSettings.getIntentFilterVerificationLPr(packageName); 12516 if (ivi != null) { 12517 if (DEBUG_DOMAIN_VERIFICATION) { 12518 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12519 + ivi.getStatusString()); 12520 } 12521 return; 12522 } 12523 } 12524 12525 // If any filters need to be verified, then all need to be. 12526 boolean needToVerify = false; 12527 for (PackageParser.Activity a : pkg.activities) { 12528 for (ActivityIntentInfo filter : a.intents) { 12529 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12530 if (DEBUG_DOMAIN_VERIFICATION) { 12531 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12532 } 12533 needToVerify = true; 12534 break; 12535 } 12536 } 12537 } 12538 12539 if (needToVerify) { 12540 final int verificationId = mIntentFilterVerificationToken++; 12541 for (PackageParser.Activity a : pkg.activities) { 12542 for (ActivityIntentInfo filter : a.intents) { 12543 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12544 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12545 "Verification needed for IntentFilter:" + filter.toString()); 12546 mIntentFilterVerifier.addOneIntentFilterVerification( 12547 verifierUid, userId, verificationId, filter, packageName); 12548 count++; 12549 } 12550 } 12551 } 12552 } 12553 } 12554 12555 if (count > 0) { 12556 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12557 + " IntentFilter verification" + (count > 1 ? "s" : "") 12558 + " for userId:" + userId); 12559 mIntentFilterVerifier.startVerifications(userId); 12560 } else { 12561 if (DEBUG_DOMAIN_VERIFICATION) { 12562 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12563 } 12564 } 12565 } 12566 12567 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12568 final ComponentName cn = filter.activity.getComponentName(); 12569 final String packageName = cn.getPackageName(); 12570 12571 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12572 packageName); 12573 if (ivi == null) { 12574 return true; 12575 } 12576 int status = ivi.getStatus(); 12577 switch (status) { 12578 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12579 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12580 return true; 12581 12582 default: 12583 // Nothing to do 12584 return false; 12585 } 12586 } 12587 12588 private static boolean isMultiArch(PackageSetting ps) { 12589 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12590 } 12591 12592 private static boolean isMultiArch(ApplicationInfo info) { 12593 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12594 } 12595 12596 private static boolean isExternal(PackageParser.Package pkg) { 12597 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12598 } 12599 12600 private static boolean isExternal(PackageSetting ps) { 12601 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12602 } 12603 12604 private static boolean isExternal(ApplicationInfo info) { 12605 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12606 } 12607 12608 private static boolean isSystemApp(PackageParser.Package pkg) { 12609 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12610 } 12611 12612 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12613 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12614 } 12615 12616 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12617 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12618 } 12619 12620 private static boolean isSystemApp(PackageSetting ps) { 12621 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12622 } 12623 12624 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12625 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12626 } 12627 12628 private int packageFlagsToInstallFlags(PackageSetting ps) { 12629 int installFlags = 0; 12630 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12631 // This existing package was an external ASEC install when we have 12632 // the external flag without a UUID 12633 installFlags |= PackageManager.INSTALL_EXTERNAL; 12634 } 12635 if (ps.isForwardLocked()) { 12636 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12637 } 12638 return installFlags; 12639 } 12640 12641 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12642 if (isExternal(pkg)) { 12643 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12644 return StorageManager.UUID_PRIMARY_PHYSICAL; 12645 } else { 12646 return pkg.volumeUuid; 12647 } 12648 } else { 12649 return StorageManager.UUID_PRIVATE_INTERNAL; 12650 } 12651 } 12652 12653 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12654 if (isExternal(pkg)) { 12655 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12656 return mSettings.getExternalVersion(); 12657 } else { 12658 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12659 } 12660 } else { 12661 return mSettings.getInternalVersion(); 12662 } 12663 } 12664 12665 private void deleteTempPackageFiles() { 12666 final FilenameFilter filter = new FilenameFilter() { 12667 public boolean accept(File dir, String name) { 12668 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12669 } 12670 }; 12671 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12672 file.delete(); 12673 } 12674 } 12675 12676 @Override 12677 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12678 int flags) { 12679 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12680 flags); 12681 } 12682 12683 @Override 12684 public void deletePackage(final String packageName, 12685 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12686 mContext.enforceCallingOrSelfPermission( 12687 android.Manifest.permission.DELETE_PACKAGES, null); 12688 Preconditions.checkNotNull(packageName); 12689 Preconditions.checkNotNull(observer); 12690 final int uid = Binder.getCallingUid(); 12691 if (UserHandle.getUserId(uid) != userId) { 12692 mContext.enforceCallingPermission( 12693 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12694 "deletePackage for user " + userId); 12695 } 12696 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12697 try { 12698 observer.onPackageDeleted(packageName, 12699 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12700 } catch (RemoteException re) { 12701 } 12702 return; 12703 } 12704 12705 boolean uninstallBlocked = false; 12706 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12707 int[] users = sUserManager.getUserIds(); 12708 for (int i = 0; i < users.length; ++i) { 12709 if (getBlockUninstallForUser(packageName, users[i])) { 12710 uninstallBlocked = true; 12711 break; 12712 } 12713 } 12714 } else { 12715 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12716 } 12717 if (uninstallBlocked) { 12718 try { 12719 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12720 null); 12721 } catch (RemoteException re) { 12722 } 12723 return; 12724 } 12725 12726 if (DEBUG_REMOVE) { 12727 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12728 } 12729 // Queue up an async operation since the package deletion may take a little while. 12730 mHandler.post(new Runnable() { 12731 public void run() { 12732 mHandler.removeCallbacks(this); 12733 final int returnCode = deletePackageX(packageName, userId, flags); 12734 if (observer != null) { 12735 try { 12736 observer.onPackageDeleted(packageName, returnCode, null); 12737 } catch (RemoteException e) { 12738 Log.i(TAG, "Observer no longer exists."); 12739 } //end catch 12740 } //end if 12741 } //end run 12742 }); 12743 } 12744 12745 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12746 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12747 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12748 try { 12749 if (dpm != null) { 12750 if (dpm.isDeviceOwner(packageName)) { 12751 return true; 12752 } 12753 int[] users; 12754 if (userId == UserHandle.USER_ALL) { 12755 users = sUserManager.getUserIds(); 12756 } else { 12757 users = new int[]{userId}; 12758 } 12759 for (int i = 0; i < users.length; ++i) { 12760 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12761 return true; 12762 } 12763 } 12764 } 12765 } catch (RemoteException e) { 12766 } 12767 return false; 12768 } 12769 12770 /** 12771 * This method is an internal method that could be get invoked either 12772 * to delete an installed package or to clean up a failed installation. 12773 * After deleting an installed package, a broadcast is sent to notify any 12774 * listeners that the package has been installed. For cleaning up a failed 12775 * installation, the broadcast is not necessary since the package's 12776 * installation wouldn't have sent the initial broadcast either 12777 * The key steps in deleting a package are 12778 * deleting the package information in internal structures like mPackages, 12779 * deleting the packages base directories through installd 12780 * updating mSettings to reflect current status 12781 * persisting settings for later use 12782 * sending a broadcast if necessary 12783 */ 12784 private int deletePackageX(String packageName, int userId, int flags) { 12785 final PackageRemovedInfo info = new PackageRemovedInfo(); 12786 final boolean res; 12787 12788 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12789 ? UserHandle.ALL : new UserHandle(userId); 12790 12791 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12792 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12793 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12794 } 12795 12796 boolean removedForAllUsers = false; 12797 boolean systemUpdate = false; 12798 12799 // for the uninstall-updates case and restricted profiles, remember the per- 12800 // userhandle installed state 12801 int[] allUsers; 12802 boolean[] perUserInstalled; 12803 synchronized (mPackages) { 12804 PackageSetting ps = mSettings.mPackages.get(packageName); 12805 allUsers = sUserManager.getUserIds(); 12806 perUserInstalled = new boolean[allUsers.length]; 12807 for (int i = 0; i < allUsers.length; i++) { 12808 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12809 } 12810 } 12811 12812 synchronized (mInstallLock) { 12813 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12814 res = deletePackageLI(packageName, removeForUser, 12815 true, allUsers, perUserInstalled, 12816 flags | REMOVE_CHATTY, info, true); 12817 systemUpdate = info.isRemovedPackageSystemUpdate; 12818 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12819 removedForAllUsers = true; 12820 } 12821 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12822 + " removedForAllUsers=" + removedForAllUsers); 12823 } 12824 12825 if (res) { 12826 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12827 12828 // If the removed package was a system update, the old system package 12829 // was re-enabled; we need to broadcast this information 12830 if (systemUpdate) { 12831 Bundle extras = new Bundle(1); 12832 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12833 ? info.removedAppId : info.uid); 12834 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12835 12836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12837 extras, null, null, null); 12838 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12839 extras, null, null, null); 12840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12841 null, packageName, null, null); 12842 } 12843 } 12844 // Force a gc here. 12845 Runtime.getRuntime().gc(); 12846 // Delete the resources here after sending the broadcast to let 12847 // other processes clean up before deleting resources. 12848 if (info.args != null) { 12849 synchronized (mInstallLock) { 12850 info.args.doPostDeleteLI(true); 12851 } 12852 } 12853 12854 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12855 } 12856 12857 class PackageRemovedInfo { 12858 String removedPackage; 12859 int uid = -1; 12860 int removedAppId = -1; 12861 int[] removedUsers = null; 12862 boolean isRemovedPackageSystemUpdate = false; 12863 // Clean up resources deleted packages. 12864 InstallArgs args = null; 12865 12866 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12867 Bundle extras = new Bundle(1); 12868 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12869 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12870 if (replacing) { 12871 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12872 } 12873 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12874 if (removedPackage != null) { 12875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12876 extras, null, null, removedUsers); 12877 if (fullRemove && !replacing) { 12878 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12879 extras, null, null, removedUsers); 12880 } 12881 } 12882 if (removedAppId >= 0) { 12883 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12884 removedUsers); 12885 } 12886 } 12887 } 12888 12889 /* 12890 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12891 * flag is not set, the data directory is removed as well. 12892 * make sure this flag is set for partially installed apps. If not its meaningless to 12893 * delete a partially installed application. 12894 */ 12895 private void removePackageDataLI(PackageSetting ps, 12896 int[] allUserHandles, boolean[] perUserInstalled, 12897 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12898 String packageName = ps.name; 12899 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12900 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12901 // Retrieve object to delete permissions for shared user later on 12902 final PackageSetting deletedPs; 12903 // reader 12904 synchronized (mPackages) { 12905 deletedPs = mSettings.mPackages.get(packageName); 12906 if (outInfo != null) { 12907 outInfo.removedPackage = packageName; 12908 outInfo.removedUsers = deletedPs != null 12909 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12910 : null; 12911 } 12912 } 12913 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12914 removeDataDirsLI(ps.volumeUuid, packageName); 12915 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12916 } 12917 // writer 12918 synchronized (mPackages) { 12919 if (deletedPs != null) { 12920 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12921 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12922 clearDefaultBrowserIfNeeded(packageName); 12923 if (outInfo != null) { 12924 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12925 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12926 } 12927 updatePermissionsLPw(deletedPs.name, null, 0); 12928 if (deletedPs.sharedUser != null) { 12929 // Remove permissions associated with package. Since runtime 12930 // permissions are per user we have to kill the removed package 12931 // or packages running under the shared user of the removed 12932 // package if revoking the permissions requested only by the removed 12933 // package is successful and this causes a change in gids. 12934 for (int userId : UserManagerService.getInstance().getUserIds()) { 12935 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12936 userId); 12937 if (userIdToKill == UserHandle.USER_ALL 12938 || userIdToKill >= UserHandle.USER_OWNER) { 12939 // If gids changed for this user, kill all affected packages. 12940 mHandler.post(new Runnable() { 12941 @Override 12942 public void run() { 12943 // This has to happen with no lock held. 12944 killApplication(deletedPs.name, deletedPs.appId, 12945 KILL_APP_REASON_GIDS_CHANGED); 12946 } 12947 }); 12948 break; 12949 } 12950 } 12951 } 12952 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12953 } 12954 // make sure to preserve per-user disabled state if this removal was just 12955 // a downgrade of a system app to the factory package 12956 if (allUserHandles != null && perUserInstalled != null) { 12957 if (DEBUG_REMOVE) { 12958 Slog.d(TAG, "Propagating install state across downgrade"); 12959 } 12960 for (int i = 0; i < allUserHandles.length; i++) { 12961 if (DEBUG_REMOVE) { 12962 Slog.d(TAG, " user " + allUserHandles[i] 12963 + " => " + perUserInstalled[i]); 12964 } 12965 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12966 } 12967 } 12968 } 12969 // can downgrade to reader 12970 if (writeSettings) { 12971 // Save settings now 12972 mSettings.writeLPr(); 12973 } 12974 } 12975 if (outInfo != null) { 12976 // A user ID was deleted here. Go through all users and remove it 12977 // from KeyStore. 12978 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12979 } 12980 } 12981 12982 static boolean locationIsPrivileged(File path) { 12983 try { 12984 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12985 .getCanonicalPath(); 12986 return path.getCanonicalPath().startsWith(privilegedAppDir); 12987 } catch (IOException e) { 12988 Slog.e(TAG, "Unable to access code path " + path); 12989 } 12990 return false; 12991 } 12992 12993 /* 12994 * Tries to delete system package. 12995 */ 12996 private boolean deleteSystemPackageLI(PackageSetting newPs, 12997 int[] allUserHandles, boolean[] perUserInstalled, 12998 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12999 final boolean applyUserRestrictions 13000 = (allUserHandles != null) && (perUserInstalled != null); 13001 PackageSetting disabledPs = null; 13002 // Confirm if the system package has been updated 13003 // An updated system app can be deleted. This will also have to restore 13004 // the system pkg from system partition 13005 // reader 13006 synchronized (mPackages) { 13007 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13008 } 13009 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13010 + " disabledPs=" + disabledPs); 13011 if (disabledPs == null) { 13012 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13013 return false; 13014 } else if (DEBUG_REMOVE) { 13015 Slog.d(TAG, "Deleting system pkg from data partition"); 13016 } 13017 if (DEBUG_REMOVE) { 13018 if (applyUserRestrictions) { 13019 Slog.d(TAG, "Remembering install states:"); 13020 for (int i = 0; i < allUserHandles.length; i++) { 13021 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13022 } 13023 } 13024 } 13025 // Delete the updated package 13026 outInfo.isRemovedPackageSystemUpdate = true; 13027 if (disabledPs.versionCode < newPs.versionCode) { 13028 // Delete data for downgrades 13029 flags &= ~PackageManager.DELETE_KEEP_DATA; 13030 } else { 13031 // Preserve data by setting flag 13032 flags |= PackageManager.DELETE_KEEP_DATA; 13033 } 13034 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13035 allUserHandles, perUserInstalled, outInfo, writeSettings); 13036 if (!ret) { 13037 return false; 13038 } 13039 // writer 13040 synchronized (mPackages) { 13041 // Reinstate the old system package 13042 mSettings.enableSystemPackageLPw(newPs.name); 13043 // Remove any native libraries from the upgraded package. 13044 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13045 } 13046 // Install the system package 13047 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13048 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13049 if (locationIsPrivileged(disabledPs.codePath)) { 13050 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13051 } 13052 13053 final PackageParser.Package newPkg; 13054 try { 13055 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13056 } catch (PackageManagerException e) { 13057 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13058 return false; 13059 } 13060 13061 // writer 13062 synchronized (mPackages) { 13063 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13064 13065 // Propagate the permissions state as we do not want to drop on the floor 13066 // runtime permissions. The update permissions method below will take 13067 // care of removing obsolete permissions and grant install permissions. 13068 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13069 updatePermissionsLPw(newPkg.packageName, newPkg, 13070 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13071 13072 if (applyUserRestrictions) { 13073 if (DEBUG_REMOVE) { 13074 Slog.d(TAG, "Propagating install state across reinstall"); 13075 } 13076 for (int i = 0; i < allUserHandles.length; i++) { 13077 if (DEBUG_REMOVE) { 13078 Slog.d(TAG, " user " + allUserHandles[i] 13079 + " => " + perUserInstalled[i]); 13080 } 13081 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13082 13083 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13084 } 13085 // Regardless of writeSettings we need to ensure that this restriction 13086 // state propagation is persisted 13087 mSettings.writeAllUsersPackageRestrictionsLPr(); 13088 } 13089 // can downgrade to reader here 13090 if (writeSettings) { 13091 mSettings.writeLPr(); 13092 } 13093 } 13094 return true; 13095 } 13096 13097 private boolean deleteInstalledPackageLI(PackageSetting ps, 13098 boolean deleteCodeAndResources, int flags, 13099 int[] allUserHandles, boolean[] perUserInstalled, 13100 PackageRemovedInfo outInfo, boolean writeSettings) { 13101 if (outInfo != null) { 13102 outInfo.uid = ps.appId; 13103 } 13104 13105 // Delete package data from internal structures and also remove data if flag is set 13106 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13107 13108 // Delete application code and resources 13109 if (deleteCodeAndResources && (outInfo != null)) { 13110 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13111 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13112 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13113 } 13114 return true; 13115 } 13116 13117 @Override 13118 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13119 int userId) { 13120 mContext.enforceCallingOrSelfPermission( 13121 android.Manifest.permission.DELETE_PACKAGES, null); 13122 synchronized (mPackages) { 13123 PackageSetting ps = mSettings.mPackages.get(packageName); 13124 if (ps == null) { 13125 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13126 return false; 13127 } 13128 if (!ps.getInstalled(userId)) { 13129 // Can't block uninstall for an app that is not installed or enabled. 13130 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13131 return false; 13132 } 13133 ps.setBlockUninstall(blockUninstall, userId); 13134 mSettings.writePackageRestrictionsLPr(userId); 13135 } 13136 return true; 13137 } 13138 13139 @Override 13140 public boolean getBlockUninstallForUser(String packageName, int userId) { 13141 synchronized (mPackages) { 13142 PackageSetting ps = mSettings.mPackages.get(packageName); 13143 if (ps == null) { 13144 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13145 return false; 13146 } 13147 return ps.getBlockUninstall(userId); 13148 } 13149 } 13150 13151 /* 13152 * This method handles package deletion in general 13153 */ 13154 private boolean deletePackageLI(String packageName, UserHandle user, 13155 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13156 int flags, PackageRemovedInfo outInfo, 13157 boolean writeSettings) { 13158 if (packageName == null) { 13159 Slog.w(TAG, "Attempt to delete null packageName."); 13160 return false; 13161 } 13162 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13163 PackageSetting ps; 13164 boolean dataOnly = false; 13165 int removeUser = -1; 13166 int appId = -1; 13167 synchronized (mPackages) { 13168 ps = mSettings.mPackages.get(packageName); 13169 if (ps == null) { 13170 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13171 return false; 13172 } 13173 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13174 && user.getIdentifier() != UserHandle.USER_ALL) { 13175 // The caller is asking that the package only be deleted for a single 13176 // user. To do this, we just mark its uninstalled state and delete 13177 // its data. If this is a system app, we only allow this to happen if 13178 // they have set the special DELETE_SYSTEM_APP which requests different 13179 // semantics than normal for uninstalling system apps. 13180 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13181 final int userId = user.getIdentifier(); 13182 ps.setUserState(userId, 13183 COMPONENT_ENABLED_STATE_DEFAULT, 13184 false, //installed 13185 true, //stopped 13186 true, //notLaunched 13187 false, //hidden 13188 null, null, null, 13189 false, // blockUninstall 13190 ps.readUserState(userId).domainVerificationStatus, 0); 13191 if (!isSystemApp(ps)) { 13192 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13193 // Other user still have this package installed, so all 13194 // we need to do is clear this user's data and save that 13195 // it is uninstalled. 13196 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13197 removeUser = user.getIdentifier(); 13198 appId = ps.appId; 13199 scheduleWritePackageRestrictionsLocked(removeUser); 13200 } else { 13201 // We need to set it back to 'installed' so the uninstall 13202 // broadcasts will be sent correctly. 13203 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13204 ps.setInstalled(true, user.getIdentifier()); 13205 } 13206 } else { 13207 // This is a system app, so we assume that the 13208 // other users still have this package installed, so all 13209 // we need to do is clear this user's data and save that 13210 // it is uninstalled. 13211 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13212 removeUser = user.getIdentifier(); 13213 appId = ps.appId; 13214 scheduleWritePackageRestrictionsLocked(removeUser); 13215 } 13216 } 13217 } 13218 13219 if (removeUser >= 0) { 13220 // From above, we determined that we are deleting this only 13221 // for a single user. Continue the work here. 13222 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13223 if (outInfo != null) { 13224 outInfo.removedPackage = packageName; 13225 outInfo.removedAppId = appId; 13226 outInfo.removedUsers = new int[] {removeUser}; 13227 } 13228 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13229 removeKeystoreDataIfNeeded(removeUser, appId); 13230 schedulePackageCleaning(packageName, removeUser, false); 13231 synchronized (mPackages) { 13232 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13233 scheduleWritePackageRestrictionsLocked(removeUser); 13234 } 13235 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13236 } 13237 return true; 13238 } 13239 13240 if (dataOnly) { 13241 // Delete application data first 13242 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13243 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13244 return true; 13245 } 13246 13247 boolean ret = false; 13248 if (isSystemApp(ps)) { 13249 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13250 // When an updated system application is deleted we delete the existing resources as well and 13251 // fall back to existing code in system partition 13252 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13253 flags, outInfo, writeSettings); 13254 } else { 13255 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13256 // Kill application pre-emptively especially for apps on sd. 13257 killApplication(packageName, ps.appId, "uninstall pkg"); 13258 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13259 allUserHandles, perUserInstalled, 13260 outInfo, writeSettings); 13261 } 13262 13263 return ret; 13264 } 13265 13266 private final class ClearStorageConnection implements ServiceConnection { 13267 IMediaContainerService mContainerService; 13268 13269 @Override 13270 public void onServiceConnected(ComponentName name, IBinder service) { 13271 synchronized (this) { 13272 mContainerService = IMediaContainerService.Stub.asInterface(service); 13273 notifyAll(); 13274 } 13275 } 13276 13277 @Override 13278 public void onServiceDisconnected(ComponentName name) { 13279 } 13280 } 13281 13282 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13283 final boolean mounted; 13284 if (Environment.isExternalStorageEmulated()) { 13285 mounted = true; 13286 } else { 13287 final String status = Environment.getExternalStorageState(); 13288 13289 mounted = status.equals(Environment.MEDIA_MOUNTED) 13290 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13291 } 13292 13293 if (!mounted) { 13294 return; 13295 } 13296 13297 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13298 int[] users; 13299 if (userId == UserHandle.USER_ALL) { 13300 users = sUserManager.getUserIds(); 13301 } else { 13302 users = new int[] { userId }; 13303 } 13304 final ClearStorageConnection conn = new ClearStorageConnection(); 13305 if (mContext.bindServiceAsUser( 13306 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13307 try { 13308 for (int curUser : users) { 13309 long timeout = SystemClock.uptimeMillis() + 5000; 13310 synchronized (conn) { 13311 long now = SystemClock.uptimeMillis(); 13312 while (conn.mContainerService == null && now < timeout) { 13313 try { 13314 conn.wait(timeout - now); 13315 } catch (InterruptedException e) { 13316 } 13317 } 13318 } 13319 if (conn.mContainerService == null) { 13320 return; 13321 } 13322 13323 final UserEnvironment userEnv = new UserEnvironment(curUser); 13324 clearDirectory(conn.mContainerService, 13325 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13326 if (allData) { 13327 clearDirectory(conn.mContainerService, 13328 userEnv.buildExternalStorageAppDataDirs(packageName)); 13329 clearDirectory(conn.mContainerService, 13330 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13331 } 13332 } 13333 } finally { 13334 mContext.unbindService(conn); 13335 } 13336 } 13337 } 13338 13339 @Override 13340 public void clearApplicationUserData(final String packageName, 13341 final IPackageDataObserver observer, final int userId) { 13342 mContext.enforceCallingOrSelfPermission( 13343 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13344 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13345 // Queue up an async operation since the package deletion may take a little while. 13346 mHandler.post(new Runnable() { 13347 public void run() { 13348 mHandler.removeCallbacks(this); 13349 final boolean succeeded; 13350 synchronized (mInstallLock) { 13351 succeeded = clearApplicationUserDataLI(packageName, userId); 13352 } 13353 clearExternalStorageDataSync(packageName, userId, true); 13354 if (succeeded) { 13355 // invoke DeviceStorageMonitor's update method to clear any notifications 13356 DeviceStorageMonitorInternal 13357 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13358 if (dsm != null) { 13359 dsm.checkMemory(); 13360 } 13361 } 13362 if(observer != null) { 13363 try { 13364 observer.onRemoveCompleted(packageName, succeeded); 13365 } catch (RemoteException e) { 13366 Log.i(TAG, "Observer no longer exists."); 13367 } 13368 } //end if observer 13369 } //end run 13370 }); 13371 } 13372 13373 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13374 if (packageName == null) { 13375 Slog.w(TAG, "Attempt to delete null packageName."); 13376 return false; 13377 } 13378 13379 // Try finding details about the requested package 13380 PackageParser.Package pkg; 13381 synchronized (mPackages) { 13382 pkg = mPackages.get(packageName); 13383 if (pkg == null) { 13384 final PackageSetting ps = mSettings.mPackages.get(packageName); 13385 if (ps != null) { 13386 pkg = ps.pkg; 13387 } 13388 } 13389 13390 if (pkg == null) { 13391 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13392 return false; 13393 } 13394 13395 PackageSetting ps = (PackageSetting) pkg.mExtras; 13396 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13397 } 13398 13399 // Always delete data directories for package, even if we found no other 13400 // record of app. This helps users recover from UID mismatches without 13401 // resorting to a full data wipe. 13402 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13403 if (retCode < 0) { 13404 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13405 return false; 13406 } 13407 13408 final int appId = pkg.applicationInfo.uid; 13409 removeKeystoreDataIfNeeded(userId, appId); 13410 13411 // Create a native library symlink only if we have native libraries 13412 // and if the native libraries are 32 bit libraries. We do not provide 13413 // this symlink for 64 bit libraries. 13414 if (pkg.applicationInfo.primaryCpuAbi != null && 13415 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13416 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13417 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13418 nativeLibPath, userId) < 0) { 13419 Slog.w(TAG, "Failed linking native library dir"); 13420 return false; 13421 } 13422 } 13423 13424 return true; 13425 } 13426 13427 /** 13428 * Reverts user permission state changes (permissions and flags) in 13429 * all packages for a given user. 13430 * 13431 * @param userId The device user for which to do a reset. 13432 */ 13433 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13434 final int packageCount = mPackages.size(); 13435 for (int i = 0; i < packageCount; i++) { 13436 PackageParser.Package pkg = mPackages.valueAt(i); 13437 PackageSetting ps = (PackageSetting) pkg.mExtras; 13438 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13439 } 13440 } 13441 13442 /** 13443 * Reverts user permission state changes (permissions and flags). 13444 * 13445 * @param ps The package for which to reset. 13446 * @param userId The device user for which to do a reset. 13447 */ 13448 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13449 final PackageSetting ps, final int userId) { 13450 if (ps.pkg == null) { 13451 return; 13452 } 13453 13454 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13455 | FLAG_PERMISSION_USER_FIXED 13456 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13457 13458 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13459 | FLAG_PERMISSION_POLICY_FIXED; 13460 13461 boolean writeInstallPermissions = false; 13462 boolean writeRuntimePermissions = false; 13463 13464 final int permissionCount = ps.pkg.requestedPermissions.size(); 13465 for (int i = 0; i < permissionCount; i++) { 13466 String permission = ps.pkg.requestedPermissions.get(i); 13467 13468 BasePermission bp = mSettings.mPermissions.get(permission); 13469 if (bp == null) { 13470 continue; 13471 } 13472 13473 // If shared user we just reset the state to which only this app contributed. 13474 if (ps.sharedUser != null) { 13475 boolean used = false; 13476 final int packageCount = ps.sharedUser.packages.size(); 13477 for (int j = 0; j < packageCount; j++) { 13478 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13479 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13480 && pkg.pkg.requestedPermissions.contains(permission)) { 13481 used = true; 13482 break; 13483 } 13484 } 13485 if (used) { 13486 continue; 13487 } 13488 } 13489 13490 PermissionsState permissionsState = ps.getPermissionsState(); 13491 13492 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13493 13494 // Always clear the user settable flags. 13495 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13496 bp.name) != null; 13497 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13498 if (hasInstallState) { 13499 writeInstallPermissions = true; 13500 } else { 13501 writeRuntimePermissions = true; 13502 } 13503 } 13504 13505 // Below is only runtime permission handling. 13506 if (!bp.isRuntime()) { 13507 continue; 13508 } 13509 13510 // Never clobber system or policy. 13511 if ((oldFlags & policyOrSystemFlags) != 0) { 13512 continue; 13513 } 13514 13515 // If this permission was granted by default, make sure it is. 13516 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13517 if (permissionsState.grantRuntimePermission(bp, userId) 13518 != PERMISSION_OPERATION_FAILURE) { 13519 writeRuntimePermissions = true; 13520 } 13521 } else { 13522 // Otherwise, reset the permission. 13523 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13524 switch (revokeResult) { 13525 case PERMISSION_OPERATION_SUCCESS: { 13526 writeRuntimePermissions = true; 13527 } break; 13528 13529 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13530 writeRuntimePermissions = true; 13531 final int appId = ps.appId; 13532 mHandler.post(new Runnable() { 13533 @Override 13534 public void run() { 13535 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13536 } 13537 }); 13538 } break; 13539 } 13540 } 13541 } 13542 13543 // Synchronously write as we are taking permissions away. 13544 if (writeRuntimePermissions) { 13545 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13546 } 13547 13548 // Synchronously write as we are taking permissions away. 13549 if (writeInstallPermissions) { 13550 mSettings.writeLPr(); 13551 } 13552 } 13553 13554 /** 13555 * Remove entries from the keystore daemon. Will only remove it if the 13556 * {@code appId} is valid. 13557 */ 13558 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13559 if (appId < 0) { 13560 return; 13561 } 13562 13563 final KeyStore keyStore = KeyStore.getInstance(); 13564 if (keyStore != null) { 13565 if (userId == UserHandle.USER_ALL) { 13566 for (final int individual : sUserManager.getUserIds()) { 13567 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13568 } 13569 } else { 13570 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13571 } 13572 } else { 13573 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13574 } 13575 } 13576 13577 @Override 13578 public void deleteApplicationCacheFiles(final String packageName, 13579 final IPackageDataObserver observer) { 13580 mContext.enforceCallingOrSelfPermission( 13581 android.Manifest.permission.DELETE_CACHE_FILES, null); 13582 // Queue up an async operation since the package deletion may take a little while. 13583 final int userId = UserHandle.getCallingUserId(); 13584 mHandler.post(new Runnable() { 13585 public void run() { 13586 mHandler.removeCallbacks(this); 13587 final boolean succeded; 13588 synchronized (mInstallLock) { 13589 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13590 } 13591 clearExternalStorageDataSync(packageName, userId, false); 13592 if (observer != null) { 13593 try { 13594 observer.onRemoveCompleted(packageName, succeded); 13595 } catch (RemoteException e) { 13596 Log.i(TAG, "Observer no longer exists."); 13597 } 13598 } //end if observer 13599 } //end run 13600 }); 13601 } 13602 13603 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13604 if (packageName == null) { 13605 Slog.w(TAG, "Attempt to delete null packageName."); 13606 return false; 13607 } 13608 PackageParser.Package p; 13609 synchronized (mPackages) { 13610 p = mPackages.get(packageName); 13611 } 13612 if (p == null) { 13613 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13614 return false; 13615 } 13616 final ApplicationInfo applicationInfo = p.applicationInfo; 13617 if (applicationInfo == null) { 13618 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13619 return false; 13620 } 13621 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13622 if (retCode < 0) { 13623 Slog.w(TAG, "Couldn't remove cache files for package: " 13624 + packageName + " u" + userId); 13625 return false; 13626 } 13627 return true; 13628 } 13629 13630 @Override 13631 public void getPackageSizeInfo(final String packageName, int userHandle, 13632 final IPackageStatsObserver observer) { 13633 mContext.enforceCallingOrSelfPermission( 13634 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13635 if (packageName == null) { 13636 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13637 } 13638 13639 PackageStats stats = new PackageStats(packageName, userHandle); 13640 13641 /* 13642 * Queue up an async operation since the package measurement may take a 13643 * little while. 13644 */ 13645 Message msg = mHandler.obtainMessage(INIT_COPY); 13646 msg.obj = new MeasureParams(stats, observer); 13647 mHandler.sendMessage(msg); 13648 } 13649 13650 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13651 PackageStats pStats) { 13652 if (packageName == null) { 13653 Slog.w(TAG, "Attempt to get size of null packageName."); 13654 return false; 13655 } 13656 PackageParser.Package p; 13657 boolean dataOnly = false; 13658 String libDirRoot = null; 13659 String asecPath = null; 13660 PackageSetting ps = null; 13661 synchronized (mPackages) { 13662 p = mPackages.get(packageName); 13663 ps = mSettings.mPackages.get(packageName); 13664 if(p == null) { 13665 dataOnly = true; 13666 if((ps == null) || (ps.pkg == null)) { 13667 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13668 return false; 13669 } 13670 p = ps.pkg; 13671 } 13672 if (ps != null) { 13673 libDirRoot = ps.legacyNativeLibraryPathString; 13674 } 13675 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13676 final long token = Binder.clearCallingIdentity(); 13677 try { 13678 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13679 if (secureContainerId != null) { 13680 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13681 } 13682 } finally { 13683 Binder.restoreCallingIdentity(token); 13684 } 13685 } 13686 } 13687 String publicSrcDir = null; 13688 if(!dataOnly) { 13689 final ApplicationInfo applicationInfo = p.applicationInfo; 13690 if (applicationInfo == null) { 13691 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13692 return false; 13693 } 13694 if (p.isForwardLocked()) { 13695 publicSrcDir = applicationInfo.getBaseResourcePath(); 13696 } 13697 } 13698 // TODO: extend to measure size of split APKs 13699 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13700 // not just the first level. 13701 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13702 // just the primary. 13703 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13704 13705 String apkPath; 13706 File packageDir = new File(p.codePath); 13707 13708 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13709 apkPath = packageDir.getAbsolutePath(); 13710 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13711 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13712 libDirRoot = null; 13713 } 13714 } else { 13715 apkPath = p.baseCodePath; 13716 } 13717 13718 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13719 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13720 if (res < 0) { 13721 return false; 13722 } 13723 13724 // Fix-up for forward-locked applications in ASEC containers. 13725 if (!isExternal(p)) { 13726 pStats.codeSize += pStats.externalCodeSize; 13727 pStats.externalCodeSize = 0L; 13728 } 13729 13730 return true; 13731 } 13732 13733 13734 @Override 13735 public void addPackageToPreferred(String packageName) { 13736 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13737 } 13738 13739 @Override 13740 public void removePackageFromPreferred(String packageName) { 13741 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13742 } 13743 13744 @Override 13745 public List<PackageInfo> getPreferredPackages(int flags) { 13746 return new ArrayList<PackageInfo>(); 13747 } 13748 13749 private int getUidTargetSdkVersionLockedLPr(int uid) { 13750 Object obj = mSettings.getUserIdLPr(uid); 13751 if (obj instanceof SharedUserSetting) { 13752 final SharedUserSetting sus = (SharedUserSetting) obj; 13753 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13754 final Iterator<PackageSetting> it = sus.packages.iterator(); 13755 while (it.hasNext()) { 13756 final PackageSetting ps = it.next(); 13757 if (ps.pkg != null) { 13758 int v = ps.pkg.applicationInfo.targetSdkVersion; 13759 if (v < vers) vers = v; 13760 } 13761 } 13762 return vers; 13763 } else if (obj instanceof PackageSetting) { 13764 final PackageSetting ps = (PackageSetting) obj; 13765 if (ps.pkg != null) { 13766 return ps.pkg.applicationInfo.targetSdkVersion; 13767 } 13768 } 13769 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13770 } 13771 13772 @Override 13773 public void addPreferredActivity(IntentFilter filter, int match, 13774 ComponentName[] set, ComponentName activity, int userId) { 13775 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13776 "Adding preferred"); 13777 } 13778 13779 private void addPreferredActivityInternal(IntentFilter filter, int match, 13780 ComponentName[] set, ComponentName activity, boolean always, int userId, 13781 String opname) { 13782 // writer 13783 int callingUid = Binder.getCallingUid(); 13784 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13785 if (filter.countActions() == 0) { 13786 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13787 return; 13788 } 13789 synchronized (mPackages) { 13790 if (mContext.checkCallingOrSelfPermission( 13791 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13792 != PackageManager.PERMISSION_GRANTED) { 13793 if (getUidTargetSdkVersionLockedLPr(callingUid) 13794 < Build.VERSION_CODES.FROYO) { 13795 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13796 + callingUid); 13797 return; 13798 } 13799 mContext.enforceCallingOrSelfPermission( 13800 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13801 } 13802 13803 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13804 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13805 + userId + ":"); 13806 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13807 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13808 scheduleWritePackageRestrictionsLocked(userId); 13809 } 13810 } 13811 13812 @Override 13813 public void replacePreferredActivity(IntentFilter filter, int match, 13814 ComponentName[] set, ComponentName activity, int userId) { 13815 if (filter.countActions() != 1) { 13816 throw new IllegalArgumentException( 13817 "replacePreferredActivity expects filter to have only 1 action."); 13818 } 13819 if (filter.countDataAuthorities() != 0 13820 || filter.countDataPaths() != 0 13821 || filter.countDataSchemes() > 1 13822 || filter.countDataTypes() != 0) { 13823 throw new IllegalArgumentException( 13824 "replacePreferredActivity expects filter to have no data authorities, " + 13825 "paths, or types; and at most one scheme."); 13826 } 13827 13828 final int callingUid = Binder.getCallingUid(); 13829 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13830 synchronized (mPackages) { 13831 if (mContext.checkCallingOrSelfPermission( 13832 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13833 != PackageManager.PERMISSION_GRANTED) { 13834 if (getUidTargetSdkVersionLockedLPr(callingUid) 13835 < Build.VERSION_CODES.FROYO) { 13836 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13837 + Binder.getCallingUid()); 13838 return; 13839 } 13840 mContext.enforceCallingOrSelfPermission( 13841 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13842 } 13843 13844 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13845 if (pir != null) { 13846 // Get all of the existing entries that exactly match this filter. 13847 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13848 if (existing != null && existing.size() == 1) { 13849 PreferredActivity cur = existing.get(0); 13850 if (DEBUG_PREFERRED) { 13851 Slog.i(TAG, "Checking replace of preferred:"); 13852 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13853 if (!cur.mPref.mAlways) { 13854 Slog.i(TAG, " -- CUR; not mAlways!"); 13855 } else { 13856 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13857 Slog.i(TAG, " -- CUR: mSet=" 13858 + Arrays.toString(cur.mPref.mSetComponents)); 13859 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13860 Slog.i(TAG, " -- NEW: mMatch=" 13861 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13862 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13863 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13864 } 13865 } 13866 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13867 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13868 && cur.mPref.sameSet(set)) { 13869 // Setting the preferred activity to what it happens to be already 13870 if (DEBUG_PREFERRED) { 13871 Slog.i(TAG, "Replacing with same preferred activity " 13872 + cur.mPref.mShortComponent + " for user " 13873 + userId + ":"); 13874 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13875 } 13876 return; 13877 } 13878 } 13879 13880 if (existing != null) { 13881 if (DEBUG_PREFERRED) { 13882 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13883 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13884 } 13885 for (int i = 0; i < existing.size(); i++) { 13886 PreferredActivity pa = existing.get(i); 13887 if (DEBUG_PREFERRED) { 13888 Slog.i(TAG, "Removing existing preferred activity " 13889 + pa.mPref.mComponent + ":"); 13890 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13891 } 13892 pir.removeFilter(pa); 13893 } 13894 } 13895 } 13896 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13897 "Replacing preferred"); 13898 } 13899 } 13900 13901 @Override 13902 public void clearPackagePreferredActivities(String packageName) { 13903 final int uid = Binder.getCallingUid(); 13904 // writer 13905 synchronized (mPackages) { 13906 PackageParser.Package pkg = mPackages.get(packageName); 13907 if (pkg == null || pkg.applicationInfo.uid != uid) { 13908 if (mContext.checkCallingOrSelfPermission( 13909 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13910 != PackageManager.PERMISSION_GRANTED) { 13911 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13912 < Build.VERSION_CODES.FROYO) { 13913 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13914 + Binder.getCallingUid()); 13915 return; 13916 } 13917 mContext.enforceCallingOrSelfPermission( 13918 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13919 } 13920 } 13921 13922 int user = UserHandle.getCallingUserId(); 13923 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13924 scheduleWritePackageRestrictionsLocked(user); 13925 } 13926 } 13927 } 13928 13929 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13930 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13931 ArrayList<PreferredActivity> removed = null; 13932 boolean changed = false; 13933 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13934 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13935 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13936 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13937 continue; 13938 } 13939 Iterator<PreferredActivity> it = pir.filterIterator(); 13940 while (it.hasNext()) { 13941 PreferredActivity pa = it.next(); 13942 // Mark entry for removal only if it matches the package name 13943 // and the entry is of type "always". 13944 if (packageName == null || 13945 (pa.mPref.mComponent.getPackageName().equals(packageName) 13946 && pa.mPref.mAlways)) { 13947 if (removed == null) { 13948 removed = new ArrayList<PreferredActivity>(); 13949 } 13950 removed.add(pa); 13951 } 13952 } 13953 if (removed != null) { 13954 for (int j=0; j<removed.size(); j++) { 13955 PreferredActivity pa = removed.get(j); 13956 pir.removeFilter(pa); 13957 } 13958 changed = true; 13959 } 13960 } 13961 return changed; 13962 } 13963 13964 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13965 private void clearIntentFilterVerificationsLPw(int userId) { 13966 final int packageCount = mPackages.size(); 13967 for (int i = 0; i < packageCount; i++) { 13968 PackageParser.Package pkg = mPackages.valueAt(i); 13969 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13970 } 13971 } 13972 13973 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13974 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13975 if (userId == UserHandle.USER_ALL) { 13976 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13977 sUserManager.getUserIds())) { 13978 for (int oneUserId : sUserManager.getUserIds()) { 13979 scheduleWritePackageRestrictionsLocked(oneUserId); 13980 } 13981 } 13982 } else { 13983 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13984 scheduleWritePackageRestrictionsLocked(userId); 13985 } 13986 } 13987 } 13988 13989 void clearDefaultBrowserIfNeeded(String packageName) { 13990 for (int oneUserId : sUserManager.getUserIds()) { 13991 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13992 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13993 if (packageName.equals(defaultBrowserPackageName)) { 13994 setDefaultBrowserPackageName(null, oneUserId); 13995 } 13996 } 13997 } 13998 13999 @Override 14000 public void resetApplicationPreferences(int userId) { 14001 mContext.enforceCallingOrSelfPermission( 14002 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14003 // writer 14004 synchronized (mPackages) { 14005 final long identity = Binder.clearCallingIdentity(); 14006 try { 14007 clearPackagePreferredActivitiesLPw(null, userId); 14008 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14009 // TODO: We have to reset the default SMS and Phone. This requires 14010 // significant refactoring to keep all default apps in the package 14011 // manager (cleaner but more work) or have the services provide 14012 // callbacks to the package manager to request a default app reset. 14013 applyFactoryDefaultBrowserLPw(userId); 14014 clearIntentFilterVerificationsLPw(userId); 14015 primeDomainVerificationsLPw(userId); 14016 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14017 scheduleWritePackageRestrictionsLocked(userId); 14018 } finally { 14019 Binder.restoreCallingIdentity(identity); 14020 } 14021 } 14022 } 14023 14024 @Override 14025 public int getPreferredActivities(List<IntentFilter> outFilters, 14026 List<ComponentName> outActivities, String packageName) { 14027 14028 int num = 0; 14029 final int userId = UserHandle.getCallingUserId(); 14030 // reader 14031 synchronized (mPackages) { 14032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14033 if (pir != null) { 14034 final Iterator<PreferredActivity> it = pir.filterIterator(); 14035 while (it.hasNext()) { 14036 final PreferredActivity pa = it.next(); 14037 if (packageName == null 14038 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14039 && pa.mPref.mAlways)) { 14040 if (outFilters != null) { 14041 outFilters.add(new IntentFilter(pa)); 14042 } 14043 if (outActivities != null) { 14044 outActivities.add(pa.mPref.mComponent); 14045 } 14046 } 14047 } 14048 } 14049 } 14050 14051 return num; 14052 } 14053 14054 @Override 14055 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14056 int userId) { 14057 int callingUid = Binder.getCallingUid(); 14058 if (callingUid != Process.SYSTEM_UID) { 14059 throw new SecurityException( 14060 "addPersistentPreferredActivity can only be run by the system"); 14061 } 14062 if (filter.countActions() == 0) { 14063 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14064 return; 14065 } 14066 synchronized (mPackages) { 14067 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14068 " :"); 14069 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14070 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14071 new PersistentPreferredActivity(filter, activity)); 14072 scheduleWritePackageRestrictionsLocked(userId); 14073 } 14074 } 14075 14076 @Override 14077 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14078 int callingUid = Binder.getCallingUid(); 14079 if (callingUid != Process.SYSTEM_UID) { 14080 throw new SecurityException( 14081 "clearPackagePersistentPreferredActivities can only be run by the system"); 14082 } 14083 ArrayList<PersistentPreferredActivity> removed = null; 14084 boolean changed = false; 14085 synchronized (mPackages) { 14086 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14087 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14088 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14089 .valueAt(i); 14090 if (userId != thisUserId) { 14091 continue; 14092 } 14093 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14094 while (it.hasNext()) { 14095 PersistentPreferredActivity ppa = it.next(); 14096 // Mark entry for removal only if it matches the package name. 14097 if (ppa.mComponent.getPackageName().equals(packageName)) { 14098 if (removed == null) { 14099 removed = new ArrayList<PersistentPreferredActivity>(); 14100 } 14101 removed.add(ppa); 14102 } 14103 } 14104 if (removed != null) { 14105 for (int j=0; j<removed.size(); j++) { 14106 PersistentPreferredActivity ppa = removed.get(j); 14107 ppir.removeFilter(ppa); 14108 } 14109 changed = true; 14110 } 14111 } 14112 14113 if (changed) { 14114 scheduleWritePackageRestrictionsLocked(userId); 14115 } 14116 } 14117 } 14118 14119 /** 14120 * Common machinery for picking apart a restored XML blob and passing 14121 * it to a caller-supplied functor to be applied to the running system. 14122 */ 14123 private void restoreFromXml(XmlPullParser parser, int userId, 14124 String expectedStartTag, BlobXmlRestorer functor) 14125 throws IOException, XmlPullParserException { 14126 int type; 14127 while ((type = parser.next()) != XmlPullParser.START_TAG 14128 && type != XmlPullParser.END_DOCUMENT) { 14129 } 14130 if (type != XmlPullParser.START_TAG) { 14131 // oops didn't find a start tag?! 14132 if (DEBUG_BACKUP) { 14133 Slog.e(TAG, "Didn't find start tag during restore"); 14134 } 14135 return; 14136 } 14137 14138 // this is supposed to be TAG_PREFERRED_BACKUP 14139 if (!expectedStartTag.equals(parser.getName())) { 14140 if (DEBUG_BACKUP) { 14141 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14142 } 14143 return; 14144 } 14145 14146 // skip interfering stuff, then we're aligned with the backing implementation 14147 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14148 functor.apply(parser, userId); 14149 } 14150 14151 private interface BlobXmlRestorer { 14152 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14153 } 14154 14155 /** 14156 * Non-Binder method, support for the backup/restore mechanism: write the 14157 * full set of preferred activities in its canonical XML format. Returns the 14158 * XML output as a byte array, or null if there is none. 14159 */ 14160 @Override 14161 public byte[] getPreferredActivityBackup(int userId) { 14162 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14163 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14164 } 14165 14166 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14167 try { 14168 final XmlSerializer serializer = new FastXmlSerializer(); 14169 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14170 serializer.startDocument(null, true); 14171 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14172 14173 synchronized (mPackages) { 14174 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14175 } 14176 14177 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14178 serializer.endDocument(); 14179 serializer.flush(); 14180 } catch (Exception e) { 14181 if (DEBUG_BACKUP) { 14182 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14183 } 14184 return null; 14185 } 14186 14187 return dataStream.toByteArray(); 14188 } 14189 14190 @Override 14191 public void restorePreferredActivities(byte[] backup, int userId) { 14192 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14193 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14194 } 14195 14196 try { 14197 final XmlPullParser parser = Xml.newPullParser(); 14198 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14199 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14200 new BlobXmlRestorer() { 14201 @Override 14202 public void apply(XmlPullParser parser, int userId) 14203 throws XmlPullParserException, IOException { 14204 synchronized (mPackages) { 14205 mSettings.readPreferredActivitiesLPw(parser, userId); 14206 } 14207 } 14208 } ); 14209 } catch (Exception e) { 14210 if (DEBUG_BACKUP) { 14211 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14212 } 14213 } 14214 } 14215 14216 /** 14217 * Non-Binder method, support for the backup/restore mechanism: write the 14218 * default browser (etc) settings in its canonical XML format. Returns the default 14219 * browser XML representation as a byte array, or null if there is none. 14220 */ 14221 @Override 14222 public byte[] getDefaultAppsBackup(int userId) { 14223 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14224 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14225 } 14226 14227 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14228 try { 14229 final XmlSerializer serializer = new FastXmlSerializer(); 14230 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14231 serializer.startDocument(null, true); 14232 serializer.startTag(null, TAG_DEFAULT_APPS); 14233 14234 synchronized (mPackages) { 14235 mSettings.writeDefaultAppsLPr(serializer, userId); 14236 } 14237 14238 serializer.endTag(null, TAG_DEFAULT_APPS); 14239 serializer.endDocument(); 14240 serializer.flush(); 14241 } catch (Exception e) { 14242 if (DEBUG_BACKUP) { 14243 Slog.e(TAG, "Unable to write default apps for backup", e); 14244 } 14245 return null; 14246 } 14247 14248 return dataStream.toByteArray(); 14249 } 14250 14251 @Override 14252 public void restoreDefaultApps(byte[] backup, int userId) { 14253 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14254 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14255 } 14256 14257 try { 14258 final XmlPullParser parser = Xml.newPullParser(); 14259 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14260 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14261 new BlobXmlRestorer() { 14262 @Override 14263 public void apply(XmlPullParser parser, int userId) 14264 throws XmlPullParserException, IOException { 14265 synchronized (mPackages) { 14266 mSettings.readDefaultAppsLPw(parser, userId); 14267 } 14268 } 14269 } ); 14270 } catch (Exception e) { 14271 if (DEBUG_BACKUP) { 14272 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14273 } 14274 } 14275 } 14276 14277 @Override 14278 public byte[] getIntentFilterVerificationBackup(int userId) { 14279 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14280 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14281 } 14282 14283 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14284 try { 14285 final XmlSerializer serializer = new FastXmlSerializer(); 14286 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14287 serializer.startDocument(null, true); 14288 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14289 14290 synchronized (mPackages) { 14291 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14292 } 14293 14294 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14295 serializer.endDocument(); 14296 serializer.flush(); 14297 } catch (Exception e) { 14298 if (DEBUG_BACKUP) { 14299 Slog.e(TAG, "Unable to write default apps for backup", e); 14300 } 14301 return null; 14302 } 14303 14304 return dataStream.toByteArray(); 14305 } 14306 14307 @Override 14308 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14309 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14310 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14311 } 14312 14313 try { 14314 final XmlPullParser parser = Xml.newPullParser(); 14315 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14316 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14317 new BlobXmlRestorer() { 14318 @Override 14319 public void apply(XmlPullParser parser, int userId) 14320 throws XmlPullParserException, IOException { 14321 synchronized (mPackages) { 14322 mSettings.readAllDomainVerificationsLPr(parser, userId); 14323 mSettings.writeLPr(); 14324 } 14325 } 14326 } ); 14327 } catch (Exception e) { 14328 if (DEBUG_BACKUP) { 14329 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14330 } 14331 } 14332 } 14333 14334 @Override 14335 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14336 int sourceUserId, int targetUserId, int flags) { 14337 mContext.enforceCallingOrSelfPermission( 14338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14339 int callingUid = Binder.getCallingUid(); 14340 enforceOwnerRights(ownerPackage, callingUid); 14341 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14342 if (intentFilter.countActions() == 0) { 14343 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14344 return; 14345 } 14346 synchronized (mPackages) { 14347 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14348 ownerPackage, targetUserId, flags); 14349 CrossProfileIntentResolver resolver = 14350 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14351 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14352 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14353 if (existing != null) { 14354 int size = existing.size(); 14355 for (int i = 0; i < size; i++) { 14356 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14357 return; 14358 } 14359 } 14360 } 14361 resolver.addFilter(newFilter); 14362 scheduleWritePackageRestrictionsLocked(sourceUserId); 14363 } 14364 } 14365 14366 @Override 14367 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14368 mContext.enforceCallingOrSelfPermission( 14369 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14370 int callingUid = Binder.getCallingUid(); 14371 enforceOwnerRights(ownerPackage, callingUid); 14372 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14373 synchronized (mPackages) { 14374 CrossProfileIntentResolver resolver = 14375 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14376 ArraySet<CrossProfileIntentFilter> set = 14377 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14378 for (CrossProfileIntentFilter filter : set) { 14379 if (filter.getOwnerPackage().equals(ownerPackage)) { 14380 resolver.removeFilter(filter); 14381 } 14382 } 14383 scheduleWritePackageRestrictionsLocked(sourceUserId); 14384 } 14385 } 14386 14387 // Enforcing that callingUid is owning pkg on userId 14388 private void enforceOwnerRights(String pkg, int callingUid) { 14389 // The system owns everything. 14390 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14391 return; 14392 } 14393 int callingUserId = UserHandle.getUserId(callingUid); 14394 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14395 if (pi == null) { 14396 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14397 + callingUserId); 14398 } 14399 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14400 throw new SecurityException("Calling uid " + callingUid 14401 + " does not own package " + pkg); 14402 } 14403 } 14404 14405 @Override 14406 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14407 Intent intent = new Intent(Intent.ACTION_MAIN); 14408 intent.addCategory(Intent.CATEGORY_HOME); 14409 14410 final int callingUserId = UserHandle.getCallingUserId(); 14411 List<ResolveInfo> list = queryIntentActivities(intent, null, 14412 PackageManager.GET_META_DATA, callingUserId); 14413 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14414 true, false, false, callingUserId); 14415 14416 allHomeCandidates.clear(); 14417 if (list != null) { 14418 for (ResolveInfo ri : list) { 14419 allHomeCandidates.add(ri); 14420 } 14421 } 14422 return (preferred == null || preferred.activityInfo == null) 14423 ? null 14424 : new ComponentName(preferred.activityInfo.packageName, 14425 preferred.activityInfo.name); 14426 } 14427 14428 @Override 14429 public void setApplicationEnabledSetting(String appPackageName, 14430 int newState, int flags, int userId, String callingPackage) { 14431 if (!sUserManager.exists(userId)) return; 14432 if (callingPackage == null) { 14433 callingPackage = Integer.toString(Binder.getCallingUid()); 14434 } 14435 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14436 } 14437 14438 @Override 14439 public void setComponentEnabledSetting(ComponentName componentName, 14440 int newState, int flags, int userId) { 14441 if (!sUserManager.exists(userId)) return; 14442 setEnabledSetting(componentName.getPackageName(), 14443 componentName.getClassName(), newState, flags, userId, null); 14444 } 14445 14446 private void setEnabledSetting(final String packageName, String className, int newState, 14447 final int flags, int userId, String callingPackage) { 14448 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14449 || newState == COMPONENT_ENABLED_STATE_ENABLED 14450 || newState == COMPONENT_ENABLED_STATE_DISABLED 14451 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14452 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14453 throw new IllegalArgumentException("Invalid new component state: " 14454 + newState); 14455 } 14456 PackageSetting pkgSetting; 14457 final int uid = Binder.getCallingUid(); 14458 final int permission = mContext.checkCallingOrSelfPermission( 14459 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14460 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14461 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14462 boolean sendNow = false; 14463 boolean isApp = (className == null); 14464 String componentName = isApp ? packageName : className; 14465 int packageUid = -1; 14466 ArrayList<String> components; 14467 14468 // writer 14469 synchronized (mPackages) { 14470 pkgSetting = mSettings.mPackages.get(packageName); 14471 if (pkgSetting == null) { 14472 if (className == null) { 14473 throw new IllegalArgumentException( 14474 "Unknown package: " + packageName); 14475 } 14476 throw new IllegalArgumentException( 14477 "Unknown component: " + packageName 14478 + "/" + className); 14479 } 14480 // Allow root and verify that userId is not being specified by a different user 14481 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14482 throw new SecurityException( 14483 "Permission Denial: attempt to change component state from pid=" 14484 + Binder.getCallingPid() 14485 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14486 } 14487 if (className == null) { 14488 // We're dealing with an application/package level state change 14489 if (pkgSetting.getEnabled(userId) == newState) { 14490 // Nothing to do 14491 return; 14492 } 14493 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14494 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14495 // Don't care about who enables an app. 14496 callingPackage = null; 14497 } 14498 pkgSetting.setEnabled(newState, userId, callingPackage); 14499 // pkgSetting.pkg.mSetEnabled = newState; 14500 } else { 14501 // We're dealing with a component level state change 14502 // First, verify that this is a valid class name. 14503 PackageParser.Package pkg = pkgSetting.pkg; 14504 if (pkg == null || !pkg.hasComponentClassName(className)) { 14505 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14506 throw new IllegalArgumentException("Component class " + className 14507 + " does not exist in " + packageName); 14508 } else { 14509 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14510 + className + " does not exist in " + packageName); 14511 } 14512 } 14513 switch (newState) { 14514 case COMPONENT_ENABLED_STATE_ENABLED: 14515 if (!pkgSetting.enableComponentLPw(className, userId)) { 14516 return; 14517 } 14518 break; 14519 case COMPONENT_ENABLED_STATE_DISABLED: 14520 if (!pkgSetting.disableComponentLPw(className, userId)) { 14521 return; 14522 } 14523 break; 14524 case COMPONENT_ENABLED_STATE_DEFAULT: 14525 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14526 return; 14527 } 14528 break; 14529 default: 14530 Slog.e(TAG, "Invalid new component state: " + newState); 14531 return; 14532 } 14533 } 14534 scheduleWritePackageRestrictionsLocked(userId); 14535 components = mPendingBroadcasts.get(userId, packageName); 14536 final boolean newPackage = components == null; 14537 if (newPackage) { 14538 components = new ArrayList<String>(); 14539 } 14540 if (!components.contains(componentName)) { 14541 components.add(componentName); 14542 } 14543 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14544 sendNow = true; 14545 // Purge entry from pending broadcast list if another one exists already 14546 // since we are sending one right away. 14547 mPendingBroadcasts.remove(userId, packageName); 14548 } else { 14549 if (newPackage) { 14550 mPendingBroadcasts.put(userId, packageName, components); 14551 } 14552 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14553 // Schedule a message 14554 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14555 } 14556 } 14557 } 14558 14559 long callingId = Binder.clearCallingIdentity(); 14560 try { 14561 if (sendNow) { 14562 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14563 sendPackageChangedBroadcast(packageName, 14564 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14565 } 14566 } finally { 14567 Binder.restoreCallingIdentity(callingId); 14568 } 14569 } 14570 14571 private void sendPackageChangedBroadcast(String packageName, 14572 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14573 if (DEBUG_INSTALL) 14574 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14575 + componentNames); 14576 Bundle extras = new Bundle(4); 14577 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14578 String nameList[] = new String[componentNames.size()]; 14579 componentNames.toArray(nameList); 14580 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14581 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14582 extras.putInt(Intent.EXTRA_UID, packageUid); 14583 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14584 new int[] {UserHandle.getUserId(packageUid)}); 14585 } 14586 14587 @Override 14588 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14589 if (!sUserManager.exists(userId)) return; 14590 final int uid = Binder.getCallingUid(); 14591 final int permission = mContext.checkCallingOrSelfPermission( 14592 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14593 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14594 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14595 // writer 14596 synchronized (mPackages) { 14597 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14598 allowedByPermission, uid, userId)) { 14599 scheduleWritePackageRestrictionsLocked(userId); 14600 } 14601 } 14602 } 14603 14604 @Override 14605 public String getInstallerPackageName(String packageName) { 14606 // reader 14607 synchronized (mPackages) { 14608 return mSettings.getInstallerPackageNameLPr(packageName); 14609 } 14610 } 14611 14612 @Override 14613 public int getApplicationEnabledSetting(String packageName, int userId) { 14614 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14615 int uid = Binder.getCallingUid(); 14616 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14617 // reader 14618 synchronized (mPackages) { 14619 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14620 } 14621 } 14622 14623 @Override 14624 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14625 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14626 int uid = Binder.getCallingUid(); 14627 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14628 // reader 14629 synchronized (mPackages) { 14630 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14631 } 14632 } 14633 14634 @Override 14635 public void enterSafeMode() { 14636 enforceSystemOrRoot("Only the system can request entering safe mode"); 14637 14638 if (!mSystemReady) { 14639 mSafeMode = true; 14640 } 14641 } 14642 14643 @Override 14644 public void systemReady() { 14645 mSystemReady = true; 14646 14647 // Read the compatibilty setting when the system is ready. 14648 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14649 mContext.getContentResolver(), 14650 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14651 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14652 if (DEBUG_SETTINGS) { 14653 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14654 } 14655 14656 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14657 14658 synchronized (mPackages) { 14659 // Verify that all of the preferred activity components actually 14660 // exist. It is possible for applications to be updated and at 14661 // that point remove a previously declared activity component that 14662 // had been set as a preferred activity. We try to clean this up 14663 // the next time we encounter that preferred activity, but it is 14664 // possible for the user flow to never be able to return to that 14665 // situation so here we do a sanity check to make sure we haven't 14666 // left any junk around. 14667 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14668 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14669 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14670 removed.clear(); 14671 for (PreferredActivity pa : pir.filterSet()) { 14672 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14673 removed.add(pa); 14674 } 14675 } 14676 if (removed.size() > 0) { 14677 for (int r=0; r<removed.size(); r++) { 14678 PreferredActivity pa = removed.get(r); 14679 Slog.w(TAG, "Removing dangling preferred activity: " 14680 + pa.mPref.mComponent); 14681 pir.removeFilter(pa); 14682 } 14683 mSettings.writePackageRestrictionsLPr( 14684 mSettings.mPreferredActivities.keyAt(i)); 14685 } 14686 } 14687 14688 for (int userId : UserManagerService.getInstance().getUserIds()) { 14689 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14690 grantPermissionsUserIds = ArrayUtils.appendInt( 14691 grantPermissionsUserIds, userId); 14692 } 14693 } 14694 } 14695 sUserManager.systemReady(); 14696 14697 // If we upgraded grant all default permissions before kicking off. 14698 for (int userId : grantPermissionsUserIds) { 14699 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14700 } 14701 14702 // Kick off any messages waiting for system ready 14703 if (mPostSystemReadyMessages != null) { 14704 for (Message msg : mPostSystemReadyMessages) { 14705 msg.sendToTarget(); 14706 } 14707 mPostSystemReadyMessages = null; 14708 } 14709 14710 // Watch for external volumes that come and go over time 14711 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14712 storage.registerListener(mStorageListener); 14713 14714 mInstallerService.systemReady(); 14715 mPackageDexOptimizer.systemReady(); 14716 14717 MountServiceInternal mountServiceInternal = LocalServices.getService( 14718 MountServiceInternal.class); 14719 mountServiceInternal.addExternalStoragePolicy( 14720 new MountServiceInternal.ExternalStorageMountPolicy() { 14721 @Override 14722 public int getMountMode(int uid, String packageName) { 14723 if (Process.isIsolated(uid)) { 14724 return Zygote.MOUNT_EXTERNAL_NONE; 14725 } 14726 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14727 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14728 } 14729 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14730 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14731 } 14732 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14733 return Zygote.MOUNT_EXTERNAL_READ; 14734 } 14735 return Zygote.MOUNT_EXTERNAL_WRITE; 14736 } 14737 14738 @Override 14739 public boolean hasExternalStorage(int uid, String packageName) { 14740 return true; 14741 } 14742 }); 14743 } 14744 14745 @Override 14746 public boolean isSafeMode() { 14747 return mSafeMode; 14748 } 14749 14750 @Override 14751 public boolean hasSystemUidErrors() { 14752 return mHasSystemUidErrors; 14753 } 14754 14755 static String arrayToString(int[] array) { 14756 StringBuffer buf = new StringBuffer(128); 14757 buf.append('['); 14758 if (array != null) { 14759 for (int i=0; i<array.length; i++) { 14760 if (i > 0) buf.append(", "); 14761 buf.append(array[i]); 14762 } 14763 } 14764 buf.append(']'); 14765 return buf.toString(); 14766 } 14767 14768 static class DumpState { 14769 public static final int DUMP_LIBS = 1 << 0; 14770 public static final int DUMP_FEATURES = 1 << 1; 14771 public static final int DUMP_RESOLVERS = 1 << 2; 14772 public static final int DUMP_PERMISSIONS = 1 << 3; 14773 public static final int DUMP_PACKAGES = 1 << 4; 14774 public static final int DUMP_SHARED_USERS = 1 << 5; 14775 public static final int DUMP_MESSAGES = 1 << 6; 14776 public static final int DUMP_PROVIDERS = 1 << 7; 14777 public static final int DUMP_VERIFIERS = 1 << 8; 14778 public static final int DUMP_PREFERRED = 1 << 9; 14779 public static final int DUMP_PREFERRED_XML = 1 << 10; 14780 public static final int DUMP_KEYSETS = 1 << 11; 14781 public static final int DUMP_VERSION = 1 << 12; 14782 public static final int DUMP_INSTALLS = 1 << 13; 14783 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14784 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14785 14786 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14787 14788 private int mTypes; 14789 14790 private int mOptions; 14791 14792 private boolean mTitlePrinted; 14793 14794 private SharedUserSetting mSharedUser; 14795 14796 public boolean isDumping(int type) { 14797 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14798 return true; 14799 } 14800 14801 return (mTypes & type) != 0; 14802 } 14803 14804 public void setDump(int type) { 14805 mTypes |= type; 14806 } 14807 14808 public boolean isOptionEnabled(int option) { 14809 return (mOptions & option) != 0; 14810 } 14811 14812 public void setOptionEnabled(int option) { 14813 mOptions |= option; 14814 } 14815 14816 public boolean onTitlePrinted() { 14817 final boolean printed = mTitlePrinted; 14818 mTitlePrinted = true; 14819 return printed; 14820 } 14821 14822 public boolean getTitlePrinted() { 14823 return mTitlePrinted; 14824 } 14825 14826 public void setTitlePrinted(boolean enabled) { 14827 mTitlePrinted = enabled; 14828 } 14829 14830 public SharedUserSetting getSharedUser() { 14831 return mSharedUser; 14832 } 14833 14834 public void setSharedUser(SharedUserSetting user) { 14835 mSharedUser = user; 14836 } 14837 } 14838 14839 @Override 14840 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14841 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14842 != PackageManager.PERMISSION_GRANTED) { 14843 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14844 + Binder.getCallingPid() 14845 + ", uid=" + Binder.getCallingUid() 14846 + " without permission " 14847 + android.Manifest.permission.DUMP); 14848 return; 14849 } 14850 14851 DumpState dumpState = new DumpState(); 14852 boolean fullPreferred = false; 14853 boolean checkin = false; 14854 14855 String packageName = null; 14856 ArraySet<String> permissionNames = null; 14857 14858 int opti = 0; 14859 while (opti < args.length) { 14860 String opt = args[opti]; 14861 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14862 break; 14863 } 14864 opti++; 14865 14866 if ("-a".equals(opt)) { 14867 // Right now we only know how to print all. 14868 } else if ("-h".equals(opt)) { 14869 pw.println("Package manager dump options:"); 14870 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14871 pw.println(" --checkin: dump for a checkin"); 14872 pw.println(" -f: print details of intent filters"); 14873 pw.println(" -h: print this help"); 14874 pw.println(" cmd may be one of:"); 14875 pw.println(" l[ibraries]: list known shared libraries"); 14876 pw.println(" f[ibraries]: list device features"); 14877 pw.println(" k[eysets]: print known keysets"); 14878 pw.println(" r[esolvers]: dump intent resolvers"); 14879 pw.println(" perm[issions]: dump permissions"); 14880 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14881 pw.println(" pref[erred]: print preferred package settings"); 14882 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14883 pw.println(" prov[iders]: dump content providers"); 14884 pw.println(" p[ackages]: dump installed packages"); 14885 pw.println(" s[hared-users]: dump shared user IDs"); 14886 pw.println(" m[essages]: print collected runtime messages"); 14887 pw.println(" v[erifiers]: print package verifier info"); 14888 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14889 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14890 pw.println(" version: print database version info"); 14891 pw.println(" write: write current settings now"); 14892 pw.println(" installs: details about install sessions"); 14893 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14894 pw.println(" <package.name>: info about given package"); 14895 return; 14896 } else if ("--checkin".equals(opt)) { 14897 checkin = true; 14898 } else if ("-f".equals(opt)) { 14899 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14900 } else { 14901 pw.println("Unknown argument: " + opt + "; use -h for help"); 14902 } 14903 } 14904 14905 // Is the caller requesting to dump a particular piece of data? 14906 if (opti < args.length) { 14907 String cmd = args[opti]; 14908 opti++; 14909 // Is this a package name? 14910 if ("android".equals(cmd) || cmd.contains(".")) { 14911 packageName = cmd; 14912 // When dumping a single package, we always dump all of its 14913 // filter information since the amount of data will be reasonable. 14914 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14915 } else if ("check-permission".equals(cmd)) { 14916 if (opti >= args.length) { 14917 pw.println("Error: check-permission missing permission argument"); 14918 return; 14919 } 14920 String perm = args[opti]; 14921 opti++; 14922 if (opti >= args.length) { 14923 pw.println("Error: check-permission missing package argument"); 14924 return; 14925 } 14926 String pkg = args[opti]; 14927 opti++; 14928 int user = UserHandle.getUserId(Binder.getCallingUid()); 14929 if (opti < args.length) { 14930 try { 14931 user = Integer.parseInt(args[opti]); 14932 } catch (NumberFormatException e) { 14933 pw.println("Error: check-permission user argument is not a number: " 14934 + args[opti]); 14935 return; 14936 } 14937 } 14938 pw.println(checkPermission(perm, pkg, user)); 14939 return; 14940 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14941 dumpState.setDump(DumpState.DUMP_LIBS); 14942 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14943 dumpState.setDump(DumpState.DUMP_FEATURES); 14944 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14945 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14946 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14947 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14948 } else if ("permission".equals(cmd)) { 14949 if (opti >= args.length) { 14950 pw.println("Error: permission requires permission name"); 14951 return; 14952 } 14953 permissionNames = new ArraySet<>(); 14954 while (opti < args.length) { 14955 permissionNames.add(args[opti]); 14956 opti++; 14957 } 14958 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14959 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14960 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14961 dumpState.setDump(DumpState.DUMP_PREFERRED); 14962 } else if ("preferred-xml".equals(cmd)) { 14963 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14964 if (opti < args.length && "--full".equals(args[opti])) { 14965 fullPreferred = true; 14966 opti++; 14967 } 14968 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14969 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14970 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14971 dumpState.setDump(DumpState.DUMP_PACKAGES); 14972 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14973 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14974 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14975 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14976 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_MESSAGES); 14978 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14979 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14980 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14981 || "intent-filter-verifiers".equals(cmd)) { 14982 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14983 } else if ("version".equals(cmd)) { 14984 dumpState.setDump(DumpState.DUMP_VERSION); 14985 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14986 dumpState.setDump(DumpState.DUMP_KEYSETS); 14987 } else if ("installs".equals(cmd)) { 14988 dumpState.setDump(DumpState.DUMP_INSTALLS); 14989 } else if ("write".equals(cmd)) { 14990 synchronized (mPackages) { 14991 mSettings.writeLPr(); 14992 pw.println("Settings written."); 14993 return; 14994 } 14995 } 14996 } 14997 14998 if (checkin) { 14999 pw.println("vers,1"); 15000 } 15001 15002 // reader 15003 synchronized (mPackages) { 15004 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15005 if (!checkin) { 15006 if (dumpState.onTitlePrinted()) 15007 pw.println(); 15008 pw.println("Database versions:"); 15009 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15010 } 15011 } 15012 15013 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15014 if (!checkin) { 15015 if (dumpState.onTitlePrinted()) 15016 pw.println(); 15017 pw.println("Verifiers:"); 15018 pw.print(" Required: "); 15019 pw.print(mRequiredVerifierPackage); 15020 pw.print(" (uid="); 15021 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15022 pw.println(")"); 15023 } else if (mRequiredVerifierPackage != null) { 15024 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15025 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15026 } 15027 } 15028 15029 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15030 packageName == null) { 15031 if (mIntentFilterVerifierComponent != null) { 15032 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15033 if (!checkin) { 15034 if (dumpState.onTitlePrinted()) 15035 pw.println(); 15036 pw.println("Intent Filter Verifier:"); 15037 pw.print(" Using: "); 15038 pw.print(verifierPackageName); 15039 pw.print(" (uid="); 15040 pw.print(getPackageUid(verifierPackageName, 0)); 15041 pw.println(")"); 15042 } else if (verifierPackageName != null) { 15043 pw.print("ifv,"); pw.print(verifierPackageName); 15044 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15045 } 15046 } else { 15047 pw.println(); 15048 pw.println("No Intent Filter Verifier available!"); 15049 } 15050 } 15051 15052 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15053 boolean printedHeader = false; 15054 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15055 while (it.hasNext()) { 15056 String name = it.next(); 15057 SharedLibraryEntry ent = mSharedLibraries.get(name); 15058 if (!checkin) { 15059 if (!printedHeader) { 15060 if (dumpState.onTitlePrinted()) 15061 pw.println(); 15062 pw.println("Libraries:"); 15063 printedHeader = true; 15064 } 15065 pw.print(" "); 15066 } else { 15067 pw.print("lib,"); 15068 } 15069 pw.print(name); 15070 if (!checkin) { 15071 pw.print(" -> "); 15072 } 15073 if (ent.path != null) { 15074 if (!checkin) { 15075 pw.print("(jar) "); 15076 pw.print(ent.path); 15077 } else { 15078 pw.print(",jar,"); 15079 pw.print(ent.path); 15080 } 15081 } else { 15082 if (!checkin) { 15083 pw.print("(apk) "); 15084 pw.print(ent.apk); 15085 } else { 15086 pw.print(",apk,"); 15087 pw.print(ent.apk); 15088 } 15089 } 15090 pw.println(); 15091 } 15092 } 15093 15094 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15095 if (dumpState.onTitlePrinted()) 15096 pw.println(); 15097 if (!checkin) { 15098 pw.println("Features:"); 15099 } 15100 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15101 while (it.hasNext()) { 15102 String name = it.next(); 15103 if (!checkin) { 15104 pw.print(" "); 15105 } else { 15106 pw.print("feat,"); 15107 } 15108 pw.println(name); 15109 } 15110 } 15111 15112 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15113 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15114 : "Activity Resolver Table:", " ", packageName, 15115 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15116 dumpState.setTitlePrinted(true); 15117 } 15118 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15119 : "Receiver Resolver Table:", " ", packageName, 15120 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15121 dumpState.setTitlePrinted(true); 15122 } 15123 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15124 : "Service Resolver Table:", " ", packageName, 15125 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15126 dumpState.setTitlePrinted(true); 15127 } 15128 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15129 : "Provider Resolver Table:", " ", packageName, 15130 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15131 dumpState.setTitlePrinted(true); 15132 } 15133 } 15134 15135 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15136 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15137 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15138 int user = mSettings.mPreferredActivities.keyAt(i); 15139 if (pir.dump(pw, 15140 dumpState.getTitlePrinted() 15141 ? "\nPreferred Activities User " + user + ":" 15142 : "Preferred Activities User " + user + ":", " ", 15143 packageName, true, false)) { 15144 dumpState.setTitlePrinted(true); 15145 } 15146 } 15147 } 15148 15149 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15150 pw.flush(); 15151 FileOutputStream fout = new FileOutputStream(fd); 15152 BufferedOutputStream str = new BufferedOutputStream(fout); 15153 XmlSerializer serializer = new FastXmlSerializer(); 15154 try { 15155 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15156 serializer.startDocument(null, true); 15157 serializer.setFeature( 15158 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15159 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15160 serializer.endDocument(); 15161 serializer.flush(); 15162 } catch (IllegalArgumentException e) { 15163 pw.println("Failed writing: " + e); 15164 } catch (IllegalStateException e) { 15165 pw.println("Failed writing: " + e); 15166 } catch (IOException e) { 15167 pw.println("Failed writing: " + e); 15168 } 15169 } 15170 15171 if (!checkin 15172 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15173 && packageName == null) { 15174 pw.println(); 15175 int count = mSettings.mPackages.size(); 15176 if (count == 0) { 15177 pw.println("No applications!"); 15178 pw.println(); 15179 } else { 15180 final String prefix = " "; 15181 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15182 if (allPackageSettings.size() == 0) { 15183 pw.println("No domain preferred apps!"); 15184 pw.println(); 15185 } else { 15186 pw.println("App verification status:"); 15187 pw.println(); 15188 count = 0; 15189 for (PackageSetting ps : allPackageSettings) { 15190 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15191 if (ivi == null || ivi.getPackageName() == null) continue; 15192 pw.println(prefix + "Package: " + ivi.getPackageName()); 15193 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15194 pw.println(prefix + "Status: " + ivi.getStatusString()); 15195 pw.println(); 15196 count++; 15197 } 15198 if (count == 0) { 15199 pw.println(prefix + "No app verification established."); 15200 pw.println(); 15201 } 15202 for (int userId : sUserManager.getUserIds()) { 15203 pw.println("App linkages for user " + userId + ":"); 15204 pw.println(); 15205 count = 0; 15206 for (PackageSetting ps : allPackageSettings) { 15207 final long status = ps.getDomainVerificationStatusForUser(userId); 15208 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15209 continue; 15210 } 15211 pw.println(prefix + "Package: " + ps.name); 15212 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15213 String statusStr = IntentFilterVerificationInfo. 15214 getStatusStringFromValue(status); 15215 pw.println(prefix + "Status: " + statusStr); 15216 pw.println(); 15217 count++; 15218 } 15219 if (count == 0) { 15220 pw.println(prefix + "No configured app linkages."); 15221 pw.println(); 15222 } 15223 } 15224 } 15225 } 15226 } 15227 15228 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15229 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15230 if (packageName == null && permissionNames == null) { 15231 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15232 if (iperm == 0) { 15233 if (dumpState.onTitlePrinted()) 15234 pw.println(); 15235 pw.println("AppOp Permissions:"); 15236 } 15237 pw.print(" AppOp Permission "); 15238 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15239 pw.println(":"); 15240 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15241 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15242 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15243 } 15244 } 15245 } 15246 } 15247 15248 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15249 boolean printedSomething = false; 15250 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15251 if (packageName != null && !packageName.equals(p.info.packageName)) { 15252 continue; 15253 } 15254 if (!printedSomething) { 15255 if (dumpState.onTitlePrinted()) 15256 pw.println(); 15257 pw.println("Registered ContentProviders:"); 15258 printedSomething = true; 15259 } 15260 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15261 pw.print(" "); pw.println(p.toString()); 15262 } 15263 printedSomething = false; 15264 for (Map.Entry<String, PackageParser.Provider> entry : 15265 mProvidersByAuthority.entrySet()) { 15266 PackageParser.Provider p = entry.getValue(); 15267 if (packageName != null && !packageName.equals(p.info.packageName)) { 15268 continue; 15269 } 15270 if (!printedSomething) { 15271 if (dumpState.onTitlePrinted()) 15272 pw.println(); 15273 pw.println("ContentProvider Authorities:"); 15274 printedSomething = true; 15275 } 15276 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15277 pw.print(" "); pw.println(p.toString()); 15278 if (p.info != null && p.info.applicationInfo != null) { 15279 final String appInfo = p.info.applicationInfo.toString(); 15280 pw.print(" applicationInfo="); pw.println(appInfo); 15281 } 15282 } 15283 } 15284 15285 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15286 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15287 } 15288 15289 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15290 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15291 } 15292 15293 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15294 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15295 } 15296 15297 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15298 // XXX should handle packageName != null by dumping only install data that 15299 // the given package is involved with. 15300 if (dumpState.onTitlePrinted()) pw.println(); 15301 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15302 } 15303 15304 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15305 if (dumpState.onTitlePrinted()) pw.println(); 15306 mSettings.dumpReadMessagesLPr(pw, dumpState); 15307 15308 pw.println(); 15309 pw.println("Package warning messages:"); 15310 BufferedReader in = null; 15311 String line = null; 15312 try { 15313 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15314 while ((line = in.readLine()) != null) { 15315 if (line.contains("ignored: updated version")) continue; 15316 pw.println(line); 15317 } 15318 } catch (IOException ignored) { 15319 } finally { 15320 IoUtils.closeQuietly(in); 15321 } 15322 } 15323 15324 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15325 BufferedReader in = null; 15326 String line = null; 15327 try { 15328 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15329 while ((line = in.readLine()) != null) { 15330 if (line.contains("ignored: updated version")) continue; 15331 pw.print("msg,"); 15332 pw.println(line); 15333 } 15334 } catch (IOException ignored) { 15335 } finally { 15336 IoUtils.closeQuietly(in); 15337 } 15338 } 15339 } 15340 } 15341 15342 private String dumpDomainString(String packageName) { 15343 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15344 List<IntentFilter> filters = getAllIntentFilters(packageName); 15345 15346 ArraySet<String> result = new ArraySet<>(); 15347 if (iviList.size() > 0) { 15348 for (IntentFilterVerificationInfo ivi : iviList) { 15349 for (String host : ivi.getDomains()) { 15350 result.add(host); 15351 } 15352 } 15353 } 15354 if (filters != null && filters.size() > 0) { 15355 for (IntentFilter filter : filters) { 15356 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15357 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15358 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15359 result.addAll(filter.getHostsList()); 15360 } 15361 } 15362 } 15363 15364 StringBuilder sb = new StringBuilder(result.size() * 16); 15365 for (String domain : result) { 15366 if (sb.length() > 0) sb.append(" "); 15367 sb.append(domain); 15368 } 15369 return sb.toString(); 15370 } 15371 15372 // ------- apps on sdcard specific code ------- 15373 static final boolean DEBUG_SD_INSTALL = false; 15374 15375 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15376 15377 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15378 15379 private boolean mMediaMounted = false; 15380 15381 static String getEncryptKey() { 15382 try { 15383 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15384 SD_ENCRYPTION_KEYSTORE_NAME); 15385 if (sdEncKey == null) { 15386 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15387 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15388 if (sdEncKey == null) { 15389 Slog.e(TAG, "Failed to create encryption keys"); 15390 return null; 15391 } 15392 } 15393 return sdEncKey; 15394 } catch (NoSuchAlgorithmException nsae) { 15395 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15396 return null; 15397 } catch (IOException ioe) { 15398 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15399 return null; 15400 } 15401 } 15402 15403 /* 15404 * Update media status on PackageManager. 15405 */ 15406 @Override 15407 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15408 int callingUid = Binder.getCallingUid(); 15409 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15410 throw new SecurityException("Media status can only be updated by the system"); 15411 } 15412 // reader; this apparently protects mMediaMounted, but should probably 15413 // be a different lock in that case. 15414 synchronized (mPackages) { 15415 Log.i(TAG, "Updating external media status from " 15416 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15417 + (mediaStatus ? "mounted" : "unmounted")); 15418 if (DEBUG_SD_INSTALL) 15419 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15420 + ", mMediaMounted=" + mMediaMounted); 15421 if (mediaStatus == mMediaMounted) { 15422 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15423 : 0, -1); 15424 mHandler.sendMessage(msg); 15425 return; 15426 } 15427 mMediaMounted = mediaStatus; 15428 } 15429 // Queue up an async operation since the package installation may take a 15430 // little while. 15431 mHandler.post(new Runnable() { 15432 public void run() { 15433 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15434 } 15435 }); 15436 } 15437 15438 /** 15439 * Called by MountService when the initial ASECs to scan are available. 15440 * Should block until all the ASEC containers are finished being scanned. 15441 */ 15442 public void scanAvailableAsecs() { 15443 updateExternalMediaStatusInner(true, false, false); 15444 if (mShouldRestoreconData) { 15445 SELinuxMMAC.setRestoreconDone(); 15446 mShouldRestoreconData = false; 15447 } 15448 } 15449 15450 /* 15451 * Collect information of applications on external media, map them against 15452 * existing containers and update information based on current mount status. 15453 * Please note that we always have to report status if reportStatus has been 15454 * set to true especially when unloading packages. 15455 */ 15456 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15457 boolean externalStorage) { 15458 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15459 int[] uidArr = EmptyArray.INT; 15460 15461 final String[] list = PackageHelper.getSecureContainerList(); 15462 if (ArrayUtils.isEmpty(list)) { 15463 Log.i(TAG, "No secure containers found"); 15464 } else { 15465 // Process list of secure containers and categorize them 15466 // as active or stale based on their package internal state. 15467 15468 // reader 15469 synchronized (mPackages) { 15470 for (String cid : list) { 15471 // Leave stages untouched for now; installer service owns them 15472 if (PackageInstallerService.isStageName(cid)) continue; 15473 15474 if (DEBUG_SD_INSTALL) 15475 Log.i(TAG, "Processing container " + cid); 15476 String pkgName = getAsecPackageName(cid); 15477 if (pkgName == null) { 15478 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15479 continue; 15480 } 15481 if (DEBUG_SD_INSTALL) 15482 Log.i(TAG, "Looking for pkg : " + pkgName); 15483 15484 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15485 if (ps == null) { 15486 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15487 continue; 15488 } 15489 15490 /* 15491 * Skip packages that are not external if we're unmounting 15492 * external storage. 15493 */ 15494 if (externalStorage && !isMounted && !isExternal(ps)) { 15495 continue; 15496 } 15497 15498 final AsecInstallArgs args = new AsecInstallArgs(cid, 15499 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15500 // The package status is changed only if the code path 15501 // matches between settings and the container id. 15502 if (ps.codePathString != null 15503 && ps.codePathString.startsWith(args.getCodePath())) { 15504 if (DEBUG_SD_INSTALL) { 15505 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15506 + " at code path: " + ps.codePathString); 15507 } 15508 15509 // We do have a valid package installed on sdcard 15510 processCids.put(args, ps.codePathString); 15511 final int uid = ps.appId; 15512 if (uid != -1) { 15513 uidArr = ArrayUtils.appendInt(uidArr, uid); 15514 } 15515 } else { 15516 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15517 + ps.codePathString); 15518 } 15519 } 15520 } 15521 15522 Arrays.sort(uidArr); 15523 } 15524 15525 // Process packages with valid entries. 15526 if (isMounted) { 15527 if (DEBUG_SD_INSTALL) 15528 Log.i(TAG, "Loading packages"); 15529 loadMediaPackages(processCids, uidArr, externalStorage); 15530 startCleaningPackages(); 15531 mInstallerService.onSecureContainersAvailable(); 15532 } else { 15533 if (DEBUG_SD_INSTALL) 15534 Log.i(TAG, "Unloading packages"); 15535 unloadMediaPackages(processCids, uidArr, reportStatus); 15536 } 15537 } 15538 15539 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15540 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15541 final int size = infos.size(); 15542 final String[] packageNames = new String[size]; 15543 final int[] packageUids = new int[size]; 15544 for (int i = 0; i < size; i++) { 15545 final ApplicationInfo info = infos.get(i); 15546 packageNames[i] = info.packageName; 15547 packageUids[i] = info.uid; 15548 } 15549 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15550 finishedReceiver); 15551 } 15552 15553 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15554 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15555 sendResourcesChangedBroadcast(mediaStatus, replacing, 15556 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15557 } 15558 15559 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15560 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15561 int size = pkgList.length; 15562 if (size > 0) { 15563 // Send broadcasts here 15564 Bundle extras = new Bundle(); 15565 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15566 if (uidArr != null) { 15567 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15568 } 15569 if (replacing) { 15570 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15571 } 15572 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15573 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15574 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15575 } 15576 } 15577 15578 /* 15579 * Look at potentially valid container ids from processCids If package 15580 * information doesn't match the one on record or package scanning fails, 15581 * the cid is added to list of removeCids. We currently don't delete stale 15582 * containers. 15583 */ 15584 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15585 boolean externalStorage) { 15586 ArrayList<String> pkgList = new ArrayList<String>(); 15587 Set<AsecInstallArgs> keys = processCids.keySet(); 15588 15589 for (AsecInstallArgs args : keys) { 15590 String codePath = processCids.get(args); 15591 if (DEBUG_SD_INSTALL) 15592 Log.i(TAG, "Loading container : " + args.cid); 15593 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15594 try { 15595 // Make sure there are no container errors first. 15596 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15597 Slog.e(TAG, "Failed to mount cid : " + args.cid 15598 + " when installing from sdcard"); 15599 continue; 15600 } 15601 // Check code path here. 15602 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15603 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15604 + " does not match one in settings " + codePath); 15605 continue; 15606 } 15607 // Parse package 15608 int parseFlags = mDefParseFlags; 15609 if (args.isExternalAsec()) { 15610 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15611 } 15612 if (args.isFwdLocked()) { 15613 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15614 } 15615 15616 synchronized (mInstallLock) { 15617 PackageParser.Package pkg = null; 15618 try { 15619 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15620 } catch (PackageManagerException e) { 15621 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15622 } 15623 // Scan the package 15624 if (pkg != null) { 15625 /* 15626 * TODO why is the lock being held? doPostInstall is 15627 * called in other places without the lock. This needs 15628 * to be straightened out. 15629 */ 15630 // writer 15631 synchronized (mPackages) { 15632 retCode = PackageManager.INSTALL_SUCCEEDED; 15633 pkgList.add(pkg.packageName); 15634 // Post process args 15635 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15636 pkg.applicationInfo.uid); 15637 } 15638 } else { 15639 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15640 } 15641 } 15642 15643 } finally { 15644 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15645 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15646 } 15647 } 15648 } 15649 // writer 15650 synchronized (mPackages) { 15651 // If the platform SDK has changed since the last time we booted, 15652 // we need to re-grant app permission to catch any new ones that 15653 // appear. This is really a hack, and means that apps can in some 15654 // cases get permissions that the user didn't initially explicitly 15655 // allow... it would be nice to have some better way to handle 15656 // this situation. 15657 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15658 : mSettings.getInternalVersion(); 15659 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15660 : StorageManager.UUID_PRIVATE_INTERNAL; 15661 15662 int updateFlags = UPDATE_PERMISSIONS_ALL; 15663 if (ver.sdkVersion != mSdkVersion) { 15664 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15665 + mSdkVersion + "; regranting permissions for external"); 15666 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15667 } 15668 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15669 15670 // Yay, everything is now upgraded 15671 ver.forceCurrent(); 15672 15673 // can downgrade to reader 15674 // Persist settings 15675 mSettings.writeLPr(); 15676 } 15677 // Send a broadcast to let everyone know we are done processing 15678 if (pkgList.size() > 0) { 15679 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15680 } 15681 } 15682 15683 /* 15684 * Utility method to unload a list of specified containers 15685 */ 15686 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15687 // Just unmount all valid containers. 15688 for (AsecInstallArgs arg : cidArgs) { 15689 synchronized (mInstallLock) { 15690 arg.doPostDeleteLI(false); 15691 } 15692 } 15693 } 15694 15695 /* 15696 * Unload packages mounted on external media. This involves deleting package 15697 * data from internal structures, sending broadcasts about diabled packages, 15698 * gc'ing to free up references, unmounting all secure containers 15699 * corresponding to packages on external media, and posting a 15700 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15701 * that we always have to post this message if status has been requested no 15702 * matter what. 15703 */ 15704 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15705 final boolean reportStatus) { 15706 if (DEBUG_SD_INSTALL) 15707 Log.i(TAG, "unloading media packages"); 15708 ArrayList<String> pkgList = new ArrayList<String>(); 15709 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15710 final Set<AsecInstallArgs> keys = processCids.keySet(); 15711 for (AsecInstallArgs args : keys) { 15712 String pkgName = args.getPackageName(); 15713 if (DEBUG_SD_INSTALL) 15714 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15715 // Delete package internally 15716 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15717 synchronized (mInstallLock) { 15718 boolean res = deletePackageLI(pkgName, null, false, null, null, 15719 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15720 if (res) { 15721 pkgList.add(pkgName); 15722 } else { 15723 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15724 failedList.add(args); 15725 } 15726 } 15727 } 15728 15729 // reader 15730 synchronized (mPackages) { 15731 // We didn't update the settings after removing each package; 15732 // write them now for all packages. 15733 mSettings.writeLPr(); 15734 } 15735 15736 // We have to absolutely send UPDATED_MEDIA_STATUS only 15737 // after confirming that all the receivers processed the ordered 15738 // broadcast when packages get disabled, force a gc to clean things up. 15739 // and unload all the containers. 15740 if (pkgList.size() > 0) { 15741 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15742 new IIntentReceiver.Stub() { 15743 public void performReceive(Intent intent, int resultCode, String data, 15744 Bundle extras, boolean ordered, boolean sticky, 15745 int sendingUser) throws RemoteException { 15746 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15747 reportStatus ? 1 : 0, 1, keys); 15748 mHandler.sendMessage(msg); 15749 } 15750 }); 15751 } else { 15752 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15753 keys); 15754 mHandler.sendMessage(msg); 15755 } 15756 } 15757 15758 private void loadPrivatePackages(final VolumeInfo vol) { 15759 mHandler.post(new Runnable() { 15760 @Override 15761 public void run() { 15762 loadPrivatePackagesInner(vol); 15763 } 15764 }); 15765 } 15766 15767 private void loadPrivatePackagesInner(VolumeInfo vol) { 15768 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15769 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15770 15771 final VersionInfo ver; 15772 final List<PackageSetting> packages; 15773 synchronized (mPackages) { 15774 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15775 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15776 } 15777 15778 for (PackageSetting ps : packages) { 15779 synchronized (mInstallLock) { 15780 final PackageParser.Package pkg; 15781 try { 15782 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15783 loaded.add(pkg.applicationInfo); 15784 } catch (PackageManagerException e) { 15785 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15786 } 15787 15788 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15789 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15790 } 15791 } 15792 } 15793 15794 synchronized (mPackages) { 15795 int updateFlags = UPDATE_PERMISSIONS_ALL; 15796 if (ver.sdkVersion != mSdkVersion) { 15797 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15798 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15799 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15800 } 15801 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15802 15803 // Yay, everything is now upgraded 15804 ver.forceCurrent(); 15805 15806 mSettings.writeLPr(); 15807 } 15808 15809 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15810 sendResourcesChangedBroadcast(true, false, loaded, null); 15811 } 15812 15813 private void unloadPrivatePackages(final VolumeInfo vol) { 15814 mHandler.post(new Runnable() { 15815 @Override 15816 public void run() { 15817 unloadPrivatePackagesInner(vol); 15818 } 15819 }); 15820 } 15821 15822 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15823 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15824 synchronized (mInstallLock) { 15825 synchronized (mPackages) { 15826 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15827 for (PackageSetting ps : packages) { 15828 if (ps.pkg == null) continue; 15829 15830 final ApplicationInfo info = ps.pkg.applicationInfo; 15831 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15832 if (deletePackageLI(ps.name, null, false, null, null, 15833 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15834 unloaded.add(info); 15835 } else { 15836 Slog.w(TAG, "Failed to unload " + ps.codePath); 15837 } 15838 } 15839 15840 mSettings.writeLPr(); 15841 } 15842 } 15843 15844 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15845 sendResourcesChangedBroadcast(false, false, unloaded, null); 15846 } 15847 15848 /** 15849 * Examine all users present on given mounted volume, and destroy data 15850 * belonging to users that are no longer valid, or whose user ID has been 15851 * recycled. 15852 */ 15853 private void reconcileUsers(String volumeUuid) { 15854 final File[] files = FileUtils 15855 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15856 for (File file : files) { 15857 if (!file.isDirectory()) continue; 15858 15859 final int userId; 15860 final UserInfo info; 15861 try { 15862 userId = Integer.parseInt(file.getName()); 15863 info = sUserManager.getUserInfo(userId); 15864 } catch (NumberFormatException e) { 15865 Slog.w(TAG, "Invalid user directory " + file); 15866 continue; 15867 } 15868 15869 boolean destroyUser = false; 15870 if (info == null) { 15871 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15872 + " because no matching user was found"); 15873 destroyUser = true; 15874 } else { 15875 try { 15876 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15877 } catch (IOException e) { 15878 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15879 + " because we failed to enforce serial number: " + e); 15880 destroyUser = true; 15881 } 15882 } 15883 15884 if (destroyUser) { 15885 synchronized (mInstallLock) { 15886 mInstaller.removeUserDataDirs(volumeUuid, userId); 15887 } 15888 } 15889 } 15890 15891 final UserManager um = mContext.getSystemService(UserManager.class); 15892 for (UserInfo user : um.getUsers()) { 15893 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15894 if (userDir.exists()) continue; 15895 15896 try { 15897 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15898 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15899 } catch (IOException e) { 15900 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15901 } 15902 } 15903 } 15904 15905 /** 15906 * Examine all apps present on given mounted volume, and destroy apps that 15907 * aren't expected, either due to uninstallation or reinstallation on 15908 * another volume. 15909 */ 15910 private void reconcileApps(String volumeUuid) { 15911 final File[] files = FileUtils 15912 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15913 for (File file : files) { 15914 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15915 && !PackageInstallerService.isStageName(file.getName()); 15916 if (!isPackage) { 15917 // Ignore entries which are not packages 15918 continue; 15919 } 15920 15921 boolean destroyApp = false; 15922 String packageName = null; 15923 try { 15924 final PackageLite pkg = PackageParser.parsePackageLite(file, 15925 PackageParser.PARSE_MUST_BE_APK); 15926 packageName = pkg.packageName; 15927 15928 synchronized (mPackages) { 15929 final PackageSetting ps = mSettings.mPackages.get(packageName); 15930 if (ps == null) { 15931 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15932 + volumeUuid + " because we found no install record"); 15933 destroyApp = true; 15934 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15935 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15936 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15937 destroyApp = true; 15938 } 15939 } 15940 15941 } catch (PackageParserException e) { 15942 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15943 destroyApp = true; 15944 } 15945 15946 if (destroyApp) { 15947 synchronized (mInstallLock) { 15948 if (packageName != null) { 15949 removeDataDirsLI(volumeUuid, packageName); 15950 } 15951 if (file.isDirectory()) { 15952 mInstaller.rmPackageDir(file.getAbsolutePath()); 15953 } else { 15954 file.delete(); 15955 } 15956 } 15957 } 15958 } 15959 } 15960 15961 private void unfreezePackage(String packageName) { 15962 synchronized (mPackages) { 15963 final PackageSetting ps = mSettings.mPackages.get(packageName); 15964 if (ps != null) { 15965 ps.frozen = false; 15966 } 15967 } 15968 } 15969 15970 @Override 15971 public int movePackage(final String packageName, final String volumeUuid) { 15972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15973 15974 final int moveId = mNextMoveId.getAndIncrement(); 15975 try { 15976 movePackageInternal(packageName, volumeUuid, moveId); 15977 } catch (PackageManagerException e) { 15978 Slog.w(TAG, "Failed to move " + packageName, e); 15979 mMoveCallbacks.notifyStatusChanged(moveId, 15980 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15981 } 15982 return moveId; 15983 } 15984 15985 private void movePackageInternal(final String packageName, final String volumeUuid, 15986 final int moveId) throws PackageManagerException { 15987 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15988 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15989 final PackageManager pm = mContext.getPackageManager(); 15990 15991 final boolean currentAsec; 15992 final String currentVolumeUuid; 15993 final File codeFile; 15994 final String installerPackageName; 15995 final String packageAbiOverride; 15996 final int appId; 15997 final String seinfo; 15998 final String label; 15999 16000 // reader 16001 synchronized (mPackages) { 16002 final PackageParser.Package pkg = mPackages.get(packageName); 16003 final PackageSetting ps = mSettings.mPackages.get(packageName); 16004 if (pkg == null || ps == null) { 16005 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16006 } 16007 16008 if (pkg.applicationInfo.isSystemApp()) { 16009 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16010 "Cannot move system application"); 16011 } 16012 16013 if (pkg.applicationInfo.isExternalAsec()) { 16014 currentAsec = true; 16015 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16016 } else if (pkg.applicationInfo.isForwardLocked()) { 16017 currentAsec = true; 16018 currentVolumeUuid = "forward_locked"; 16019 } else { 16020 currentAsec = false; 16021 currentVolumeUuid = ps.volumeUuid; 16022 16023 final File probe = new File(pkg.codePath); 16024 final File probeOat = new File(probe, "oat"); 16025 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16026 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16027 "Move only supported for modern cluster style installs"); 16028 } 16029 } 16030 16031 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16032 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16033 "Package already moved to " + volumeUuid); 16034 } 16035 16036 if (ps.frozen) { 16037 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16038 "Failed to move already frozen package"); 16039 } 16040 ps.frozen = true; 16041 16042 codeFile = new File(pkg.codePath); 16043 installerPackageName = ps.installerPackageName; 16044 packageAbiOverride = ps.cpuAbiOverrideString; 16045 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16046 seinfo = pkg.applicationInfo.seinfo; 16047 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16048 } 16049 16050 // Now that we're guarded by frozen state, kill app during move 16051 final long token = Binder.clearCallingIdentity(); 16052 try { 16053 killApplication(packageName, appId, "move pkg"); 16054 } finally { 16055 Binder.restoreCallingIdentity(token); 16056 } 16057 16058 final Bundle extras = new Bundle(); 16059 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16060 extras.putString(Intent.EXTRA_TITLE, label); 16061 mMoveCallbacks.notifyCreated(moveId, extras); 16062 16063 int installFlags; 16064 final boolean moveCompleteApp; 16065 final File measurePath; 16066 16067 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16068 installFlags = INSTALL_INTERNAL; 16069 moveCompleteApp = !currentAsec; 16070 measurePath = Environment.getDataAppDirectory(volumeUuid); 16071 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16072 installFlags = INSTALL_EXTERNAL; 16073 moveCompleteApp = false; 16074 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16075 } else { 16076 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16077 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16078 || !volume.isMountedWritable()) { 16079 unfreezePackage(packageName); 16080 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16081 "Move location not mounted private volume"); 16082 } 16083 16084 Preconditions.checkState(!currentAsec); 16085 16086 installFlags = INSTALL_INTERNAL; 16087 moveCompleteApp = true; 16088 measurePath = Environment.getDataAppDirectory(volumeUuid); 16089 } 16090 16091 final PackageStats stats = new PackageStats(null, -1); 16092 synchronized (mInstaller) { 16093 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16094 unfreezePackage(packageName); 16095 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16096 "Failed to measure package size"); 16097 } 16098 } 16099 16100 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16101 + stats.dataSize); 16102 16103 final long startFreeBytes = measurePath.getFreeSpace(); 16104 final long sizeBytes; 16105 if (moveCompleteApp) { 16106 sizeBytes = stats.codeSize + stats.dataSize; 16107 } else { 16108 sizeBytes = stats.codeSize; 16109 } 16110 16111 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16112 unfreezePackage(packageName); 16113 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16114 "Not enough free space to move"); 16115 } 16116 16117 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16118 16119 final CountDownLatch installedLatch = new CountDownLatch(1); 16120 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16121 @Override 16122 public void onUserActionRequired(Intent intent) throws RemoteException { 16123 throw new IllegalStateException(); 16124 } 16125 16126 @Override 16127 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16128 Bundle extras) throws RemoteException { 16129 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16130 + PackageManager.installStatusToString(returnCode, msg)); 16131 16132 installedLatch.countDown(); 16133 16134 // Regardless of success or failure of the move operation, 16135 // always unfreeze the package 16136 unfreezePackage(packageName); 16137 16138 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16139 switch (status) { 16140 case PackageInstaller.STATUS_SUCCESS: 16141 mMoveCallbacks.notifyStatusChanged(moveId, 16142 PackageManager.MOVE_SUCCEEDED); 16143 break; 16144 case PackageInstaller.STATUS_FAILURE_STORAGE: 16145 mMoveCallbacks.notifyStatusChanged(moveId, 16146 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16147 break; 16148 default: 16149 mMoveCallbacks.notifyStatusChanged(moveId, 16150 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16151 break; 16152 } 16153 } 16154 }; 16155 16156 final MoveInfo move; 16157 if (moveCompleteApp) { 16158 // Kick off a thread to report progress estimates 16159 new Thread() { 16160 @Override 16161 public void run() { 16162 while (true) { 16163 try { 16164 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16165 break; 16166 } 16167 } catch (InterruptedException ignored) { 16168 } 16169 16170 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16171 final int progress = 10 + (int) MathUtils.constrain( 16172 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16173 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16174 } 16175 } 16176 }.start(); 16177 16178 final String dataAppName = codeFile.getName(); 16179 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16180 dataAppName, appId, seinfo); 16181 } else { 16182 move = null; 16183 } 16184 16185 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16186 16187 final Message msg = mHandler.obtainMessage(INIT_COPY); 16188 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16189 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16190 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16191 mHandler.sendMessage(msg); 16192 } 16193 16194 @Override 16195 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16196 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16197 16198 final int realMoveId = mNextMoveId.getAndIncrement(); 16199 final Bundle extras = new Bundle(); 16200 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16201 mMoveCallbacks.notifyCreated(realMoveId, extras); 16202 16203 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16204 @Override 16205 public void onCreated(int moveId, Bundle extras) { 16206 // Ignored 16207 } 16208 16209 @Override 16210 public void onStatusChanged(int moveId, int status, long estMillis) { 16211 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16212 } 16213 }; 16214 16215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16216 storage.setPrimaryStorageUuid(volumeUuid, callback); 16217 return realMoveId; 16218 } 16219 16220 @Override 16221 public int getMoveStatus(int moveId) { 16222 mContext.enforceCallingOrSelfPermission( 16223 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16224 return mMoveCallbacks.mLastStatus.get(moveId); 16225 } 16226 16227 @Override 16228 public void registerMoveCallback(IPackageMoveObserver callback) { 16229 mContext.enforceCallingOrSelfPermission( 16230 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16231 mMoveCallbacks.register(callback); 16232 } 16233 16234 @Override 16235 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16236 mContext.enforceCallingOrSelfPermission( 16237 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16238 mMoveCallbacks.unregister(callback); 16239 } 16240 16241 @Override 16242 public boolean setInstallLocation(int loc) { 16243 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16244 null); 16245 if (getInstallLocation() == loc) { 16246 return true; 16247 } 16248 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16249 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16250 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16251 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16252 return true; 16253 } 16254 return false; 16255 } 16256 16257 @Override 16258 public int getInstallLocation() { 16259 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16260 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16261 PackageHelper.APP_INSTALL_AUTO); 16262 } 16263 16264 /** Called by UserManagerService */ 16265 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16266 mDirtyUsers.remove(userHandle); 16267 mSettings.removeUserLPw(userHandle); 16268 mPendingBroadcasts.remove(userHandle); 16269 if (mInstaller != null) { 16270 // Technically, we shouldn't be doing this with the package lock 16271 // held. However, this is very rare, and there is already so much 16272 // other disk I/O going on, that we'll let it slide for now. 16273 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16274 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16275 final String volumeUuid = vol.getFsUuid(); 16276 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16277 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16278 } 16279 } 16280 mUserNeedsBadging.delete(userHandle); 16281 removeUnusedPackagesLILPw(userManager, userHandle); 16282 } 16283 16284 /** 16285 * We're removing userHandle and would like to remove any downloaded packages 16286 * that are no longer in use by any other user. 16287 * @param userHandle the user being removed 16288 */ 16289 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16290 final boolean DEBUG_CLEAN_APKS = false; 16291 int [] users = userManager.getUserIdsLPr(); 16292 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16293 while (psit.hasNext()) { 16294 PackageSetting ps = psit.next(); 16295 if (ps.pkg == null) { 16296 continue; 16297 } 16298 final String packageName = ps.pkg.packageName; 16299 // Skip over if system app 16300 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16301 continue; 16302 } 16303 if (DEBUG_CLEAN_APKS) { 16304 Slog.i(TAG, "Checking package " + packageName); 16305 } 16306 boolean keep = false; 16307 for (int i = 0; i < users.length; i++) { 16308 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16309 keep = true; 16310 if (DEBUG_CLEAN_APKS) { 16311 Slog.i(TAG, " Keeping package " + packageName + " for user " 16312 + users[i]); 16313 } 16314 break; 16315 } 16316 } 16317 if (!keep) { 16318 if (DEBUG_CLEAN_APKS) { 16319 Slog.i(TAG, " Removing package " + packageName); 16320 } 16321 mHandler.post(new Runnable() { 16322 public void run() { 16323 deletePackageX(packageName, userHandle, 0); 16324 } //end run 16325 }); 16326 } 16327 } 16328 } 16329 16330 /** Called by UserManagerService */ 16331 void createNewUserLILPw(int userHandle) { 16332 if (mInstaller != null) { 16333 mInstaller.createUserConfig(userHandle); 16334 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16335 applyFactoryDefaultBrowserLPw(userHandle); 16336 primeDomainVerificationsLPw(userHandle); 16337 } 16338 } 16339 16340 void newUserCreated(final int userHandle) { 16341 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16342 } 16343 16344 @Override 16345 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16346 mContext.enforceCallingOrSelfPermission( 16347 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16348 "Only package verification agents can read the verifier device identity"); 16349 16350 synchronized (mPackages) { 16351 return mSettings.getVerifierDeviceIdentityLPw(); 16352 } 16353 } 16354 16355 @Override 16356 public void setPermissionEnforced(String permission, boolean enforced) { 16357 // TODO: Now that we no longer change GID for storage, this should to away. 16358 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16359 "setPermissionEnforced"); 16360 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16361 synchronized (mPackages) { 16362 if (mSettings.mReadExternalStorageEnforced == null 16363 || mSettings.mReadExternalStorageEnforced != enforced) { 16364 mSettings.mReadExternalStorageEnforced = enforced; 16365 mSettings.writeLPr(); 16366 } 16367 } 16368 // kill any non-foreground processes so we restart them and 16369 // grant/revoke the GID. 16370 final IActivityManager am = ActivityManagerNative.getDefault(); 16371 if (am != null) { 16372 final long token = Binder.clearCallingIdentity(); 16373 try { 16374 am.killProcessesBelowForeground("setPermissionEnforcement"); 16375 } catch (RemoteException e) { 16376 } finally { 16377 Binder.restoreCallingIdentity(token); 16378 } 16379 } 16380 } else { 16381 throw new IllegalArgumentException("No selective enforcement for " + permission); 16382 } 16383 } 16384 16385 @Override 16386 @Deprecated 16387 public boolean isPermissionEnforced(String permission) { 16388 return true; 16389 } 16390 16391 @Override 16392 public boolean isStorageLow() { 16393 final long token = Binder.clearCallingIdentity(); 16394 try { 16395 final DeviceStorageMonitorInternal 16396 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16397 if (dsm != null) { 16398 return dsm.isMemoryLow(); 16399 } else { 16400 return false; 16401 } 16402 } finally { 16403 Binder.restoreCallingIdentity(token); 16404 } 16405 } 16406 16407 @Override 16408 public IPackageInstaller getPackageInstaller() { 16409 return mInstallerService; 16410 } 16411 16412 private boolean userNeedsBadging(int userId) { 16413 int index = mUserNeedsBadging.indexOfKey(userId); 16414 if (index < 0) { 16415 final UserInfo userInfo; 16416 final long token = Binder.clearCallingIdentity(); 16417 try { 16418 userInfo = sUserManager.getUserInfo(userId); 16419 } finally { 16420 Binder.restoreCallingIdentity(token); 16421 } 16422 final boolean b; 16423 if (userInfo != null && userInfo.isManagedProfile()) { 16424 b = true; 16425 } else { 16426 b = false; 16427 } 16428 mUserNeedsBadging.put(userId, b); 16429 return b; 16430 } 16431 return mUserNeedsBadging.valueAt(index); 16432 } 16433 16434 @Override 16435 public KeySet getKeySetByAlias(String packageName, String alias) { 16436 if (packageName == null || alias == null) { 16437 return null; 16438 } 16439 synchronized(mPackages) { 16440 final PackageParser.Package pkg = mPackages.get(packageName); 16441 if (pkg == null) { 16442 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16443 throw new IllegalArgumentException("Unknown package: " + packageName); 16444 } 16445 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16446 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16447 } 16448 } 16449 16450 @Override 16451 public KeySet getSigningKeySet(String packageName) { 16452 if (packageName == null) { 16453 return null; 16454 } 16455 synchronized(mPackages) { 16456 final PackageParser.Package pkg = mPackages.get(packageName); 16457 if (pkg == null) { 16458 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16459 throw new IllegalArgumentException("Unknown package: " + packageName); 16460 } 16461 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16462 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16463 throw new SecurityException("May not access signing KeySet of other apps."); 16464 } 16465 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16466 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16467 } 16468 } 16469 16470 @Override 16471 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16472 if (packageName == null || ks == null) { 16473 return false; 16474 } 16475 synchronized(mPackages) { 16476 final PackageParser.Package pkg = mPackages.get(packageName); 16477 if (pkg == null) { 16478 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16479 throw new IllegalArgumentException("Unknown package: " + packageName); 16480 } 16481 IBinder ksh = ks.getToken(); 16482 if (ksh instanceof KeySetHandle) { 16483 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16484 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16485 } 16486 return false; 16487 } 16488 } 16489 16490 @Override 16491 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16492 if (packageName == null || ks == null) { 16493 return false; 16494 } 16495 synchronized(mPackages) { 16496 final PackageParser.Package pkg = mPackages.get(packageName); 16497 if (pkg == null) { 16498 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16499 throw new IllegalArgumentException("Unknown package: " + packageName); 16500 } 16501 IBinder ksh = ks.getToken(); 16502 if (ksh instanceof KeySetHandle) { 16503 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16504 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16505 } 16506 return false; 16507 } 16508 } 16509 16510 public void getUsageStatsIfNoPackageUsageInfo() { 16511 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16512 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16513 if (usm == null) { 16514 throw new IllegalStateException("UsageStatsManager must be initialized"); 16515 } 16516 long now = System.currentTimeMillis(); 16517 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16518 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16519 String packageName = entry.getKey(); 16520 PackageParser.Package pkg = mPackages.get(packageName); 16521 if (pkg == null) { 16522 continue; 16523 } 16524 UsageStats usage = entry.getValue(); 16525 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16526 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16527 } 16528 } 16529 } 16530 16531 /** 16532 * Check and throw if the given before/after packages would be considered a 16533 * downgrade. 16534 */ 16535 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16536 throws PackageManagerException { 16537 if (after.versionCode < before.mVersionCode) { 16538 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16539 "Update version code " + after.versionCode + " is older than current " 16540 + before.mVersionCode); 16541 } else if (after.versionCode == before.mVersionCode) { 16542 if (after.baseRevisionCode < before.baseRevisionCode) { 16543 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16544 "Update base revision code " + after.baseRevisionCode 16545 + " is older than current " + before.baseRevisionCode); 16546 } 16547 16548 if (!ArrayUtils.isEmpty(after.splitNames)) { 16549 for (int i = 0; i < after.splitNames.length; i++) { 16550 final String splitName = after.splitNames[i]; 16551 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16552 if (j != -1) { 16553 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16554 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16555 "Update split " + splitName + " revision code " 16556 + after.splitRevisionCodes[i] + " is older than current " 16557 + before.splitRevisionCodes[j]); 16558 } 16559 } 16560 } 16561 } 16562 } 16563 } 16564 16565 private static class MoveCallbacks extends Handler { 16566 private static final int MSG_CREATED = 1; 16567 private static final int MSG_STATUS_CHANGED = 2; 16568 16569 private final RemoteCallbackList<IPackageMoveObserver> 16570 mCallbacks = new RemoteCallbackList<>(); 16571 16572 private final SparseIntArray mLastStatus = new SparseIntArray(); 16573 16574 public MoveCallbacks(Looper looper) { 16575 super(looper); 16576 } 16577 16578 public void register(IPackageMoveObserver callback) { 16579 mCallbacks.register(callback); 16580 } 16581 16582 public void unregister(IPackageMoveObserver callback) { 16583 mCallbacks.unregister(callback); 16584 } 16585 16586 @Override 16587 public void handleMessage(Message msg) { 16588 final SomeArgs args = (SomeArgs) msg.obj; 16589 final int n = mCallbacks.beginBroadcast(); 16590 for (int i = 0; i < n; i++) { 16591 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16592 try { 16593 invokeCallback(callback, msg.what, args); 16594 } catch (RemoteException ignored) { 16595 } 16596 } 16597 mCallbacks.finishBroadcast(); 16598 args.recycle(); 16599 } 16600 16601 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16602 throws RemoteException { 16603 switch (what) { 16604 case MSG_CREATED: { 16605 callback.onCreated(args.argi1, (Bundle) args.arg2); 16606 break; 16607 } 16608 case MSG_STATUS_CHANGED: { 16609 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16610 break; 16611 } 16612 } 16613 } 16614 16615 private void notifyCreated(int moveId, Bundle extras) { 16616 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16617 16618 final SomeArgs args = SomeArgs.obtain(); 16619 args.argi1 = moveId; 16620 args.arg2 = extras; 16621 obtainMessage(MSG_CREATED, args).sendToTarget(); 16622 } 16623 16624 private void notifyStatusChanged(int moveId, int status) { 16625 notifyStatusChanged(moveId, status, -1); 16626 } 16627 16628 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16629 Slog.v(TAG, "Move " + moveId + " status " + status); 16630 16631 final SomeArgs args = SomeArgs.obtain(); 16632 args.argi1 = moveId; 16633 args.argi2 = status; 16634 args.arg3 = estMillis; 16635 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16636 16637 synchronized (mLastStatus) { 16638 mLastStatus.put(moveId, status); 16639 } 16640 } 16641 } 16642 16643 private final class OnPermissionChangeListeners extends Handler { 16644 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16645 16646 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16647 new RemoteCallbackList<>(); 16648 16649 public OnPermissionChangeListeners(Looper looper) { 16650 super(looper); 16651 } 16652 16653 @Override 16654 public void handleMessage(Message msg) { 16655 switch (msg.what) { 16656 case MSG_ON_PERMISSIONS_CHANGED: { 16657 final int uid = msg.arg1; 16658 handleOnPermissionsChanged(uid); 16659 } break; 16660 } 16661 } 16662 16663 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16664 mPermissionListeners.register(listener); 16665 16666 } 16667 16668 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16669 mPermissionListeners.unregister(listener); 16670 } 16671 16672 public void onPermissionsChanged(int uid) { 16673 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16674 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16675 } 16676 } 16677 16678 private void handleOnPermissionsChanged(int uid) { 16679 final int count = mPermissionListeners.beginBroadcast(); 16680 try { 16681 for (int i = 0; i < count; i++) { 16682 IOnPermissionsChangeListener callback = mPermissionListeners 16683 .getBroadcastItem(i); 16684 try { 16685 callback.onPermissionsChanged(uid); 16686 } catch (RemoteException e) { 16687 Log.e(TAG, "Permission listener is dead", e); 16688 } 16689 } 16690 } finally { 16691 mPermissionListeners.finishBroadcast(); 16692 } 16693 } 16694 } 16695 16696 private class PackageManagerInternalImpl extends PackageManagerInternal { 16697 @Override 16698 public void setLocationPackagesProvider(PackagesProvider provider) { 16699 synchronized (mPackages) { 16700 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16701 } 16702 } 16703 16704 @Override 16705 public void setImePackagesProvider(PackagesProvider provider) { 16706 synchronized (mPackages) { 16707 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16708 } 16709 } 16710 16711 @Override 16712 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16713 synchronized (mPackages) { 16714 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16715 } 16716 } 16717 16718 @Override 16719 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16720 synchronized (mPackages) { 16721 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16722 } 16723 } 16724 16725 @Override 16726 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16727 synchronized (mPackages) { 16728 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16729 } 16730 } 16731 16732 @Override 16733 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16734 synchronized (mPackages) { 16735 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16736 } 16737 } 16738 16739 @Override 16740 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16741 synchronized (mPackages) { 16742 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16743 } 16744 } 16745 16746 @Override 16747 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16748 synchronized (mPackages) { 16749 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16750 packageName, userId); 16751 } 16752 } 16753 16754 @Override 16755 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16756 synchronized (mPackages) { 16757 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16758 packageName, userId); 16759 } 16760 } 16761 @Override 16762 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16763 synchronized (mPackages) { 16764 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16765 packageName, userId); 16766 } 16767 } 16768 } 16769 16770 @Override 16771 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16772 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16773 synchronized (mPackages) { 16774 final long identity = Binder.clearCallingIdentity(); 16775 try { 16776 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16777 packageNames, userId); 16778 } finally { 16779 Binder.restoreCallingIdentity(identity); 16780 } 16781 } 16782 } 16783 16784 private static void enforceSystemOrPhoneCaller(String tag) { 16785 int callingUid = Binder.getCallingUid(); 16786 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16787 throw new SecurityException( 16788 "Cannot call " + tag + " from UID " + callingUid); 16789 } 16790 } 16791} 16792