PackageManagerService.java revision 2699f065558ba78066887210b0c7346105959860
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_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 64import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 65import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 66import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 67import static android.content.pm.PackageManager.PERMISSION_DENIED; 68import static android.content.pm.PackageManager.PERMISSION_GRANTED; 69import static android.content.pm.PackageParser.isApkFile; 70import static android.os.Process.PACKAGE_INFO_GID; 71import static android.os.Process.SYSTEM_UID; 72import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 73import static android.system.OsConstants.O_CREAT; 74import static android.system.OsConstants.O_RDWR; 75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 79import static com.android.internal.util.ArrayUtils.appendInt; 80import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 89 90import android.Manifest; 91import android.app.ActivityManager; 92import android.app.ActivityManagerNative; 93import android.app.AppGlobals; 94import android.app.IActivityManager; 95import android.app.admin.IDevicePolicyManager; 96import android.app.backup.IBackupManager; 97import android.app.usage.UsageStats; 98import android.app.usage.UsageStatsManager; 99import android.content.BroadcastReceiver; 100import android.content.ComponentName; 101import android.content.Context; 102import android.content.IIntentReceiver; 103import android.content.Intent; 104import android.content.IntentFilter; 105import android.content.IntentSender; 106import android.content.IntentSender.SendIntentException; 107import android.content.ServiceConnection; 108import android.content.pm.ActivityInfo; 109import android.content.pm.ApplicationInfo; 110import android.content.pm.AppsQueryHelper; 111import android.content.pm.FeatureInfo; 112import android.content.pm.IOnPermissionsChangeListener; 113import android.content.pm.IPackageDataObserver; 114import android.content.pm.IPackageDeleteObserver; 115import android.content.pm.IPackageDeleteObserver2; 116import android.content.pm.IPackageInstallObserver2; 117import android.content.pm.IPackageInstaller; 118import android.content.pm.IPackageManager; 119import android.content.pm.IPackageMoveObserver; 120import android.content.pm.IPackageStatsObserver; 121import android.content.pm.InstrumentationInfo; 122import android.content.pm.IntentFilterVerificationInfo; 123import android.content.pm.KeySet; 124import android.content.pm.ManifestDigest; 125import android.content.pm.PackageCleanItem; 126import android.content.pm.PackageInfo; 127import android.content.pm.PackageInfoLite; 128import android.content.pm.PackageInstaller; 129import android.content.pm.PackageManager; 130import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 131import android.content.pm.PackageManagerInternal; 132import android.content.pm.PackageParser; 133import android.content.pm.PackageParser.ActivityIntentInfo; 134import android.content.pm.PackageParser.PackageLite; 135import android.content.pm.PackageParser.PackageParserException; 136import android.content.pm.PackageStats; 137import android.content.pm.PackageUserState; 138import android.content.pm.ParceledListSlice; 139import android.content.pm.PermissionGroupInfo; 140import android.content.pm.PermissionInfo; 141import android.content.pm.ProviderInfo; 142import android.content.pm.ResolveInfo; 143import android.content.pm.ServiceInfo; 144import android.content.pm.Signature; 145import android.content.pm.UserInfo; 146import android.content.pm.VerificationParams; 147import android.content.pm.VerifierDeviceIdentity; 148import android.content.pm.VerifierInfo; 149import android.content.res.Resources; 150import android.hardware.display.DisplayManager; 151import android.net.Uri; 152import android.os.Debug; 153import android.os.Binder; 154import android.os.Build; 155import android.os.Bundle; 156import android.os.Environment; 157import android.os.Environment.UserEnvironment; 158import android.os.FileUtils; 159import android.os.Handler; 160import android.os.IBinder; 161import android.os.Looper; 162import android.os.Message; 163import android.os.Parcel; 164import android.os.ParcelFileDescriptor; 165import android.os.Process; 166import android.os.RemoteCallbackList; 167import android.os.RemoteException; 168import android.os.ResultReceiver; 169import android.os.SELinux; 170import android.os.ServiceManager; 171import android.os.SystemClock; 172import android.os.SystemProperties; 173import android.os.Trace; 174import android.os.UserHandle; 175import android.os.UserManager; 176import android.os.storage.IMountService; 177import android.os.storage.MountServiceInternal; 178import android.os.storage.StorageEventListener; 179import android.os.storage.StorageManager; 180import android.os.storage.VolumeInfo; 181import android.os.storage.VolumeRecord; 182import android.security.KeyStore; 183import android.security.SystemKeyStore; 184import android.system.ErrnoException; 185import android.system.Os; 186import android.system.StructStat; 187import android.text.TextUtils; 188import android.text.format.DateUtils; 189import android.util.ArrayMap; 190import android.util.ArraySet; 191import android.util.AtomicFile; 192import android.util.DisplayMetrics; 193import android.util.EventLog; 194import android.util.ExceptionUtils; 195import android.util.Log; 196import android.util.LogPrinter; 197import android.util.MathUtils; 198import android.util.PrintStreamPrinter; 199import android.util.Slog; 200import android.util.SparseArray; 201import android.util.SparseBooleanArray; 202import android.util.SparseIntArray; 203import android.util.Xml; 204import android.view.Display; 205 206import dalvik.system.DexFile; 207import dalvik.system.VMRuntime; 208 209import libcore.io.IoUtils; 210import libcore.util.EmptyArray; 211 212import com.android.internal.R; 213import com.android.internal.annotations.GuardedBy; 214import com.android.internal.app.EphemeralResolveInfo; 215import com.android.internal.app.IMediaContainerService; 216import com.android.internal.app.ResolverActivity; 217import com.android.internal.content.NativeLibraryHelper; 218import com.android.internal.content.PackageHelper; 219import com.android.internal.os.IParcelFileDescriptorFactory; 220import com.android.internal.os.SomeArgs; 221import com.android.internal.os.Zygote; 222import com.android.internal.util.ArrayUtils; 223import com.android.internal.util.FastPrintWriter; 224import com.android.internal.util.FastXmlSerializer; 225import com.android.internal.util.IndentingPrintWriter; 226import com.android.internal.util.Preconditions; 227import com.android.server.EventLogTags; 228import com.android.server.FgThread; 229import com.android.server.IntentResolver; 230import com.android.server.LocalServices; 231import com.android.server.ServiceThread; 232import com.android.server.SystemConfig; 233import com.android.server.Watchdog; 234import com.android.server.pm.PermissionsState.PermissionState; 235import com.android.server.pm.Settings.DatabaseVersion; 236import com.android.server.pm.Settings.VersionInfo; 237import com.android.server.storage.DeviceStorageMonitorInternal; 238 239import org.xmlpull.v1.XmlPullParser; 240import org.xmlpull.v1.XmlPullParserException; 241import org.xmlpull.v1.XmlSerializer; 242 243import java.io.BufferedInputStream; 244import java.io.BufferedOutputStream; 245import java.io.BufferedReader; 246import java.io.ByteArrayInputStream; 247import java.io.ByteArrayOutputStream; 248import java.io.File; 249import java.io.FileDescriptor; 250import java.io.FileNotFoundException; 251import java.io.FileOutputStream; 252import java.io.FileReader; 253import java.io.FilenameFilter; 254import java.io.IOException; 255import java.io.InputStream; 256import java.io.PrintWriter; 257import java.nio.charset.StandardCharsets; 258import java.security.MessageDigest; 259import java.security.NoSuchAlgorithmException; 260import java.security.PublicKey; 261import java.security.cert.CertificateEncodingException; 262import java.security.cert.CertificateException; 263import java.text.SimpleDateFormat; 264import java.util.ArrayList; 265import java.util.Arrays; 266import java.util.Collection; 267import java.util.Collections; 268import java.util.Comparator; 269import java.util.Date; 270import java.util.Iterator; 271import java.util.List; 272import java.util.Map; 273import java.util.Objects; 274import java.util.Set; 275import java.util.concurrent.CountDownLatch; 276import java.util.concurrent.TimeUnit; 277import java.util.concurrent.atomic.AtomicBoolean; 278import java.util.concurrent.atomic.AtomicInteger; 279import java.util.concurrent.atomic.AtomicLong; 280 281/** 282 * Keep track of all those .apks everywhere. 283 * 284 * This is very central to the platform's security; please run the unit 285 * tests whenever making modifications here: 286 * 287runtest -c android.content.pm.PackageManagerTests frameworks-core 288 * 289 * {@hide} 290 */ 291public class PackageManagerService extends IPackageManager.Stub { 292 static final String TAG = "PackageManager"; 293 static final boolean DEBUG_SETTINGS = false; 294 static final boolean DEBUG_PREFERRED = false; 295 static final boolean DEBUG_UPGRADE = false; 296 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 297 private static final boolean DEBUG_BACKUP = false; 298 private static final boolean DEBUG_INSTALL = false; 299 private static final boolean DEBUG_REMOVE = false; 300 private static final boolean DEBUG_BROADCASTS = false; 301 private static final boolean DEBUG_SHOW_INFO = false; 302 private static final boolean DEBUG_PACKAGE_INFO = false; 303 private static final boolean DEBUG_INTENT_MATCHING = false; 304 private static final boolean DEBUG_PACKAGE_SCANNING = false; 305 private static final boolean DEBUG_VERIFY = false; 306 private static final boolean DEBUG_DEXOPT = false; 307 private static final boolean DEBUG_ABI_SELECTION = false; 308 private static final boolean DEBUG_EPHEMERAL = false; 309 310 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 311 312 private static final int RADIO_UID = Process.PHONE_UID; 313 private static final int LOG_UID = Process.LOG_UID; 314 private static final int NFC_UID = Process.NFC_UID; 315 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 316 private static final int SHELL_UID = Process.SHELL_UID; 317 318 // Cap the size of permission trees that 3rd party apps can define 319 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 320 321 // Suffix used during package installation when copying/moving 322 // package apks to install directory. 323 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 324 325 static final int SCAN_NO_DEX = 1<<1; 326 static final int SCAN_FORCE_DEX = 1<<2; 327 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 328 static final int SCAN_NEW_INSTALL = 1<<4; 329 static final int SCAN_NO_PATHS = 1<<5; 330 static final int SCAN_UPDATE_TIME = 1<<6; 331 static final int SCAN_DEFER_DEX = 1<<7; 332 static final int SCAN_BOOTING = 1<<8; 333 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 334 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 335 static final int SCAN_REPLACING = 1<<11; 336 static final int SCAN_REQUIRE_KNOWN = 1<<12; 337 static final int SCAN_MOVE = 1<<13; 338 static final int SCAN_INITIAL = 1<<14; 339 340 static final int REMOVE_CHATTY = 1<<16; 341 342 private static final int[] EMPTY_INT_ARRAY = new int[0]; 343 344 /** 345 * Timeout (in milliseconds) after which the watchdog should declare that 346 * our handler thread is wedged. The usual default for such things is one 347 * minute but we sometimes do very lengthy I/O operations on this thread, 348 * such as installing multi-gigabyte applications, so ours needs to be longer. 349 */ 350 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 351 352 /** 353 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 354 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 355 * settings entry if available, otherwise we use the hardcoded default. If it's been 356 * more than this long since the last fstrim, we force one during the boot sequence. 357 * 358 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 359 * one gets run at the next available charging+idle time. This final mandatory 360 * no-fstrim check kicks in only of the other scheduling criteria is never met. 361 */ 362 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 363 364 /** 365 * Whether verification is enabled by default. 366 */ 367 private static final boolean DEFAULT_VERIFY_ENABLE = true; 368 369 /** 370 * The default maximum time to wait for the verification agent to return in 371 * milliseconds. 372 */ 373 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 374 375 /** 376 * The default response for package verification timeout. 377 * 378 * This can be either PackageManager.VERIFICATION_ALLOW or 379 * PackageManager.VERIFICATION_REJECT. 380 */ 381 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 382 383 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 384 385 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 386 DEFAULT_CONTAINER_PACKAGE, 387 "com.android.defcontainer.DefaultContainerService"); 388 389 private static final String KILL_APP_REASON_GIDS_CHANGED = 390 "permission grant or revoke changed gids"; 391 392 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 393 "permissions revoked"; 394 395 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 396 397 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 398 399 /** Permission grant: not grant the permission. */ 400 private static final int GRANT_DENIED = 1; 401 402 /** Permission grant: grant the permission as an install permission. */ 403 private static final int GRANT_INSTALL = 2; 404 405 /** Permission grant: grant the permission as a runtime one. */ 406 private static final int GRANT_RUNTIME = 3; 407 408 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 409 private static final int GRANT_UPGRADE = 4; 410 411 /** Canonical intent used to identify what counts as a "web browser" app */ 412 private static final Intent sBrowserIntent; 413 static { 414 sBrowserIntent = new Intent(); 415 sBrowserIntent.setAction(Intent.ACTION_VIEW); 416 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 417 sBrowserIntent.setData(Uri.parse("http:")); 418 } 419 420 final ServiceThread mHandlerThread; 421 422 final PackageHandler mHandler; 423 424 /** 425 * Messages for {@link #mHandler} that need to wait for system ready before 426 * being dispatched. 427 */ 428 private ArrayList<Message> mPostSystemReadyMessages; 429 430 final int mSdkVersion = Build.VERSION.SDK_INT; 431 432 final Context mContext; 433 final boolean mFactoryTest; 434 final boolean mOnlyCore; 435 final DisplayMetrics mMetrics; 436 final int mDefParseFlags; 437 final String[] mSeparateProcesses; 438 final boolean mIsUpgrade; 439 440 // This is where all application persistent data goes. 441 final File mAppDataDir; 442 443 // This is where all application persistent data goes for secondary users. 444 final File mUserAppDataDir; 445 446 /** The location for ASEC container files on internal storage. */ 447 final String mAsecInternalPath; 448 449 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 450 // LOCK HELD. Can be called with mInstallLock held. 451 @GuardedBy("mInstallLock") 452 final Installer mInstaller; 453 454 /** Directory where installed third-party apps stored */ 455 final File mAppInstallDir; 456 final File mEphemeralInstallDir; 457 458 /** 459 * Directory to which applications installed internally have their 460 * 32 bit native libraries copied. 461 */ 462 private File mAppLib32InstallDir; 463 464 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 465 // apps. 466 final File mDrmAppPrivateInstallDir; 467 468 // ---------------------------------------------------------------- 469 470 // Lock for state used when installing and doing other long running 471 // operations. Methods that must be called with this lock held have 472 // the suffix "LI". 473 final Object mInstallLock = new Object(); 474 475 // ---------------------------------------------------------------- 476 477 // Keys are String (package name), values are Package. This also serves 478 // as the lock for the global state. Methods that must be called with 479 // this lock held have the prefix "LP". 480 @GuardedBy("mPackages") 481 final ArrayMap<String, PackageParser.Package> mPackages = 482 new ArrayMap<String, PackageParser.Package>(); 483 484 // Tracks available target package names -> overlay package paths. 485 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 486 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 487 488 /** 489 * Tracks new system packages [received in an OTA] that we expect to 490 * find updated user-installed versions. Keys are package name, values 491 * are package location. 492 */ 493 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 494 495 /** 496 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 497 */ 498 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 499 /** 500 * Whether or not system app permissions should be promoted from install to runtime. 501 */ 502 boolean mPromoteSystemApps; 503 504 final Settings mSettings; 505 boolean mRestoredSettings; 506 507 // System configuration read by SystemConfig. 508 final int[] mGlobalGids; 509 final SparseArray<ArraySet<String>> mSystemPermissions; 510 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 511 512 // If mac_permissions.xml was found for seinfo labeling. 513 boolean mFoundPolicyFile; 514 515 // If a recursive restorecon of /data/data/<pkg> is needed. 516 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 517 518 public static final class SharedLibraryEntry { 519 public final String path; 520 public final String apk; 521 522 SharedLibraryEntry(String _path, String _apk) { 523 path = _path; 524 apk = _apk; 525 } 526 } 527 528 // Currently known shared libraries. 529 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 530 new ArrayMap<String, SharedLibraryEntry>(); 531 532 // All available activities, for your resolving pleasure. 533 final ActivityIntentResolver mActivities = 534 new ActivityIntentResolver(); 535 536 // All available receivers, for your resolving pleasure. 537 final ActivityIntentResolver mReceivers = 538 new ActivityIntentResolver(); 539 540 // All available services, for your resolving pleasure. 541 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 542 543 // All available providers, for your resolving pleasure. 544 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 545 546 // Mapping from provider base names (first directory in content URI codePath) 547 // to the provider information. 548 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 549 new ArrayMap<String, PackageParser.Provider>(); 550 551 // Mapping from instrumentation class names to info about them. 552 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 553 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 554 555 // Mapping from permission names to info about them. 556 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 557 new ArrayMap<String, PackageParser.PermissionGroup>(); 558 559 // Packages whose data we have transfered into another package, thus 560 // should no longer exist. 561 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 562 563 // Broadcast actions that are only available to the system. 564 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 565 566 /** List of packages waiting for verification. */ 567 final SparseArray<PackageVerificationState> mPendingVerification 568 = new SparseArray<PackageVerificationState>(); 569 570 /** Set of packages associated with each app op permission. */ 571 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 572 573 final PackageInstallerService mInstallerService; 574 575 private final PackageDexOptimizer mPackageDexOptimizer; 576 577 private AtomicInteger mNextMoveId = new AtomicInteger(); 578 private final MoveCallbacks mMoveCallbacks; 579 580 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 581 582 // Cache of users who need badging. 583 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 584 585 /** Token for keys in mPendingVerification. */ 586 private int mPendingVerificationToken = 0; 587 588 volatile boolean mSystemReady; 589 volatile boolean mSafeMode; 590 volatile boolean mHasSystemUidErrors; 591 592 ApplicationInfo mAndroidApplication; 593 final ActivityInfo mResolveActivity = new ActivityInfo(); 594 final ResolveInfo mResolveInfo = new ResolveInfo(); 595 ComponentName mResolveComponentName; 596 PackageParser.Package mPlatformPackage; 597 ComponentName mCustomResolverComponentName; 598 599 boolean mResolverReplaced = false; 600 601 private final ComponentName mIntentFilterVerifierComponent; 602 private int mIntentFilterVerificationToken = 0; 603 604 /** Component that knows whether or not an ephemeral application exists */ 605 final ComponentName mEphemeralResolverComponent; 606 /** The service connection to the ephemeral resolver */ 607 final EphemeralResolverConnection mEphemeralResolverConnection; 608 609 /** Component used to install ephemeral applications */ 610 final ComponentName mEphemeralInstallerComponent; 611 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 612 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 613 614 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 615 = new SparseArray<IntentFilterVerificationState>(); 616 617 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 618 new DefaultPermissionGrantPolicy(this); 619 620 // List of packages names to keep cached, even if they are uninstalled for all users 621 private List<String> mKeepUninstalledPackages; 622 623 private static class IFVerificationParams { 624 PackageParser.Package pkg; 625 boolean replacing; 626 int userId; 627 int verifierUid; 628 629 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 630 int _userId, int _verifierUid) { 631 pkg = _pkg; 632 replacing = _replacing; 633 userId = _userId; 634 replacing = _replacing; 635 verifierUid = _verifierUid; 636 } 637 } 638 639 private interface IntentFilterVerifier<T extends IntentFilter> { 640 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 641 T filter, String packageName); 642 void startVerifications(int userId); 643 void receiveVerificationResponse(int verificationId); 644 } 645 646 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 647 private Context mContext; 648 private ComponentName mIntentFilterVerifierComponent; 649 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 650 651 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 652 mContext = context; 653 mIntentFilterVerifierComponent = verifierComponent; 654 } 655 656 private String getDefaultScheme() { 657 return IntentFilter.SCHEME_HTTPS; 658 } 659 660 @Override 661 public void startVerifications(int userId) { 662 // Launch verifications requests 663 int count = mCurrentIntentFilterVerifications.size(); 664 for (int n=0; n<count; n++) { 665 int verificationId = mCurrentIntentFilterVerifications.get(n); 666 final IntentFilterVerificationState ivs = 667 mIntentFilterVerificationStates.get(verificationId); 668 669 String packageName = ivs.getPackageName(); 670 671 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 672 final int filterCount = filters.size(); 673 ArraySet<String> domainsSet = new ArraySet<>(); 674 for (int m=0; m<filterCount; m++) { 675 PackageParser.ActivityIntentInfo filter = filters.get(m); 676 domainsSet.addAll(filter.getHostsList()); 677 } 678 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 679 synchronized (mPackages) { 680 if (mSettings.createIntentFilterVerificationIfNeededLPw( 681 packageName, domainsList) != null) { 682 scheduleWriteSettingsLocked(); 683 } 684 } 685 sendVerificationRequest(userId, verificationId, ivs); 686 } 687 mCurrentIntentFilterVerifications.clear(); 688 } 689 690 private void sendVerificationRequest(int userId, int verificationId, 691 IntentFilterVerificationState ivs) { 692 693 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 694 verificationIntent.putExtra( 695 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 696 verificationId); 697 verificationIntent.putExtra( 698 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 699 getDefaultScheme()); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 702 ivs.getHostsString()); 703 verificationIntent.putExtra( 704 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 705 ivs.getPackageName()); 706 verificationIntent.setComponent(mIntentFilterVerifierComponent); 707 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 708 709 UserHandle user = new UserHandle(userId); 710 mContext.sendBroadcastAsUser(verificationIntent, user); 711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 712 "Sending IntentFilter verification broadcast"); 713 } 714 715 public void receiveVerificationResponse(int verificationId) { 716 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 717 718 final boolean verified = ivs.isVerified(); 719 720 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 721 final int count = filters.size(); 722 if (DEBUG_DOMAIN_VERIFICATION) { 723 Slog.i(TAG, "Received verification response " + verificationId 724 + " for " + count + " filters, verified=" + verified); 725 } 726 for (int n=0; n<count; n++) { 727 PackageParser.ActivityIntentInfo filter = filters.get(n); 728 filter.setVerified(verified); 729 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 731 + " verified with result:" + verified + " and hosts:" 732 + ivs.getHostsString()); 733 } 734 735 mIntentFilterVerificationStates.remove(verificationId); 736 737 final String packageName = ivs.getPackageName(); 738 IntentFilterVerificationInfo ivi = null; 739 740 synchronized (mPackages) { 741 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 742 } 743 if (ivi == null) { 744 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 745 + verificationId + " packageName:" + packageName); 746 return; 747 } 748 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 749 "Updating IntentFilterVerificationInfo for package " + packageName 750 +" verificationId:" + verificationId); 751 752 synchronized (mPackages) { 753 if (verified) { 754 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 755 } else { 756 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 757 } 758 scheduleWriteSettingsLocked(); 759 760 final int userId = ivs.getUserId(); 761 if (userId != UserHandle.USER_ALL) { 762 final int userStatus = 763 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 764 765 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 766 boolean needUpdate = false; 767 768 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 769 // already been set by the User thru the Disambiguation dialog 770 switch (userStatus) { 771 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 772 if (verified) { 773 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 774 } else { 775 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 776 } 777 needUpdate = true; 778 break; 779 780 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 781 if (verified) { 782 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 783 needUpdate = true; 784 } 785 break; 786 787 default: 788 // Nothing to do 789 } 790 791 if (needUpdate) { 792 mSettings.updateIntentFilterVerificationStatusLPw( 793 packageName, updatedStatus, userId); 794 scheduleWritePackageRestrictionsLocked(userId); 795 } 796 } 797 } 798 } 799 800 @Override 801 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 802 ActivityIntentInfo filter, String packageName) { 803 if (!hasValidDomains(filter)) { 804 return false; 805 } 806 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 807 if (ivs == null) { 808 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 809 packageName); 810 } 811 if (DEBUG_DOMAIN_VERIFICATION) { 812 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 813 } 814 ivs.addFilter(filter); 815 return true; 816 } 817 818 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 819 int userId, int verificationId, String packageName) { 820 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 821 verifierUid, userId, packageName); 822 ivs.setPendingState(); 823 synchronized (mPackages) { 824 mIntentFilterVerificationStates.append(verificationId, ivs); 825 mCurrentIntentFilterVerifications.add(verificationId); 826 } 827 return ivs; 828 } 829 } 830 831 private static boolean hasValidDomains(ActivityIntentInfo filter) { 832 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 833 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 834 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 835 } 836 837 private IntentFilterVerifier mIntentFilterVerifier; 838 839 // Set of pending broadcasts for aggregating enable/disable of components. 840 static class PendingPackageBroadcasts { 841 // for each user id, a map of <package name -> components within that package> 842 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 843 844 public PendingPackageBroadcasts() { 845 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 846 } 847 848 public ArrayList<String> get(int userId, String packageName) { 849 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 850 return packages.get(packageName); 851 } 852 853 public void put(int userId, String packageName, ArrayList<String> components) { 854 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 855 packages.put(packageName, components); 856 } 857 858 public void remove(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 860 if (packages != null) { 861 packages.remove(packageName); 862 } 863 } 864 865 public void remove(int userId) { 866 mUidMap.remove(userId); 867 } 868 869 public int userIdCount() { 870 return mUidMap.size(); 871 } 872 873 public int userIdAt(int n) { 874 return mUidMap.keyAt(n); 875 } 876 877 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 878 return mUidMap.get(userId); 879 } 880 881 public int size() { 882 // total number of pending broadcast entries across all userIds 883 int num = 0; 884 for (int i = 0; i< mUidMap.size(); i++) { 885 num += mUidMap.valueAt(i).size(); 886 } 887 return num; 888 } 889 890 public void clear() { 891 mUidMap.clear(); 892 } 893 894 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 895 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 896 if (map == null) { 897 map = new ArrayMap<String, ArrayList<String>>(); 898 mUidMap.put(userId, map); 899 } 900 return map; 901 } 902 } 903 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 904 905 // Service Connection to remote media container service to copy 906 // package uri's from external media onto secure containers 907 // or internal storage. 908 private IMediaContainerService mContainerService = null; 909 910 static final int SEND_PENDING_BROADCAST = 1; 911 static final int MCS_BOUND = 3; 912 static final int END_COPY = 4; 913 static final int INIT_COPY = 5; 914 static final int MCS_UNBIND = 6; 915 static final int START_CLEANING_PACKAGE = 7; 916 static final int FIND_INSTALL_LOC = 8; 917 static final int POST_INSTALL = 9; 918 static final int MCS_RECONNECT = 10; 919 static final int MCS_GIVE_UP = 11; 920 static final int UPDATED_MEDIA_STATUS = 12; 921 static final int WRITE_SETTINGS = 13; 922 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 923 static final int PACKAGE_VERIFIED = 15; 924 static final int CHECK_PENDING_VERIFICATION = 16; 925 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 926 static final int INTENT_FILTER_VERIFIED = 18; 927 928 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 929 930 // Delay time in millisecs 931 static final int BROADCAST_DELAY = 10 * 1000; 932 933 static UserManagerService sUserManager; 934 935 // Stores a list of users whose package restrictions file needs to be updated 936 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 937 938 final private DefaultContainerConnection mDefContainerConn = 939 new DefaultContainerConnection(); 940 class DefaultContainerConnection implements ServiceConnection { 941 public void onServiceConnected(ComponentName name, IBinder service) { 942 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 943 IMediaContainerService imcs = 944 IMediaContainerService.Stub.asInterface(service); 945 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 946 } 947 948 public void onServiceDisconnected(ComponentName name) { 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 950 } 951 } 952 953 // Recordkeeping of restore-after-install operations that are currently in flight 954 // between the Package Manager and the Backup Manager 955 class PostInstallData { 956 public InstallArgs args; 957 public PackageInstalledInfo res; 958 959 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 960 args = _a; 961 res = _r; 962 } 963 } 964 965 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 966 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 967 968 // XML tags for backup/restore of various bits of state 969 private static final String TAG_PREFERRED_BACKUP = "pa"; 970 private static final String TAG_DEFAULT_APPS = "da"; 971 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 972 973 final String mRequiredVerifierPackage; 974 final String mRequiredInstallerPackage; 975 976 private final PackageUsage mPackageUsage = new PackageUsage(); 977 978 private class PackageUsage { 979 private static final int WRITE_INTERVAL 980 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 981 982 private final Object mFileLock = new Object(); 983 private final AtomicLong mLastWritten = new AtomicLong(0); 984 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 985 986 private boolean mIsHistoricalPackageUsageAvailable = true; 987 988 boolean isHistoricalPackageUsageAvailable() { 989 return mIsHistoricalPackageUsageAvailable; 990 } 991 992 void write(boolean force) { 993 if (force) { 994 writeInternal(); 995 return; 996 } 997 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 998 && !DEBUG_DEXOPT) { 999 return; 1000 } 1001 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1002 new Thread("PackageUsage_DiskWriter") { 1003 @Override 1004 public void run() { 1005 try { 1006 writeInternal(); 1007 } finally { 1008 mBackgroundWriteRunning.set(false); 1009 } 1010 } 1011 }.start(); 1012 } 1013 } 1014 1015 private void writeInternal() { 1016 synchronized (mPackages) { 1017 synchronized (mFileLock) { 1018 AtomicFile file = getFile(); 1019 FileOutputStream f = null; 1020 try { 1021 f = file.startWrite(); 1022 BufferedOutputStream out = new BufferedOutputStream(f); 1023 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1024 StringBuilder sb = new StringBuilder(); 1025 for (PackageParser.Package pkg : mPackages.values()) { 1026 if (pkg.mLastPackageUsageTimeInMills == 0) { 1027 continue; 1028 } 1029 sb.setLength(0); 1030 sb.append(pkg.packageName); 1031 sb.append(' '); 1032 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1033 sb.append('\n'); 1034 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1035 } 1036 out.flush(); 1037 file.finishWrite(f); 1038 } catch (IOException e) { 1039 if (f != null) { 1040 file.failWrite(f); 1041 } 1042 Log.e(TAG, "Failed to write package usage times", e); 1043 } 1044 } 1045 } 1046 mLastWritten.set(SystemClock.elapsedRealtime()); 1047 } 1048 1049 void readLP() { 1050 synchronized (mFileLock) { 1051 AtomicFile file = getFile(); 1052 BufferedInputStream in = null; 1053 try { 1054 in = new BufferedInputStream(file.openRead()); 1055 StringBuffer sb = new StringBuffer(); 1056 while (true) { 1057 String packageName = readToken(in, sb, ' '); 1058 if (packageName == null) { 1059 break; 1060 } 1061 String timeInMillisString = readToken(in, sb, '\n'); 1062 if (timeInMillisString == null) { 1063 throw new IOException("Failed to find last usage time for package " 1064 + packageName); 1065 } 1066 PackageParser.Package pkg = mPackages.get(packageName); 1067 if (pkg == null) { 1068 continue; 1069 } 1070 long timeInMillis; 1071 try { 1072 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1073 } catch (NumberFormatException e) { 1074 throw new IOException("Failed to parse " + timeInMillisString 1075 + " as a long.", e); 1076 } 1077 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1078 } 1079 } catch (FileNotFoundException expected) { 1080 mIsHistoricalPackageUsageAvailable = false; 1081 } catch (IOException e) { 1082 Log.w(TAG, "Failed to read package usage times", e); 1083 } finally { 1084 IoUtils.closeQuietly(in); 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1091 throws IOException { 1092 sb.setLength(0); 1093 while (true) { 1094 int ch = in.read(); 1095 if (ch == -1) { 1096 if (sb.length() == 0) { 1097 return null; 1098 } 1099 throw new IOException("Unexpected EOF"); 1100 } 1101 if (ch == endOfToken) { 1102 return sb.toString(); 1103 } 1104 sb.append((char)ch); 1105 } 1106 } 1107 1108 private AtomicFile getFile() { 1109 File dataDir = Environment.getDataDirectory(); 1110 File systemDir = new File(dataDir, "system"); 1111 File fname = new File(systemDir, "package-usage.list"); 1112 return new AtomicFile(fname); 1113 } 1114 } 1115 1116 class PackageHandler extends Handler { 1117 private boolean mBound = false; 1118 final ArrayList<HandlerParams> mPendingInstalls = 1119 new ArrayList<HandlerParams>(); 1120 1121 private boolean connectToService() { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1123 " DefaultContainerService"); 1124 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1126 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1127 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1129 mBound = true; 1130 return true; 1131 } 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 return false; 1134 } 1135 1136 private void disconnectService() { 1137 mContainerService = null; 1138 mBound = false; 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 mContext.unbindService(mDefContainerConn); 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } 1143 1144 PackageHandler(Looper looper) { 1145 super(looper); 1146 } 1147 1148 public void handleMessage(Message msg) { 1149 try { 1150 doHandleMessage(msg); 1151 } finally { 1152 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1153 } 1154 } 1155 1156 void doHandleMessage(Message msg) { 1157 switch (msg.what) { 1158 case INIT_COPY: { 1159 HandlerParams params = (HandlerParams) msg.obj; 1160 int idx = mPendingInstalls.size(); 1161 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1162 // If a bind was already initiated we dont really 1163 // need to do anything. The pending install 1164 // will be processed later on. 1165 if (!mBound) { 1166 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1167 System.identityHashCode(mHandler)); 1168 // If this is the only one pending we might 1169 // have to bind to the service again. 1170 if (!connectToService()) { 1171 Slog.e(TAG, "Failed to bind to media container service"); 1172 params.serviceError(); 1173 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1174 System.identityHashCode(mHandler)); 1175 if (params.traceMethod != null) { 1176 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1177 params.traceCookie); 1178 } 1179 return; 1180 } else { 1181 // Once we bind to the service, the first 1182 // pending request will be processed. 1183 mPendingInstalls.add(idx, params); 1184 } 1185 } else { 1186 mPendingInstalls.add(idx, params); 1187 // Already bound to the service. Just make 1188 // sure we trigger off processing the first request. 1189 if (idx == 0) { 1190 mHandler.sendEmptyMessage(MCS_BOUND); 1191 } 1192 } 1193 break; 1194 } 1195 case MCS_BOUND: { 1196 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1197 if (msg.obj != null) { 1198 mContainerService = (IMediaContainerService) msg.obj; 1199 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1200 System.identityHashCode(mHandler)); 1201 } 1202 if (mContainerService == null) { 1203 if (!mBound) { 1204 // Something seriously wrong since we are not bound and we are not 1205 // waiting for connection. Bail out. 1206 Slog.e(TAG, "Cannot bind to media container service"); 1207 for (HandlerParams params : mPendingInstalls) { 1208 // Indicate service bind error 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1214 params.traceMethod, params.traceCookie); 1215 } 1216 return; 1217 } 1218 mPendingInstalls.clear(); 1219 } else { 1220 Slog.w(TAG, "Waiting to connect to media container service"); 1221 } 1222 } else if (mPendingInstalls.size() > 0) { 1223 HandlerParams params = mPendingInstalls.get(0); 1224 if (params != null) { 1225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1226 System.identityHashCode(params)); 1227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1228 if (params.startCopy()) { 1229 // We are done... look for more work or to 1230 // go idle. 1231 if (DEBUG_SD_INSTALL) Log.i(TAG, 1232 "Checking for more work or unbind..."); 1233 // Delete pending install 1234 if (mPendingInstalls.size() > 0) { 1235 mPendingInstalls.remove(0); 1236 } 1237 if (mPendingInstalls.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_SD_INSTALL) Log.i(TAG, 1240 "Posting delayed MCS_UNBIND"); 1241 removeMessages(MCS_UNBIND); 1242 Message ubmsg = obtainMessage(MCS_UNBIND); 1243 // Unbind after a little delay, to avoid 1244 // continual thrashing. 1245 sendMessageDelayed(ubmsg, 10000); 1246 } 1247 } else { 1248 // There are more pending requests in queue. 1249 // Just post MCS_BOUND message to trigger processing 1250 // of next pending install. 1251 if (DEBUG_SD_INSTALL) Log.i(TAG, 1252 "Posting MCS_BOUND for next work"); 1253 mHandler.sendEmptyMessage(MCS_BOUND); 1254 } 1255 } 1256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1257 } 1258 } else { 1259 // Should never happen ideally. 1260 Slog.w(TAG, "Empty queue"); 1261 } 1262 break; 1263 } 1264 case MCS_RECONNECT: { 1265 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1266 if (mPendingInstalls.size() > 0) { 1267 if (mBound) { 1268 disconnectService(); 1269 } 1270 if (!connectToService()) { 1271 Slog.e(TAG, "Failed to bind to media container service"); 1272 for (HandlerParams params : mPendingInstalls) { 1273 // Indicate service bind error 1274 params.serviceError(); 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1276 System.identityHashCode(params)); 1277 } 1278 mPendingInstalls.clear(); 1279 } 1280 } 1281 break; 1282 } 1283 case MCS_UNBIND: { 1284 // If there is no actual work left, then time to unbind. 1285 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1286 1287 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1288 if (mBound) { 1289 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1290 1291 disconnectService(); 1292 } 1293 } else if (mPendingInstalls.size() > 0) { 1294 // There are more pending requests in queue. 1295 // Just post MCS_BOUND message to trigger processing 1296 // of next pending install. 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 1300 break; 1301 } 1302 case MCS_GIVE_UP: { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1304 HandlerParams params = mPendingInstalls.remove(0); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1306 System.identityHashCode(params)); 1307 break; 1308 } 1309 case SEND_PENDING_BROADCAST: { 1310 String packages[]; 1311 ArrayList<String> components[]; 1312 int size = 0; 1313 int uids[]; 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 synchronized (mPackages) { 1316 if (mPendingBroadcasts == null) { 1317 return; 1318 } 1319 size = mPendingBroadcasts.size(); 1320 if (size <= 0) { 1321 // Nothing to be done. Just return 1322 return; 1323 } 1324 packages = new String[size]; 1325 components = new ArrayList[size]; 1326 uids = new int[size]; 1327 int i = 0; // filling out the above arrays 1328 1329 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1330 int packageUserId = mPendingBroadcasts.userIdAt(n); 1331 Iterator<Map.Entry<String, ArrayList<String>>> it 1332 = mPendingBroadcasts.packagesForUserId(packageUserId) 1333 .entrySet().iterator(); 1334 while (it.hasNext() && i < size) { 1335 Map.Entry<String, ArrayList<String>> ent = it.next(); 1336 packages[i] = ent.getKey(); 1337 components[i] = ent.getValue(); 1338 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1339 uids[i] = (ps != null) 1340 ? UserHandle.getUid(packageUserId, ps.appId) 1341 : -1; 1342 i++; 1343 } 1344 } 1345 size = i; 1346 mPendingBroadcasts.clear(); 1347 } 1348 // Send broadcasts 1349 for (int i = 0; i < size; i++) { 1350 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1351 } 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 break; 1354 } 1355 case START_CLEANING_PACKAGE: { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 final String packageName = (String)msg.obj; 1358 final int userId = msg.arg1; 1359 final boolean andCode = msg.arg2 != 0; 1360 synchronized (mPackages) { 1361 if (userId == UserHandle.USER_ALL) { 1362 int[] users = sUserManager.getUserIds(); 1363 for (int user : users) { 1364 mSettings.addPackageToCleanLPw( 1365 new PackageCleanItem(user, packageName, andCode)); 1366 } 1367 } else { 1368 mSettings.addPackageToCleanLPw( 1369 new PackageCleanItem(userId, packageName, andCode)); 1370 } 1371 } 1372 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1373 startCleaningPackages(); 1374 } break; 1375 case POST_INSTALL: { 1376 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1377 1378 PostInstallData data = mRunningInstalls.get(msg.arg1); 1379 mRunningInstalls.delete(msg.arg1); 1380 boolean deleteOld = false; 1381 1382 if (data != null) { 1383 InstallArgs args = data.args; 1384 PackageInstalledInfo res = data.res; 1385 1386 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1387 final String packageName = res.pkg.applicationInfo.packageName; 1388 res.removedInfo.sendBroadcast(false, true, false); 1389 Bundle extras = new Bundle(1); 1390 extras.putInt(Intent.EXTRA_UID, res.uid); 1391 1392 // Now that we successfully installed the package, grant runtime 1393 // permissions if requested before broadcasting the install. 1394 if ((args.installFlags 1395 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1396 && res.pkg.applicationInfo.targetSdkVersion 1397 >= Build.VERSION_CODES.M) { 1398 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1399 args.installGrantPermissions); 1400 } 1401 1402 // Determine the set of users who are adding this 1403 // package for the first time vs. those who are seeing 1404 // an update. 1405 int[] firstUsers; 1406 int[] updateUsers = new int[0]; 1407 if (res.origUsers == null || res.origUsers.length == 0) { 1408 firstUsers = res.newUsers; 1409 } else { 1410 firstUsers = new int[0]; 1411 for (int i=0; i<res.newUsers.length; i++) { 1412 int user = res.newUsers[i]; 1413 boolean isNew = true; 1414 for (int j=0; j<res.origUsers.length; j++) { 1415 if (res.origUsers[j] == user) { 1416 isNew = false; 1417 break; 1418 } 1419 } 1420 if (isNew) { 1421 int[] newFirst = new int[firstUsers.length+1]; 1422 System.arraycopy(firstUsers, 0, newFirst, 0, 1423 firstUsers.length); 1424 newFirst[firstUsers.length] = user; 1425 firstUsers = newFirst; 1426 } else { 1427 int[] newUpdate = new int[updateUsers.length+1]; 1428 System.arraycopy(updateUsers, 0, newUpdate, 0, 1429 updateUsers.length); 1430 newUpdate[updateUsers.length] = user; 1431 updateUsers = newUpdate; 1432 } 1433 } 1434 } 1435 // don't broadcast for ephemeral installs/updates 1436 final boolean isEphemeral = isEphemeral(res.pkg); 1437 if (!isEphemeral) { 1438 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1439 extras, 0 /*flags*/, null /*targetPackage*/, 1440 null /*finishedReceiver*/, firstUsers); 1441 } 1442 final boolean update = res.removedInfo.removedPackage != null; 1443 if (update) { 1444 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1445 } 1446 if (!isEphemeral) { 1447 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1448 extras, 0 /*flags*/, null /*targetPackage*/, 1449 null /*finishedReceiver*/, updateUsers); 1450 } 1451 if (update) { 1452 if (!isEphemeral) { 1453 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1454 packageName, extras, 0 /*flags*/, 1455 null /*targetPackage*/, null /*finishedReceiver*/, 1456 updateUsers); 1457 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1458 null /*package*/, null /*extras*/, 0 /*flags*/, 1459 packageName /*targetPackage*/, 1460 null /*finishedReceiver*/, updateUsers); 1461 } 1462 1463 // treat asec-hosted packages like removable media on upgrade 1464 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1465 if (DEBUG_INSTALL) { 1466 Slog.i(TAG, "upgrading pkg " + res.pkg 1467 + " is ASEC-hosted -> AVAILABLE"); 1468 } 1469 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1470 ArrayList<String> pkgList = new ArrayList<String>(1); 1471 pkgList.add(packageName); 1472 sendResourcesChangedBroadcast(true, true, 1473 pkgList,uidArray, null); 1474 } 1475 } 1476 if (res.removedInfo.args != null) { 1477 // Remove the replaced package's older resources safely now 1478 deleteOld = true; 1479 } 1480 1481 // If this app is a browser and it's newly-installed for some 1482 // users, clear any default-browser state in those users 1483 if (firstUsers.length > 0) { 1484 // the app's nature doesn't depend on the user, so we can just 1485 // check its browser nature in any user and generalize. 1486 if (packageIsBrowser(packageName, firstUsers[0])) { 1487 synchronized (mPackages) { 1488 for (int userId : firstUsers) { 1489 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1490 } 1491 } 1492 } 1493 } 1494 // Log current value of "unknown sources" setting 1495 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1496 getUnknownSourcesSettings()); 1497 } 1498 // Force a gc to clear up things 1499 Runtime.getRuntime().gc(); 1500 // We delete after a gc for applications on sdcard. 1501 if (deleteOld) { 1502 synchronized (mInstallLock) { 1503 res.removedInfo.args.doPostDeleteLI(true); 1504 } 1505 } 1506 if (args.observer != null) { 1507 try { 1508 Bundle extras = extrasForInstallResult(res); 1509 args.observer.onPackageInstalled(res.name, res.returnCode, 1510 res.returnMsg, extras); 1511 } catch (RemoteException e) { 1512 Slog.i(TAG, "Observer no longer exists."); 1513 } 1514 } 1515 if (args.traceMethod != null) { 1516 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1517 args.traceCookie); 1518 } 1519 return; 1520 } else { 1521 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1522 } 1523 1524 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1525 } break; 1526 case UPDATED_MEDIA_STATUS: { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1528 boolean reportStatus = msg.arg1 == 1; 1529 boolean doGc = msg.arg2 == 1; 1530 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1531 if (doGc) { 1532 // Force a gc to clear up stale containers. 1533 Runtime.getRuntime().gc(); 1534 } 1535 if (msg.obj != null) { 1536 @SuppressWarnings("unchecked") 1537 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1539 // Unload containers 1540 unloadAllContainers(args); 1541 } 1542 if (reportStatus) { 1543 try { 1544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1545 PackageHelper.getMountService().finishMediaUpdate(); 1546 } catch (RemoteException e) { 1547 Log.e(TAG, "MountService not running?"); 1548 } 1549 } 1550 } break; 1551 case WRITE_SETTINGS: { 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1553 synchronized (mPackages) { 1554 removeMessages(WRITE_SETTINGS); 1555 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1556 mSettings.writeLPr(); 1557 mDirtyUsers.clear(); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 } break; 1561 case WRITE_PACKAGE_RESTRICTIONS: { 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1563 synchronized (mPackages) { 1564 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1565 for (int userId : mDirtyUsers) { 1566 mSettings.writePackageRestrictionsLPr(userId); 1567 } 1568 mDirtyUsers.clear(); 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 } break; 1572 case CHECK_PENDING_VERIFICATION: { 1573 final int verificationId = msg.arg1; 1574 final PackageVerificationState state = mPendingVerification.get(verificationId); 1575 1576 if ((state != null) && !state.timeoutExtended()) { 1577 final InstallArgs args = state.getInstallArgs(); 1578 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1579 1580 Slog.i(TAG, "Verification timed out for " + originUri); 1581 mPendingVerification.remove(verificationId); 1582 1583 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1584 1585 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1586 Slog.i(TAG, "Continuing with installation of " + originUri); 1587 state.setVerifierResponse(Binder.getCallingUid(), 1588 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1589 broadcastPackageVerified(verificationId, originUri, 1590 PackageManager.VERIFICATION_ALLOW, 1591 state.getInstallArgs().getUser()); 1592 try { 1593 ret = args.copyApk(mContainerService, true); 1594 } catch (RemoteException e) { 1595 Slog.e(TAG, "Could not contact the ContainerService"); 1596 } 1597 } else { 1598 broadcastPackageVerified(verificationId, originUri, 1599 PackageManager.VERIFICATION_REJECT, 1600 state.getInstallArgs().getUser()); 1601 } 1602 1603 Trace.asyncTraceEnd( 1604 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1605 1606 processPendingInstall(args, ret); 1607 mHandler.sendEmptyMessage(MCS_UNBIND); 1608 } 1609 break; 1610 } 1611 case PACKAGE_VERIFIED: { 1612 final int verificationId = msg.arg1; 1613 1614 final PackageVerificationState state = mPendingVerification.get(verificationId); 1615 if (state == null) { 1616 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1617 break; 1618 } 1619 1620 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1621 1622 state.setVerifierResponse(response.callerUid, response.code); 1623 1624 if (state.isVerificationComplete()) { 1625 mPendingVerification.remove(verificationId); 1626 1627 final InstallArgs args = state.getInstallArgs(); 1628 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1629 1630 int ret; 1631 if (state.isInstallAllowed()) { 1632 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1633 broadcastPackageVerified(verificationId, originUri, 1634 response.code, state.getInstallArgs().getUser()); 1635 try { 1636 ret = args.copyApk(mContainerService, true); 1637 } catch (RemoteException e) { 1638 Slog.e(TAG, "Could not contact the ContainerService"); 1639 } 1640 } else { 1641 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1642 } 1643 1644 Trace.asyncTraceEnd( 1645 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1646 1647 processPendingInstall(args, ret); 1648 mHandler.sendEmptyMessage(MCS_UNBIND); 1649 } 1650 1651 break; 1652 } 1653 case START_INTENT_FILTER_VERIFICATIONS: { 1654 IFVerificationParams params = (IFVerificationParams) msg.obj; 1655 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1656 params.replacing, params.pkg); 1657 break; 1658 } 1659 case INTENT_FILTER_VERIFIED: { 1660 final int verificationId = msg.arg1; 1661 1662 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1663 verificationId); 1664 if (state == null) { 1665 Slog.w(TAG, "Invalid IntentFilter verification token " 1666 + verificationId + " received"); 1667 break; 1668 } 1669 1670 final int userId = state.getUserId(); 1671 1672 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1673 "Processing IntentFilter verification with token:" 1674 + verificationId + " and userId:" + userId); 1675 1676 final IntentFilterVerificationResponse response = 1677 (IntentFilterVerificationResponse) msg.obj; 1678 1679 state.setVerifierResponse(response.callerUid, response.code); 1680 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1682 "IntentFilter verification with token:" + verificationId 1683 + " and userId:" + userId 1684 + " is settings verifier response with response code:" 1685 + response.code); 1686 1687 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1688 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1689 + response.getFailedDomainsString()); 1690 } 1691 1692 if (state.isVerificationComplete()) { 1693 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1694 } else { 1695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1696 "IntentFilter verification with token:" + verificationId 1697 + " was not said to be complete"); 1698 } 1699 1700 break; 1701 } 1702 } 1703 } 1704 } 1705 1706 private StorageEventListener mStorageListener = new StorageEventListener() { 1707 @Override 1708 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1709 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1710 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1711 final String volumeUuid = vol.getFsUuid(); 1712 1713 // Clean up any users or apps that were removed or recreated 1714 // while this volume was missing 1715 reconcileUsers(volumeUuid); 1716 reconcileApps(volumeUuid); 1717 1718 // Clean up any install sessions that expired or were 1719 // cancelled while this volume was missing 1720 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1721 1722 loadPrivatePackages(vol); 1723 1724 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1725 unloadPrivatePackages(vol); 1726 } 1727 } 1728 1729 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1730 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1731 updateExternalMediaStatus(true, false); 1732 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1733 updateExternalMediaStatus(false, false); 1734 } 1735 } 1736 } 1737 1738 @Override 1739 public void onVolumeForgotten(String fsUuid) { 1740 if (TextUtils.isEmpty(fsUuid)) { 1741 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1742 return; 1743 } 1744 1745 // Remove any apps installed on the forgotten volume 1746 synchronized (mPackages) { 1747 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1748 for (PackageSetting ps : packages) { 1749 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1750 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1751 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1752 } 1753 1754 mSettings.onVolumeForgotten(fsUuid); 1755 mSettings.writeLPr(); 1756 } 1757 } 1758 }; 1759 1760 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1761 String[] grantedPermissions) { 1762 if (userId >= UserHandle.USER_SYSTEM) { 1763 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1764 } else if (userId == UserHandle.USER_ALL) { 1765 final int[] userIds; 1766 synchronized (mPackages) { 1767 userIds = UserManagerService.getInstance().getUserIds(); 1768 } 1769 for (int someUserId : userIds) { 1770 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1771 } 1772 } 1773 1774 // We could have touched GID membership, so flush out packages.list 1775 synchronized (mPackages) { 1776 mSettings.writePackageListLPr(); 1777 } 1778 } 1779 1780 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1781 String[] grantedPermissions) { 1782 SettingBase sb = (SettingBase) pkg.mExtras; 1783 if (sb == null) { 1784 return; 1785 } 1786 1787 PermissionsState permissionsState = sb.getPermissionsState(); 1788 1789 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1790 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1791 1792 synchronized (mPackages) { 1793 for (String permission : pkg.requestedPermissions) { 1794 BasePermission bp = mSettings.mPermissions.get(permission); 1795 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1796 && (grantedPermissions == null 1797 || ArrayUtils.contains(grantedPermissions, permission))) { 1798 final int flags = permissionsState.getPermissionFlags(permission, userId); 1799 // Installer cannot change immutable permissions. 1800 if ((flags & immutableFlags) == 0) { 1801 grantRuntimePermission(pkg.packageName, permission, userId); 1802 } 1803 } 1804 } 1805 } 1806 } 1807 1808 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1809 Bundle extras = null; 1810 switch (res.returnCode) { 1811 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1812 extras = new Bundle(); 1813 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1814 res.origPermission); 1815 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1816 res.origPackage); 1817 break; 1818 } 1819 case PackageManager.INSTALL_SUCCEEDED: { 1820 extras = new Bundle(); 1821 extras.putBoolean(Intent.EXTRA_REPLACING, 1822 res.removedInfo != null && res.removedInfo.removedPackage != null); 1823 break; 1824 } 1825 } 1826 return extras; 1827 } 1828 1829 void scheduleWriteSettingsLocked() { 1830 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1831 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1832 } 1833 } 1834 1835 void scheduleWritePackageRestrictionsLocked(int userId) { 1836 if (!sUserManager.exists(userId)) return; 1837 mDirtyUsers.add(userId); 1838 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1839 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1840 } 1841 } 1842 1843 public static PackageManagerService main(Context context, Installer installer, 1844 boolean factoryTest, boolean onlyCore) { 1845 PackageManagerService m = new PackageManagerService(context, installer, 1846 factoryTest, onlyCore); 1847 m.enableSystemUserApps(); 1848 ServiceManager.addService("package", m); 1849 return m; 1850 } 1851 1852 private void enableSystemUserApps() { 1853 if (!UserManager.isSplitSystemUser()) { 1854 return; 1855 } 1856 // For system user, enable apps based on the following conditions: 1857 // - app is whitelisted or belong to one of these groups: 1858 // -- system app which has no launcher icons 1859 // -- system app which has INTERACT_ACROSS_USERS permission 1860 // -- system IME app 1861 // - app is not in the blacklist 1862 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1863 Set<String> enableApps = new ArraySet<>(); 1864 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1865 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1866 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1867 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1868 enableApps.addAll(wlApps); 1869 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1870 enableApps.removeAll(blApps); 1871 1872 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1873 UserHandle.SYSTEM); 1874 final int systemAppsSize = systemApps.size(); 1875 synchronized (mPackages) { 1876 for (int i = 0; i < systemAppsSize; i++) { 1877 String pName = systemApps.get(i); 1878 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1879 // Should not happen, but we shouldn't be failing if it does 1880 if (pkgSetting == null) { 1881 continue; 1882 } 1883 boolean installed = enableApps.contains(pName); 1884 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1885 } 1886 } 1887 } 1888 1889 static String[] splitString(String str, char sep) { 1890 int count = 1; 1891 int i = 0; 1892 while ((i=str.indexOf(sep, i)) >= 0) { 1893 count++; 1894 i++; 1895 } 1896 1897 String[] res = new String[count]; 1898 i=0; 1899 count = 0; 1900 int lastI=0; 1901 while ((i=str.indexOf(sep, i)) >= 0) { 1902 res[count] = str.substring(lastI, i); 1903 count++; 1904 i++; 1905 lastI = i; 1906 } 1907 res[count] = str.substring(lastI, str.length()); 1908 return res; 1909 } 1910 1911 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1912 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1913 Context.DISPLAY_SERVICE); 1914 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1915 } 1916 1917 public PackageManagerService(Context context, Installer installer, 1918 boolean factoryTest, boolean onlyCore) { 1919 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1920 SystemClock.uptimeMillis()); 1921 1922 if (mSdkVersion <= 0) { 1923 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1924 } 1925 1926 mContext = context; 1927 mFactoryTest = factoryTest; 1928 mOnlyCore = onlyCore; 1929 mMetrics = new DisplayMetrics(); 1930 mSettings = new Settings(mPackages); 1931 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1932 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1933 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1934 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1935 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1936 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1937 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1938 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1939 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1940 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1941 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1942 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1943 1944 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1945 if (separateProcesses != null && separateProcesses.length() > 0) { 1946 if ("*".equals(separateProcesses)) { 1947 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1948 mSeparateProcesses = null; 1949 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1950 } else { 1951 mDefParseFlags = 0; 1952 mSeparateProcesses = separateProcesses.split(","); 1953 Slog.w(TAG, "Running with debug.separate_processes: " 1954 + separateProcesses); 1955 } 1956 } else { 1957 mDefParseFlags = 0; 1958 mSeparateProcesses = null; 1959 } 1960 1961 mInstaller = installer; 1962 mPackageDexOptimizer = new PackageDexOptimizer(this); 1963 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1964 1965 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1966 FgThread.get().getLooper()); 1967 1968 getDefaultDisplayMetrics(context, mMetrics); 1969 1970 SystemConfig systemConfig = SystemConfig.getInstance(); 1971 mGlobalGids = systemConfig.getGlobalGids(); 1972 mSystemPermissions = systemConfig.getSystemPermissions(); 1973 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1974 1975 synchronized (mInstallLock) { 1976 // writer 1977 synchronized (mPackages) { 1978 mHandlerThread = new ServiceThread(TAG, 1979 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1980 mHandlerThread.start(); 1981 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1982 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1983 1984 File dataDir = Environment.getDataDirectory(); 1985 mAppDataDir = new File(dataDir, "data"); 1986 mAppInstallDir = new File(dataDir, "app"); 1987 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1988 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1989 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1990 mUserAppDataDir = new File(dataDir, "user"); 1991 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1992 1993 sUserManager = new UserManagerService(context, this, mPackages); 1994 1995 // Propagate permission configuration in to package manager. 1996 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1997 = systemConfig.getPermissions(); 1998 for (int i=0; i<permConfig.size(); i++) { 1999 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2000 BasePermission bp = mSettings.mPermissions.get(perm.name); 2001 if (bp == null) { 2002 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2003 mSettings.mPermissions.put(perm.name, bp); 2004 } 2005 if (perm.gids != null) { 2006 bp.setGids(perm.gids, perm.perUser); 2007 } 2008 } 2009 2010 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2011 for (int i=0; i<libConfig.size(); i++) { 2012 mSharedLibraries.put(libConfig.keyAt(i), 2013 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2014 } 2015 2016 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2017 2018 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2019 2020 String customResolverActivity = Resources.getSystem().getString( 2021 R.string.config_customResolverActivity); 2022 if (TextUtils.isEmpty(customResolverActivity)) { 2023 customResolverActivity = null; 2024 } else { 2025 mCustomResolverComponentName = ComponentName.unflattenFromString( 2026 customResolverActivity); 2027 } 2028 2029 long startTime = SystemClock.uptimeMillis(); 2030 2031 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2032 startTime); 2033 2034 // Set flag to monitor and not change apk file paths when 2035 // scanning install directories. 2036 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2037 2038 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2039 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2040 2041 if (bootClassPath == null) { 2042 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2043 } 2044 2045 if (systemServerClassPath == null) { 2046 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2047 } 2048 2049 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2050 final String[] dexCodeInstructionSets = 2051 getDexCodeInstructionSets( 2052 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2053 2054 /** 2055 * Ensure all external libraries have had dexopt run on them. 2056 */ 2057 if (mSharedLibraries.size() > 0) { 2058 // NOTE: For now, we're compiling these system "shared libraries" 2059 // (and framework jars) into all available architectures. It's possible 2060 // to compile them only when we come across an app that uses them (there's 2061 // already logic for that in scanPackageLI) but that adds some complexity. 2062 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2063 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2064 final String lib = libEntry.path; 2065 if (lib == null) { 2066 continue; 2067 } 2068 2069 try { 2070 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2071 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2072 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2073 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2074 } 2075 } catch (FileNotFoundException e) { 2076 Slog.w(TAG, "Library not found: " + lib); 2077 } catch (IOException e) { 2078 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2079 + e.getMessage()); 2080 } 2081 } 2082 } 2083 } 2084 2085 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2086 2087 final VersionInfo ver = mSettings.getInternalVersion(); 2088 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2089 // when upgrading from pre-M, promote system app permissions from install to runtime 2090 mPromoteSystemApps = 2091 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2092 2093 // save off the names of pre-existing system packages prior to scanning; we don't 2094 // want to automatically grant runtime permissions for new system apps 2095 if (mPromoteSystemApps) { 2096 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2097 while (pkgSettingIter.hasNext()) { 2098 PackageSetting ps = pkgSettingIter.next(); 2099 if (isSystemApp(ps)) { 2100 mExistingSystemPackages.add(ps.name); 2101 } 2102 } 2103 } 2104 2105 // Collect vendor overlay packages. 2106 // (Do this before scanning any apps.) 2107 // For security and version matching reason, only consider 2108 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2109 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2110 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2111 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2112 2113 // Find base frameworks (resource packages without code). 2114 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR 2116 | PackageParser.PARSE_IS_PRIVILEGED, 2117 scanFlags | SCAN_NO_DEX, 0); 2118 2119 // Collected privileged system packages. 2120 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2121 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2122 | PackageParser.PARSE_IS_SYSTEM_DIR 2123 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2124 2125 // Collect ordinary system packages. 2126 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2127 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 // Collect all vendor packages. 2131 File vendorAppDir = new File("/vendor/app"); 2132 try { 2133 vendorAppDir = vendorAppDir.getCanonicalFile(); 2134 } catch (IOException e) { 2135 // failed to look up canonical path, continue with original one 2136 } 2137 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2138 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2139 2140 // Collect all OEM packages. 2141 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2142 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2143 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2144 2145 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2146 mInstaller.moveFiles(); 2147 2148 // Prune any system packages that no longer exist. 2149 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2150 if (!mOnlyCore) { 2151 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2152 while (psit.hasNext()) { 2153 PackageSetting ps = psit.next(); 2154 2155 /* 2156 * If this is not a system app, it can't be a 2157 * disable system app. 2158 */ 2159 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2160 continue; 2161 } 2162 2163 /* 2164 * If the package is scanned, it's not erased. 2165 */ 2166 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2167 if (scannedPkg != null) { 2168 /* 2169 * If the system app is both scanned and in the 2170 * disabled packages list, then it must have been 2171 * added via OTA. Remove it from the currently 2172 * scanned package so the previously user-installed 2173 * application can be scanned. 2174 */ 2175 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2176 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2177 + ps.name + "; removing system app. Last known codePath=" 2178 + ps.codePathString + ", installStatus=" + ps.installStatus 2179 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2180 + scannedPkg.mVersionCode); 2181 removePackageLI(ps, true); 2182 mExpectingBetter.put(ps.name, ps.codePath); 2183 } 2184 2185 continue; 2186 } 2187 2188 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2189 psit.remove(); 2190 logCriticalInfo(Log.WARN, "System package " + ps.name 2191 + " no longer exists; wiping its data"); 2192 removeDataDirsLI(null, ps.name); 2193 } else { 2194 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2195 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2196 possiblyDeletedUpdatedSystemApps.add(ps.name); 2197 } 2198 } 2199 } 2200 } 2201 2202 //look for any incomplete package installations 2203 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2204 //clean up list 2205 for(int i = 0; i < deletePkgsList.size(); i++) { 2206 //clean up here 2207 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2208 } 2209 //delete tmp files 2210 deleteTempPackageFiles(); 2211 2212 // Remove any shared userIDs that have no associated packages 2213 mSettings.pruneSharedUsersLPw(); 2214 2215 if (!mOnlyCore) { 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2217 SystemClock.uptimeMillis()); 2218 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2219 2220 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2221 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2222 2223 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2224 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2225 2226 /** 2227 * Remove disable package settings for any updated system 2228 * apps that were removed via an OTA. If they're not a 2229 * previously-updated app, remove them completely. 2230 * Otherwise, just revoke their system-level permissions. 2231 */ 2232 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2233 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2234 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2235 2236 String msg; 2237 if (deletedPkg == null) { 2238 msg = "Updated system package " + deletedAppName 2239 + " no longer exists; wiping its data"; 2240 removeDataDirsLI(null, deletedAppName); 2241 } else { 2242 msg = "Updated system app + " + deletedAppName 2243 + " no longer present; removing system privileges for " 2244 + deletedAppName; 2245 2246 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2247 2248 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2249 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2250 } 2251 logCriticalInfo(Log.WARN, msg); 2252 } 2253 2254 /** 2255 * Make sure all system apps that we expected to appear on 2256 * the userdata partition actually showed up. If they never 2257 * appeared, crawl back and revive the system version. 2258 */ 2259 for (int i = 0; i < mExpectingBetter.size(); i++) { 2260 final String packageName = mExpectingBetter.keyAt(i); 2261 if (!mPackages.containsKey(packageName)) { 2262 final File scanFile = mExpectingBetter.valueAt(i); 2263 2264 logCriticalInfo(Log.WARN, "Expected better " + packageName 2265 + " but never showed up; reverting to system"); 2266 2267 final int reparseFlags; 2268 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR 2271 | PackageParser.PARSE_IS_PRIVILEGED; 2272 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2273 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2274 | PackageParser.PARSE_IS_SYSTEM_DIR; 2275 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2276 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR; 2278 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2279 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2280 | PackageParser.PARSE_IS_SYSTEM_DIR; 2281 } else { 2282 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2283 continue; 2284 } 2285 2286 mSettings.enableSystemPackageLPw(packageName); 2287 2288 try { 2289 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2290 } catch (PackageManagerException e) { 2291 Slog.e(TAG, "Failed to parse original system package: " 2292 + e.getMessage()); 2293 } 2294 } 2295 } 2296 } 2297 mExpectingBetter.clear(); 2298 2299 // Now that we know all of the shared libraries, update all clients to have 2300 // the correct library paths. 2301 updateAllSharedLibrariesLPw(); 2302 2303 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2304 // NOTE: We ignore potential failures here during a system scan (like 2305 // the rest of the commands above) because there's precious little we 2306 // can do about it. A settings error is reported, though. 2307 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2308 false /* boot complete */); 2309 } 2310 2311 // Now that we know all the packages we are keeping, 2312 // read and update their last usage times. 2313 mPackageUsage.readLP(); 2314 2315 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2316 SystemClock.uptimeMillis()); 2317 Slog.i(TAG, "Time to scan packages: " 2318 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2319 + " seconds"); 2320 2321 // If the platform SDK has changed since the last time we booted, 2322 // we need to re-grant app permission to catch any new ones that 2323 // appear. This is really a hack, and means that apps can in some 2324 // cases get permissions that the user didn't initially explicitly 2325 // allow... it would be nice to have some better way to handle 2326 // this situation. 2327 int updateFlags = UPDATE_PERMISSIONS_ALL; 2328 if (ver.sdkVersion != mSdkVersion) { 2329 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2330 + mSdkVersion + "; regranting permissions for internal storage"); 2331 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2332 } 2333 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2334 ver.sdkVersion = mSdkVersion; 2335 2336 // If this is the first boot or an update from pre-M, and it is a normal 2337 // boot, then we need to initialize the default preferred apps across 2338 // all defined users. 2339 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2340 for (UserInfo user : sUserManager.getUsers(true)) { 2341 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2342 applyFactoryDefaultBrowserLPw(user.id); 2343 primeDomainVerificationsLPw(user.id); 2344 } 2345 } 2346 2347 // If this is first boot after an OTA, and a normal boot, then 2348 // we need to clear code cache directories. 2349 if (mIsUpgrade && !onlyCore) { 2350 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2351 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2352 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2353 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2354 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2355 } 2356 } 2357 ver.fingerprint = Build.FINGERPRINT; 2358 } 2359 2360 checkDefaultBrowser(); 2361 2362 // clear only after permissions and other defaults have been updated 2363 mExistingSystemPackages.clear(); 2364 mPromoteSystemApps = false; 2365 2366 // All the changes are done during package scanning. 2367 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2368 2369 // can downgrade to reader 2370 mSettings.writeLPr(); 2371 2372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2373 SystemClock.uptimeMillis()); 2374 2375 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2376 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2377 2378 mInstallerService = new PackageInstallerService(context, this); 2379 2380 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2381 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2382 mIntentFilterVerifierComponent); 2383 2384 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2385 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2386 // both the installer and resolver must be present to enable ephemeral 2387 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2388 if (DEBUG_EPHEMERAL) { 2389 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2390 + " installer:" + ephemeralInstallerComponent); 2391 } 2392 mEphemeralResolverComponent = ephemeralResolverComponent; 2393 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2394 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2395 mEphemeralResolverConnection = 2396 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2397 } else { 2398 if (DEBUG_EPHEMERAL) { 2399 final String missingComponent = 2400 (ephemeralResolverComponent == null) 2401 ? (ephemeralInstallerComponent == null) 2402 ? "resolver and installer" 2403 : "resolver" 2404 : "installer"; 2405 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2406 } 2407 mEphemeralResolverComponent = null; 2408 mEphemeralInstallerComponent = null; 2409 mEphemeralResolverConnection = null; 2410 } 2411 } // synchronized (mPackages) 2412 } // synchronized (mInstallLock) 2413 2414 // Now after opening every single application zip, make sure they 2415 // are all flushed. Not really needed, but keeps things nice and 2416 // tidy. 2417 Runtime.getRuntime().gc(); 2418 2419 // The initial scanning above does many calls into installd while 2420 // holding the mPackages lock, but we're mostly interested in yelling 2421 // once we have a booted system. 2422 mInstaller.setWarnIfHeld(mPackages); 2423 2424 // Expose private service for system components to use. 2425 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2426 } 2427 2428 @Override 2429 public boolean isFirstBoot() { 2430 return !mRestoredSettings; 2431 } 2432 2433 @Override 2434 public boolean isOnlyCoreApps() { 2435 return mOnlyCore; 2436 } 2437 2438 @Override 2439 public boolean isUpgrade() { 2440 return mIsUpgrade; 2441 } 2442 2443 private String getRequiredVerifierLPr() { 2444 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2445 // We only care about verifier that's installed under system user. 2446 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2447 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2448 2449 String requiredVerifier = null; 2450 2451 final int N = receivers.size(); 2452 for (int i = 0; i < N; i++) { 2453 final ResolveInfo info = receivers.get(i); 2454 2455 if (info.activityInfo == null) { 2456 continue; 2457 } 2458 2459 final String packageName = info.activityInfo.packageName; 2460 2461 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2462 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2463 continue; 2464 } 2465 2466 if (requiredVerifier != null) { 2467 throw new RuntimeException("There can be only one required verifier"); 2468 } 2469 2470 requiredVerifier = packageName; 2471 } 2472 2473 return requiredVerifier; 2474 } 2475 2476 private String getRequiredInstallerLPr() { 2477 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2478 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2479 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2480 2481 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2482 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2483 2484 String requiredInstaller = null; 2485 2486 final int N = installers.size(); 2487 for (int i = 0; i < N; i++) { 2488 final ResolveInfo info = installers.get(i); 2489 final String packageName = info.activityInfo.packageName; 2490 2491 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2492 continue; 2493 } 2494 2495 if (requiredInstaller != null) { 2496 throw new RuntimeException("There must be one required installer"); 2497 } 2498 2499 requiredInstaller = packageName; 2500 } 2501 2502 if (requiredInstaller == null) { 2503 throw new RuntimeException("There must be one required installer"); 2504 } 2505 2506 return requiredInstaller; 2507 } 2508 2509 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2510 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2511 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2512 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2513 2514 ComponentName verifierComponentName = null; 2515 2516 int priority = -1000; 2517 final int N = receivers.size(); 2518 for (int i = 0; i < N; i++) { 2519 final ResolveInfo info = receivers.get(i); 2520 2521 if (info.activityInfo == null) { 2522 continue; 2523 } 2524 2525 final String packageName = info.activityInfo.packageName; 2526 2527 final PackageSetting ps = mSettings.mPackages.get(packageName); 2528 if (ps == null) { 2529 continue; 2530 } 2531 2532 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2533 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2534 continue; 2535 } 2536 2537 // Select the IntentFilterVerifier with the highest priority 2538 if (priority < info.priority) { 2539 priority = info.priority; 2540 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2541 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2542 + verifierComponentName + " with priority: " + info.priority); 2543 } 2544 } 2545 2546 return verifierComponentName; 2547 } 2548 2549 private ComponentName getEphemeralResolverLPr() { 2550 final String[] packageArray = 2551 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2552 if (packageArray.length == 0) { 2553 if (DEBUG_EPHEMERAL) { 2554 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2555 } 2556 return null; 2557 } 2558 2559 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2560 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2561 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2562 2563 final int N = resolvers.size(); 2564 if (N == 0) { 2565 if (DEBUG_EPHEMERAL) { 2566 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2567 } 2568 return null; 2569 } 2570 2571 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2572 for (int i = 0; i < N; i++) { 2573 final ResolveInfo info = resolvers.get(i); 2574 2575 if (info.serviceInfo == null) { 2576 continue; 2577 } 2578 2579 final String packageName = info.serviceInfo.packageName; 2580 if (!possiblePackages.contains(packageName)) { 2581 if (DEBUG_EPHEMERAL) { 2582 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2583 + " pkg: " + packageName + ", info:" + info); 2584 } 2585 continue; 2586 } 2587 2588 if (DEBUG_EPHEMERAL) { 2589 Slog.v(TAG, "Ephemeral resolver found;" 2590 + " pkg: " + packageName + ", info:" + info); 2591 } 2592 return new ComponentName(packageName, info.serviceInfo.name); 2593 } 2594 if (DEBUG_EPHEMERAL) { 2595 Slog.v(TAG, "Ephemeral resolver NOT found"); 2596 } 2597 return null; 2598 } 2599 2600 private ComponentName getEphemeralInstallerLPr() { 2601 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2602 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2603 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2604 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2605 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2606 2607 ComponentName ephemeralInstaller = null; 2608 2609 final int N = installers.size(); 2610 for (int i = 0; i < N; i++) { 2611 final ResolveInfo info = installers.get(i); 2612 final String packageName = info.activityInfo.packageName; 2613 2614 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2615 if (DEBUG_EPHEMERAL) { 2616 Slog.d(TAG, "Ephemeral installer is not system app;" 2617 + " pkg: " + packageName + ", info:" + info); 2618 } 2619 continue; 2620 } 2621 2622 if (ephemeralInstaller != null) { 2623 throw new RuntimeException("There must only be one ephemeral installer"); 2624 } 2625 2626 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2627 } 2628 2629 return ephemeralInstaller; 2630 } 2631 2632 private void primeDomainVerificationsLPw(int userId) { 2633 if (DEBUG_DOMAIN_VERIFICATION) { 2634 Slog.d(TAG, "Priming domain verifications in user " + userId); 2635 } 2636 2637 SystemConfig systemConfig = SystemConfig.getInstance(); 2638 ArraySet<String> packages = systemConfig.getLinkedApps(); 2639 ArraySet<String> domains = new ArraySet<String>(); 2640 2641 for (String packageName : packages) { 2642 PackageParser.Package pkg = mPackages.get(packageName); 2643 if (pkg != null) { 2644 if (!pkg.isSystemApp()) { 2645 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2646 continue; 2647 } 2648 2649 domains.clear(); 2650 for (PackageParser.Activity a : pkg.activities) { 2651 for (ActivityIntentInfo filter : a.intents) { 2652 if (hasValidDomains(filter)) { 2653 domains.addAll(filter.getHostsList()); 2654 } 2655 } 2656 } 2657 2658 if (domains.size() > 0) { 2659 if (DEBUG_DOMAIN_VERIFICATION) { 2660 Slog.v(TAG, " + " + packageName); 2661 } 2662 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2663 // state w.r.t. the formal app-linkage "no verification attempted" state; 2664 // and then 'always' in the per-user state actually used for intent resolution. 2665 final IntentFilterVerificationInfo ivi; 2666 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2667 new ArrayList<String>(domains)); 2668 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2669 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2670 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2671 } else { 2672 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2673 + "' does not handle web links"); 2674 } 2675 } else { 2676 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2677 } 2678 } 2679 2680 scheduleWritePackageRestrictionsLocked(userId); 2681 scheduleWriteSettingsLocked(); 2682 } 2683 2684 private void applyFactoryDefaultBrowserLPw(int userId) { 2685 // The default browser app's package name is stored in a string resource, 2686 // with a product-specific overlay used for vendor customization. 2687 String browserPkg = mContext.getResources().getString( 2688 com.android.internal.R.string.default_browser); 2689 if (!TextUtils.isEmpty(browserPkg)) { 2690 // non-empty string => required to be a known package 2691 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2692 if (ps == null) { 2693 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2694 browserPkg = null; 2695 } else { 2696 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2697 } 2698 } 2699 2700 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2701 // default. If there's more than one, just leave everything alone. 2702 if (browserPkg == null) { 2703 calculateDefaultBrowserLPw(userId); 2704 } 2705 } 2706 2707 private void calculateDefaultBrowserLPw(int userId) { 2708 List<String> allBrowsers = resolveAllBrowserApps(userId); 2709 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2710 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2711 } 2712 2713 private List<String> resolveAllBrowserApps(int userId) { 2714 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2715 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2716 PackageManager.MATCH_ALL, userId); 2717 2718 final int count = list.size(); 2719 List<String> result = new ArrayList<String>(count); 2720 for (int i=0; i<count; i++) { 2721 ResolveInfo info = list.get(i); 2722 if (info.activityInfo == null 2723 || !info.handleAllWebDataURI 2724 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2725 || result.contains(info.activityInfo.packageName)) { 2726 continue; 2727 } 2728 result.add(info.activityInfo.packageName); 2729 } 2730 2731 return result; 2732 } 2733 2734 private boolean packageIsBrowser(String packageName, int userId) { 2735 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2736 PackageManager.MATCH_ALL, userId); 2737 final int N = list.size(); 2738 for (int i = 0; i < N; i++) { 2739 ResolveInfo info = list.get(i); 2740 if (packageName.equals(info.activityInfo.packageName)) { 2741 return true; 2742 } 2743 } 2744 return false; 2745 } 2746 2747 private void checkDefaultBrowser() { 2748 final int myUserId = UserHandle.myUserId(); 2749 final String packageName = getDefaultBrowserPackageName(myUserId); 2750 if (packageName != null) { 2751 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2752 if (info == null) { 2753 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2754 synchronized (mPackages) { 2755 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2756 } 2757 } 2758 } 2759 } 2760 2761 @Override 2762 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2763 throws RemoteException { 2764 try { 2765 return super.onTransact(code, data, reply, flags); 2766 } catch (RuntimeException e) { 2767 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2768 Slog.wtf(TAG, "Package Manager Crash", e); 2769 } 2770 throw e; 2771 } 2772 } 2773 2774 void cleanupInstallFailedPackage(PackageSetting ps) { 2775 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2776 2777 removeDataDirsLI(ps.volumeUuid, ps.name); 2778 if (ps.codePath != null) { 2779 if (ps.codePath.isDirectory()) { 2780 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2781 } else { 2782 ps.codePath.delete(); 2783 } 2784 } 2785 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2786 if (ps.resourcePath.isDirectory()) { 2787 FileUtils.deleteContents(ps.resourcePath); 2788 } 2789 ps.resourcePath.delete(); 2790 } 2791 mSettings.removePackageLPw(ps.name); 2792 } 2793 2794 static int[] appendInts(int[] cur, int[] add) { 2795 if (add == null) return cur; 2796 if (cur == null) return add; 2797 final int N = add.length; 2798 for (int i=0; i<N; i++) { 2799 cur = appendInt(cur, add[i]); 2800 } 2801 return cur; 2802 } 2803 2804 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2805 if (!sUserManager.exists(userId)) return null; 2806 final PackageSetting ps = (PackageSetting) p.mExtras; 2807 if (ps == null) { 2808 return null; 2809 } 2810 2811 final PermissionsState permissionsState = ps.getPermissionsState(); 2812 2813 final int[] gids = permissionsState.computeGids(userId); 2814 final Set<String> permissions = permissionsState.getPermissions(userId); 2815 final PackageUserState state = ps.readUserState(userId); 2816 2817 return PackageParser.generatePackageInfo(p, gids, flags, 2818 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2819 } 2820 2821 @Override 2822 public void checkPackageStartable(String packageName, int userId) { 2823 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2824 2825 synchronized (mPackages) { 2826 final PackageSetting ps = mSettings.mPackages.get(packageName); 2827 if (ps == null) { 2828 throw new SecurityException("Package " + packageName + " was not found!"); 2829 } 2830 2831 if (ps.frozen) { 2832 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2833 } 2834 2835 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2836 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2837 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2838 } 2839 } 2840 } 2841 2842 @Override 2843 public boolean isPackageAvailable(String packageName, int userId) { 2844 if (!sUserManager.exists(userId)) return false; 2845 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2846 synchronized (mPackages) { 2847 PackageParser.Package p = mPackages.get(packageName); 2848 if (p != null) { 2849 final PackageSetting ps = (PackageSetting) p.mExtras; 2850 if (ps != null) { 2851 final PackageUserState state = ps.readUserState(userId); 2852 if (state != null) { 2853 return PackageParser.isAvailable(state); 2854 } 2855 } 2856 } 2857 } 2858 return false; 2859 } 2860 2861 @Override 2862 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2865 // reader 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) 2869 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2870 if (p != null) { 2871 return generatePackageInfo(p, flags, userId); 2872 } 2873 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2874 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2875 } 2876 } 2877 return null; 2878 } 2879 2880 @Override 2881 public String[] currentToCanonicalPackageNames(String[] names) { 2882 String[] out = new String[names.length]; 2883 // reader 2884 synchronized (mPackages) { 2885 for (int i=names.length-1; i>=0; i--) { 2886 PackageSetting ps = mSettings.mPackages.get(names[i]); 2887 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2888 } 2889 } 2890 return out; 2891 } 2892 2893 @Override 2894 public String[] canonicalToCurrentPackageNames(String[] names) { 2895 String[] out = new String[names.length]; 2896 // reader 2897 synchronized (mPackages) { 2898 for (int i=names.length-1; i>=0; i--) { 2899 String cur = mSettings.mRenamedPackages.get(names[i]); 2900 out[i] = cur != null ? cur : names[i]; 2901 } 2902 } 2903 return out; 2904 } 2905 2906 @Override 2907 public int getPackageUid(String packageName, int userId) { 2908 return getPackageUidEtc(packageName, 0, userId); 2909 } 2910 2911 @Override 2912 public int getPackageUidEtc(String packageName, int flags, int userId) { 2913 if (!sUserManager.exists(userId)) return -1; 2914 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2915 2916 // reader 2917 synchronized (mPackages) { 2918 final PackageParser.Package p = mPackages.get(packageName); 2919 if (p != null) { 2920 return UserHandle.getUid(userId, p.applicationInfo.uid); 2921 } 2922 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2923 final PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null) { 2925 return UserHandle.getUid(userId, ps.appId); 2926 } 2927 } 2928 } 2929 2930 return -1; 2931 } 2932 2933 @Override 2934 public int[] getPackageGids(String packageName, int userId) { 2935 return getPackageGidsEtc(packageName, 0, userId); 2936 } 2937 2938 @Override 2939 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2940 if (!sUserManager.exists(userId)) { 2941 return null; 2942 } 2943 2944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2945 "getPackageGids"); 2946 2947 // reader 2948 synchronized (mPackages) { 2949 final PackageParser.Package p = mPackages.get(packageName); 2950 if (p != null) { 2951 PackageSetting ps = (PackageSetting) p.mExtras; 2952 return ps.getPermissionsState().computeGids(userId); 2953 } 2954 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2955 final PackageSetting ps = mSettings.mPackages.get(packageName); 2956 if (ps != null) { 2957 return ps.getPermissionsState().computeGids(userId); 2958 } 2959 } 2960 } 2961 2962 return null; 2963 } 2964 2965 static PermissionInfo generatePermissionInfo( 2966 BasePermission bp, int flags) { 2967 if (bp.perm != null) { 2968 return PackageParser.generatePermissionInfo(bp.perm, flags); 2969 } 2970 PermissionInfo pi = new PermissionInfo(); 2971 pi.name = bp.name; 2972 pi.packageName = bp.sourcePackage; 2973 pi.nonLocalizedLabel = bp.name; 2974 pi.protectionLevel = bp.protectionLevel; 2975 return pi; 2976 } 2977 2978 @Override 2979 public PermissionInfo getPermissionInfo(String name, int flags) { 2980 // reader 2981 synchronized (mPackages) { 2982 final BasePermission p = mSettings.mPermissions.get(name); 2983 if (p != null) { 2984 return generatePermissionInfo(p, flags); 2985 } 2986 return null; 2987 } 2988 } 2989 2990 @Override 2991 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2995 for (BasePermission p : mSettings.mPermissions.values()) { 2996 if (group == null) { 2997 if (p.perm == null || p.perm.info.group == null) { 2998 out.add(generatePermissionInfo(p, flags)); 2999 } 3000 } else { 3001 if (p.perm != null && group.equals(p.perm.info.group)) { 3002 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3003 } 3004 } 3005 } 3006 3007 if (out.size() > 0) { 3008 return out; 3009 } 3010 return mPermissionGroups.containsKey(group) ? out : null; 3011 } 3012 } 3013 3014 @Override 3015 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3016 // reader 3017 synchronized (mPackages) { 3018 return PackageParser.generatePermissionGroupInfo( 3019 mPermissionGroups.get(name), flags); 3020 } 3021 } 3022 3023 @Override 3024 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3025 // reader 3026 synchronized (mPackages) { 3027 final int N = mPermissionGroups.size(); 3028 ArrayList<PermissionGroupInfo> out 3029 = new ArrayList<PermissionGroupInfo>(N); 3030 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3031 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3032 } 3033 return out; 3034 } 3035 } 3036 3037 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3038 int userId) { 3039 if (!sUserManager.exists(userId)) return null; 3040 PackageSetting ps = mSettings.mPackages.get(packageName); 3041 if (ps != null) { 3042 if (ps.pkg == null) { 3043 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3044 flags, userId); 3045 if (pInfo != null) { 3046 return pInfo.applicationInfo; 3047 } 3048 return null; 3049 } 3050 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3051 ps.readUserState(userId), userId); 3052 } 3053 return null; 3054 } 3055 3056 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3057 int userId) { 3058 if (!sUserManager.exists(userId)) return null; 3059 PackageSetting ps = mSettings.mPackages.get(packageName); 3060 if (ps != null) { 3061 PackageParser.Package pkg = ps.pkg; 3062 if (pkg == null) { 3063 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3064 return null; 3065 } 3066 // Only data remains, so we aren't worried about code paths 3067 pkg = new PackageParser.Package(packageName); 3068 pkg.applicationInfo.packageName = packageName; 3069 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3070 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3071 pkg.applicationInfo.uid = ps.appId; 3072 pkg.applicationInfo.initForUser(userId); 3073 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3074 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3075 } 3076 return generatePackageInfo(pkg, flags, userId); 3077 } 3078 return null; 3079 } 3080 3081 @Override 3082 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3083 if (!sUserManager.exists(userId)) return null; 3084 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3085 // writer 3086 synchronized (mPackages) { 3087 PackageParser.Package p = mPackages.get(packageName); 3088 if (DEBUG_PACKAGE_INFO) Log.v( 3089 TAG, "getApplicationInfo " + packageName 3090 + ": " + p); 3091 if (p != null) { 3092 PackageSetting ps = mSettings.mPackages.get(packageName); 3093 if (ps == null) return null; 3094 // Note: isEnabledLP() does not apply here - always return info 3095 return PackageParser.generateApplicationInfo( 3096 p, flags, ps.readUserState(userId), userId); 3097 } 3098 if ("android".equals(packageName)||"system".equals(packageName)) { 3099 return mAndroidApplication; 3100 } 3101 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3102 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3103 } 3104 } 3105 return null; 3106 } 3107 3108 @Override 3109 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3110 final IPackageDataObserver observer) { 3111 mContext.enforceCallingOrSelfPermission( 3112 android.Manifest.permission.CLEAR_APP_CACHE, null); 3113 // Queue up an async operation since clearing cache may take a little while. 3114 mHandler.post(new Runnable() { 3115 public void run() { 3116 mHandler.removeCallbacks(this); 3117 int retCode = -1; 3118 synchronized (mInstallLock) { 3119 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3120 if (retCode < 0) { 3121 Slog.w(TAG, "Couldn't clear application caches"); 3122 } 3123 } 3124 if (observer != null) { 3125 try { 3126 observer.onRemoveCompleted(null, (retCode >= 0)); 3127 } catch (RemoteException e) { 3128 Slog.w(TAG, "RemoveException when invoking call back"); 3129 } 3130 } 3131 } 3132 }); 3133 } 3134 3135 @Override 3136 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3137 final IntentSender pi) { 3138 mContext.enforceCallingOrSelfPermission( 3139 android.Manifest.permission.CLEAR_APP_CACHE, null); 3140 // Queue up an async operation since clearing cache may take a little while. 3141 mHandler.post(new Runnable() { 3142 public void run() { 3143 mHandler.removeCallbacks(this); 3144 int retCode = -1; 3145 synchronized (mInstallLock) { 3146 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3147 if (retCode < 0) { 3148 Slog.w(TAG, "Couldn't clear application caches"); 3149 } 3150 } 3151 if(pi != null) { 3152 try { 3153 // Callback via pending intent 3154 int code = (retCode >= 0) ? 1 : 0; 3155 pi.sendIntent(null, code, null, 3156 null, null); 3157 } catch (SendIntentException e1) { 3158 Slog.i(TAG, "Failed to send pending intent"); 3159 } 3160 } 3161 } 3162 }); 3163 } 3164 3165 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3166 synchronized (mInstallLock) { 3167 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3168 throw new IOException("Failed to free enough space"); 3169 } 3170 } 3171 } 3172 3173 /** 3174 * Return if the user key is currently unlocked. 3175 */ 3176 private boolean isUserKeyUnlocked(int userId) { 3177 if (StorageManager.isFileBasedEncryptionEnabled()) { 3178 final IMountService mount = IMountService.Stub 3179 .asInterface(ServiceManager.getService("mount")); 3180 if (mount == null) { 3181 Slog.w(TAG, "Early during boot, assuming locked"); 3182 return false; 3183 } 3184 final long token = Binder.clearCallingIdentity(); 3185 try { 3186 return mount.isUserKeyUnlocked(userId); 3187 } catch (RemoteException e) { 3188 throw e.rethrowAsRuntimeException(); 3189 } finally { 3190 Binder.restoreCallingIdentity(token); 3191 } 3192 } else { 3193 return true; 3194 } 3195 } 3196 3197 /** 3198 * Augment the given flags depending on current user running state. This is 3199 * purposefully done before acquiring {@link #mPackages} lock. 3200 */ 3201 private int augmentFlagsForUser(int flags, int userId) { 3202 if (!isUserKeyUnlocked(userId)) { 3203 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3204 } 3205 return flags; 3206 } 3207 3208 @Override 3209 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3210 if (!sUserManager.exists(userId)) return null; 3211 flags = augmentFlagsForUser(flags, userId); 3212 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3213 synchronized (mPackages) { 3214 PackageParser.Activity a = mActivities.mActivities.get(component); 3215 3216 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3217 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3218 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3219 if (ps == null) return null; 3220 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3221 userId); 3222 } 3223 if (mResolveComponentName.equals(component)) { 3224 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3225 new PackageUserState(), userId); 3226 } 3227 } 3228 return null; 3229 } 3230 3231 @Override 3232 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3233 String resolvedType) { 3234 synchronized (mPackages) { 3235 if (component.equals(mResolveComponentName)) { 3236 // The resolver supports EVERYTHING! 3237 return true; 3238 } 3239 PackageParser.Activity a = mActivities.mActivities.get(component); 3240 if (a == null) { 3241 return false; 3242 } 3243 for (int i=0; i<a.intents.size(); i++) { 3244 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3245 intent.getData(), intent.getCategories(), TAG) >= 0) { 3246 return true; 3247 } 3248 } 3249 return false; 3250 } 3251 } 3252 3253 @Override 3254 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return null; 3256 flags = augmentFlagsForUser(flags, userId); 3257 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3258 synchronized (mPackages) { 3259 PackageParser.Activity a = mReceivers.mActivities.get(component); 3260 if (DEBUG_PACKAGE_INFO) Log.v( 3261 TAG, "getReceiverInfo " + component + ": " + a); 3262 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3263 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3264 if (ps == null) return null; 3265 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3266 userId); 3267 } 3268 } 3269 return null; 3270 } 3271 3272 @Override 3273 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3274 if (!sUserManager.exists(userId)) return null; 3275 flags = augmentFlagsForUser(flags, userId); 3276 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3277 synchronized (mPackages) { 3278 PackageParser.Service s = mServices.mServices.get(component); 3279 if (DEBUG_PACKAGE_INFO) Log.v( 3280 TAG, "getServiceInfo " + component + ": " + s); 3281 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3282 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3283 if (ps == null) return null; 3284 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3285 userId); 3286 } 3287 } 3288 return null; 3289 } 3290 3291 @Override 3292 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3293 if (!sUserManager.exists(userId)) return null; 3294 flags = augmentFlagsForUser(flags, userId); 3295 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3296 synchronized (mPackages) { 3297 PackageParser.Provider p = mProviders.mProviders.get(component); 3298 if (DEBUG_PACKAGE_INFO) Log.v( 3299 TAG, "getProviderInfo " + component + ": " + p); 3300 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3301 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3302 if (ps == null) return null; 3303 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3304 userId); 3305 } 3306 } 3307 return null; 3308 } 3309 3310 @Override 3311 public String[] getSystemSharedLibraryNames() { 3312 Set<String> libSet; 3313 synchronized (mPackages) { 3314 libSet = mSharedLibraries.keySet(); 3315 int size = libSet.size(); 3316 if (size > 0) { 3317 String[] libs = new String[size]; 3318 libSet.toArray(libs); 3319 return libs; 3320 } 3321 } 3322 return null; 3323 } 3324 3325 /** 3326 * @hide 3327 */ 3328 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3329 synchronized (mPackages) { 3330 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3331 if (lib != null && lib.apk != null) { 3332 return mPackages.get(lib.apk); 3333 } 3334 } 3335 return null; 3336 } 3337 3338 @Override 3339 public FeatureInfo[] getSystemAvailableFeatures() { 3340 Collection<FeatureInfo> featSet; 3341 synchronized (mPackages) { 3342 featSet = mAvailableFeatures.values(); 3343 int size = featSet.size(); 3344 if (size > 0) { 3345 FeatureInfo[] features = new FeatureInfo[size+1]; 3346 featSet.toArray(features); 3347 FeatureInfo fi = new FeatureInfo(); 3348 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3349 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3350 features[size] = fi; 3351 return features; 3352 } 3353 } 3354 return null; 3355 } 3356 3357 @Override 3358 public boolean hasSystemFeature(String name) { 3359 synchronized (mPackages) { 3360 return mAvailableFeatures.containsKey(name); 3361 } 3362 } 3363 3364 private void checkValidCaller(int uid, int userId) { 3365 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3366 return; 3367 3368 throw new SecurityException("Caller uid=" + uid 3369 + " is not privileged to communicate with user=" + userId); 3370 } 3371 3372 @Override 3373 public int checkPermission(String permName, String pkgName, int userId) { 3374 if (!sUserManager.exists(userId)) { 3375 return PackageManager.PERMISSION_DENIED; 3376 } 3377 3378 synchronized (mPackages) { 3379 final PackageParser.Package p = mPackages.get(pkgName); 3380 if (p != null && p.mExtras != null) { 3381 final PackageSetting ps = (PackageSetting) p.mExtras; 3382 final PermissionsState permissionsState = ps.getPermissionsState(); 3383 if (permissionsState.hasPermission(permName, userId)) { 3384 return PackageManager.PERMISSION_GRANTED; 3385 } 3386 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3387 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3388 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3389 return PackageManager.PERMISSION_GRANTED; 3390 } 3391 } 3392 } 3393 3394 return PackageManager.PERMISSION_DENIED; 3395 } 3396 3397 @Override 3398 public int checkUidPermission(String permName, int uid) { 3399 final int userId = UserHandle.getUserId(uid); 3400 3401 if (!sUserManager.exists(userId)) { 3402 return PackageManager.PERMISSION_DENIED; 3403 } 3404 3405 synchronized (mPackages) { 3406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3407 if (obj != null) { 3408 final SettingBase ps = (SettingBase) obj; 3409 final PermissionsState permissionsState = ps.getPermissionsState(); 3410 if (permissionsState.hasPermission(permName, userId)) { 3411 return PackageManager.PERMISSION_GRANTED; 3412 } 3413 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3414 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3415 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3416 return PackageManager.PERMISSION_GRANTED; 3417 } 3418 } else { 3419 ArraySet<String> perms = mSystemPermissions.get(uid); 3420 if (perms != null) { 3421 if (perms.contains(permName)) { 3422 return PackageManager.PERMISSION_GRANTED; 3423 } 3424 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3425 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3426 return PackageManager.PERMISSION_GRANTED; 3427 } 3428 } 3429 } 3430 } 3431 3432 return PackageManager.PERMISSION_DENIED; 3433 } 3434 3435 @Override 3436 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3437 if (UserHandle.getCallingUserId() != userId) { 3438 mContext.enforceCallingPermission( 3439 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3440 "isPermissionRevokedByPolicy for user " + userId); 3441 } 3442 3443 if (checkPermission(permission, packageName, userId) 3444 == PackageManager.PERMISSION_GRANTED) { 3445 return false; 3446 } 3447 3448 final long identity = Binder.clearCallingIdentity(); 3449 try { 3450 final int flags = getPermissionFlags(permission, packageName, userId); 3451 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3452 } finally { 3453 Binder.restoreCallingIdentity(identity); 3454 } 3455 } 3456 3457 @Override 3458 public String getPermissionControllerPackageName() { 3459 synchronized (mPackages) { 3460 return mRequiredInstallerPackage; 3461 } 3462 } 3463 3464 /** 3465 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3466 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3467 * @param checkShell TODO(yamasani): 3468 * @param message the message to log on security exception 3469 */ 3470 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3471 boolean checkShell, String message) { 3472 if (userId < 0) { 3473 throw new IllegalArgumentException("Invalid userId " + userId); 3474 } 3475 if (checkShell) { 3476 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3477 } 3478 if (userId == UserHandle.getUserId(callingUid)) return; 3479 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3480 if (requireFullPermission) { 3481 mContext.enforceCallingOrSelfPermission( 3482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3483 } else { 3484 try { 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3487 } catch (SecurityException se) { 3488 mContext.enforceCallingOrSelfPermission( 3489 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3490 } 3491 } 3492 } 3493 } 3494 3495 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3496 if (callingUid == Process.SHELL_UID) { 3497 if (userHandle >= 0 3498 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3499 throw new SecurityException("Shell does not have permission to access user " 3500 + userHandle); 3501 } else if (userHandle < 0) { 3502 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3503 + Debug.getCallers(3)); 3504 } 3505 } 3506 } 3507 3508 private BasePermission findPermissionTreeLP(String permName) { 3509 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3510 if (permName.startsWith(bp.name) && 3511 permName.length() > bp.name.length() && 3512 permName.charAt(bp.name.length()) == '.') { 3513 return bp; 3514 } 3515 } 3516 return null; 3517 } 3518 3519 private BasePermission checkPermissionTreeLP(String permName) { 3520 if (permName != null) { 3521 BasePermission bp = findPermissionTreeLP(permName); 3522 if (bp != null) { 3523 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3524 return bp; 3525 } 3526 throw new SecurityException("Calling uid " 3527 + Binder.getCallingUid() 3528 + " is not allowed to add to permission tree " 3529 + bp.name + " owned by uid " + bp.uid); 3530 } 3531 } 3532 throw new SecurityException("No permission tree found for " + permName); 3533 } 3534 3535 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3536 if (s1 == null) { 3537 return s2 == null; 3538 } 3539 if (s2 == null) { 3540 return false; 3541 } 3542 if (s1.getClass() != s2.getClass()) { 3543 return false; 3544 } 3545 return s1.equals(s2); 3546 } 3547 3548 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3549 if (pi1.icon != pi2.icon) return false; 3550 if (pi1.logo != pi2.logo) return false; 3551 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3552 if (!compareStrings(pi1.name, pi2.name)) return false; 3553 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3554 // We'll take care of setting this one. 3555 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3556 // These are not currently stored in settings. 3557 //if (!compareStrings(pi1.group, pi2.group)) return false; 3558 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3559 //if (pi1.labelRes != pi2.labelRes) return false; 3560 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3561 return true; 3562 } 3563 3564 int permissionInfoFootprint(PermissionInfo info) { 3565 int size = info.name.length(); 3566 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3567 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3568 return size; 3569 } 3570 3571 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3572 int size = 0; 3573 for (BasePermission perm : mSettings.mPermissions.values()) { 3574 if (perm.uid == tree.uid) { 3575 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3576 } 3577 } 3578 return size; 3579 } 3580 3581 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3582 // We calculate the max size of permissions defined by this uid and throw 3583 // if that plus the size of 'info' would exceed our stated maximum. 3584 if (tree.uid != Process.SYSTEM_UID) { 3585 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3586 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3587 throw new SecurityException("Permission tree size cap exceeded"); 3588 } 3589 } 3590 } 3591 3592 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3593 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3594 throw new SecurityException("Label must be specified in permission"); 3595 } 3596 BasePermission tree = checkPermissionTreeLP(info.name); 3597 BasePermission bp = mSettings.mPermissions.get(info.name); 3598 boolean added = bp == null; 3599 boolean changed = true; 3600 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3601 if (added) { 3602 enforcePermissionCapLocked(info, tree); 3603 bp = new BasePermission(info.name, tree.sourcePackage, 3604 BasePermission.TYPE_DYNAMIC); 3605 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3606 throw new SecurityException( 3607 "Not allowed to modify non-dynamic permission " 3608 + info.name); 3609 } else { 3610 if (bp.protectionLevel == fixedLevel 3611 && bp.perm.owner.equals(tree.perm.owner) 3612 && bp.uid == tree.uid 3613 && comparePermissionInfos(bp.perm.info, info)) { 3614 changed = false; 3615 } 3616 } 3617 bp.protectionLevel = fixedLevel; 3618 info = new PermissionInfo(info); 3619 info.protectionLevel = fixedLevel; 3620 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3621 bp.perm.info.packageName = tree.perm.info.packageName; 3622 bp.uid = tree.uid; 3623 if (added) { 3624 mSettings.mPermissions.put(info.name, bp); 3625 } 3626 if (changed) { 3627 if (!async) { 3628 mSettings.writeLPr(); 3629 } else { 3630 scheduleWriteSettingsLocked(); 3631 } 3632 } 3633 return added; 3634 } 3635 3636 @Override 3637 public boolean addPermission(PermissionInfo info) { 3638 synchronized (mPackages) { 3639 return addPermissionLocked(info, false); 3640 } 3641 } 3642 3643 @Override 3644 public boolean addPermissionAsync(PermissionInfo info) { 3645 synchronized (mPackages) { 3646 return addPermissionLocked(info, true); 3647 } 3648 } 3649 3650 @Override 3651 public void removePermission(String name) { 3652 synchronized (mPackages) { 3653 checkPermissionTreeLP(name); 3654 BasePermission bp = mSettings.mPermissions.get(name); 3655 if (bp != null) { 3656 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3657 throw new SecurityException( 3658 "Not allowed to modify non-dynamic permission " 3659 + name); 3660 } 3661 mSettings.mPermissions.remove(name); 3662 mSettings.writeLPr(); 3663 } 3664 } 3665 } 3666 3667 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3668 BasePermission bp) { 3669 int index = pkg.requestedPermissions.indexOf(bp.name); 3670 if (index == -1) { 3671 throw new SecurityException("Package " + pkg.packageName 3672 + " has not requested permission " + bp.name); 3673 } 3674 if (!bp.isRuntime() && !bp.isDevelopment()) { 3675 throw new SecurityException("Permission " + bp.name 3676 + " is not a changeable permission type"); 3677 } 3678 } 3679 3680 @Override 3681 public void grantRuntimePermission(String packageName, String name, final int userId) { 3682 if (!sUserManager.exists(userId)) { 3683 Log.e(TAG, "No such user:" + userId); 3684 return; 3685 } 3686 3687 mContext.enforceCallingOrSelfPermission( 3688 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3689 "grantRuntimePermission"); 3690 3691 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3692 "grantRuntimePermission"); 3693 3694 final int uid; 3695 final SettingBase sb; 3696 3697 synchronized (mPackages) { 3698 final PackageParser.Package pkg = mPackages.get(packageName); 3699 if (pkg == null) { 3700 throw new IllegalArgumentException("Unknown package: " + packageName); 3701 } 3702 3703 final BasePermission bp = mSettings.mPermissions.get(name); 3704 if (bp == null) { 3705 throw new IllegalArgumentException("Unknown permission: " + name); 3706 } 3707 3708 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3709 3710 // If a permission review is required for legacy apps we represent 3711 // their permissions as always granted runtime ones since we need 3712 // to keep the review required permission flag per user while an 3713 // install permission's state is shared across all users. 3714 if (Build.PERMISSIONS_REVIEW_REQUIRED 3715 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3716 && bp.isRuntime()) { 3717 return; 3718 } 3719 3720 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3721 sb = (SettingBase) pkg.mExtras; 3722 if (sb == null) { 3723 throw new IllegalArgumentException("Unknown package: " + packageName); 3724 } 3725 3726 final PermissionsState permissionsState = sb.getPermissionsState(); 3727 3728 final int flags = permissionsState.getPermissionFlags(name, userId); 3729 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3730 throw new SecurityException("Cannot grant system fixed permission: " 3731 + name + " for package: " + packageName); 3732 } 3733 3734 if (bp.isDevelopment()) { 3735 // Development permissions must be handled specially, since they are not 3736 // normal runtime permissions. For now they apply to all users. 3737 if (permissionsState.grantInstallPermission(bp) != 3738 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3739 scheduleWriteSettingsLocked(); 3740 } 3741 return; 3742 } 3743 3744 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3745 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3746 return; 3747 } 3748 3749 final int result = permissionsState.grantRuntimePermission(bp, userId); 3750 switch (result) { 3751 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3752 return; 3753 } 3754 3755 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3756 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3757 mHandler.post(new Runnable() { 3758 @Override 3759 public void run() { 3760 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3761 } 3762 }); 3763 } 3764 break; 3765 } 3766 3767 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3768 3769 // Not critical if that is lost - app has to request again. 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 3773 // Only need to do this if user is initialized. Otherwise it's a new user 3774 // and there are no processes running as the user yet and there's no need 3775 // to make an expensive call to remount processes for the changed permissions. 3776 if (READ_EXTERNAL_STORAGE.equals(name) 3777 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3778 final long token = Binder.clearCallingIdentity(); 3779 try { 3780 if (sUserManager.isInitialized(userId)) { 3781 MountServiceInternal mountServiceInternal = LocalServices.getService( 3782 MountServiceInternal.class); 3783 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3784 } 3785 } finally { 3786 Binder.restoreCallingIdentity(token); 3787 } 3788 } 3789 } 3790 3791 @Override 3792 public void revokeRuntimePermission(String packageName, String name, int userId) { 3793 if (!sUserManager.exists(userId)) { 3794 Log.e(TAG, "No such user:" + userId); 3795 return; 3796 } 3797 3798 mContext.enforceCallingOrSelfPermission( 3799 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3800 "revokeRuntimePermission"); 3801 3802 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3803 "revokeRuntimePermission"); 3804 3805 final int appId; 3806 3807 synchronized (mPackages) { 3808 final PackageParser.Package pkg = mPackages.get(packageName); 3809 if (pkg == null) { 3810 throw new IllegalArgumentException("Unknown package: " + packageName); 3811 } 3812 3813 final BasePermission bp = mSettings.mPermissions.get(name); 3814 if (bp == null) { 3815 throw new IllegalArgumentException("Unknown permission: " + name); 3816 } 3817 3818 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3819 3820 // If a permission review is required for legacy apps we represent 3821 // their permissions as always granted runtime ones since we need 3822 // to keep the review required permission flag per user while an 3823 // install permission's state is shared across all users. 3824 if (Build.PERMISSIONS_REVIEW_REQUIRED 3825 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3826 && bp.isRuntime()) { 3827 return; 3828 } 3829 3830 SettingBase sb = (SettingBase) pkg.mExtras; 3831 if (sb == null) { 3832 throw new IllegalArgumentException("Unknown package: " + packageName); 3833 } 3834 3835 final PermissionsState permissionsState = sb.getPermissionsState(); 3836 3837 final int flags = permissionsState.getPermissionFlags(name, userId); 3838 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3839 throw new SecurityException("Cannot revoke system fixed permission: " 3840 + name + " for package: " + packageName); 3841 } 3842 3843 if (bp.isDevelopment()) { 3844 // Development permissions must be handled specially, since they are not 3845 // normal runtime permissions. For now they apply to all users. 3846 if (permissionsState.revokeInstallPermission(bp) != 3847 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3848 scheduleWriteSettingsLocked(); 3849 } 3850 return; 3851 } 3852 3853 if (permissionsState.revokeRuntimePermission(bp, userId) == 3854 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3855 return; 3856 } 3857 3858 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3859 3860 // Critical, after this call app should never have the permission. 3861 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3862 3863 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3864 } 3865 3866 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3867 } 3868 3869 @Override 3870 public void resetRuntimePermissions() { 3871 mContext.enforceCallingOrSelfPermission( 3872 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3873 "revokeRuntimePermission"); 3874 3875 int callingUid = Binder.getCallingUid(); 3876 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3877 mContext.enforceCallingOrSelfPermission( 3878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3879 "resetRuntimePermissions"); 3880 } 3881 3882 synchronized (mPackages) { 3883 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3884 for (int userId : UserManagerService.getInstance().getUserIds()) { 3885 final int packageCount = mPackages.size(); 3886 for (int i = 0; i < packageCount; i++) { 3887 PackageParser.Package pkg = mPackages.valueAt(i); 3888 if (!(pkg.mExtras instanceof PackageSetting)) { 3889 continue; 3890 } 3891 PackageSetting ps = (PackageSetting) pkg.mExtras; 3892 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3893 } 3894 } 3895 } 3896 } 3897 3898 @Override 3899 public int getPermissionFlags(String name, String packageName, int userId) { 3900 if (!sUserManager.exists(userId)) { 3901 return 0; 3902 } 3903 3904 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3905 3906 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3907 "getPermissionFlags"); 3908 3909 synchronized (mPackages) { 3910 final PackageParser.Package pkg = mPackages.get(packageName); 3911 if (pkg == null) { 3912 throw new IllegalArgumentException("Unknown package: " + packageName); 3913 } 3914 3915 final BasePermission bp = mSettings.mPermissions.get(name); 3916 if (bp == null) { 3917 throw new IllegalArgumentException("Unknown permission: " + name); 3918 } 3919 3920 SettingBase sb = (SettingBase) pkg.mExtras; 3921 if (sb == null) { 3922 throw new IllegalArgumentException("Unknown package: " + packageName); 3923 } 3924 3925 PermissionsState permissionsState = sb.getPermissionsState(); 3926 return permissionsState.getPermissionFlags(name, userId); 3927 } 3928 } 3929 3930 @Override 3931 public void updatePermissionFlags(String name, String packageName, int flagMask, 3932 int flagValues, int userId) { 3933 if (!sUserManager.exists(userId)) { 3934 return; 3935 } 3936 3937 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3938 3939 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3940 "updatePermissionFlags"); 3941 3942 // Only the system can change these flags and nothing else. 3943 if (getCallingUid() != Process.SYSTEM_UID) { 3944 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3945 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3946 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3947 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3948 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3949 } 3950 3951 synchronized (mPackages) { 3952 final PackageParser.Package pkg = mPackages.get(packageName); 3953 if (pkg == null) { 3954 throw new IllegalArgumentException("Unknown package: " + packageName); 3955 } 3956 3957 final BasePermission bp = mSettings.mPermissions.get(name); 3958 if (bp == null) { 3959 throw new IllegalArgumentException("Unknown permission: " + name); 3960 } 3961 3962 SettingBase sb = (SettingBase) pkg.mExtras; 3963 if (sb == null) { 3964 throw new IllegalArgumentException("Unknown package: " + packageName); 3965 } 3966 3967 PermissionsState permissionsState = sb.getPermissionsState(); 3968 3969 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3970 3971 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3972 // Install and runtime permissions are stored in different places, 3973 // so figure out what permission changed and persist the change. 3974 if (permissionsState.getInstallPermissionState(name) != null) { 3975 scheduleWriteSettingsLocked(); 3976 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3977 || hadState) { 3978 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3979 } 3980 } 3981 } 3982 } 3983 3984 /** 3985 * Update the permission flags for all packages and runtime permissions of a user in order 3986 * to allow device or profile owner to remove POLICY_FIXED. 3987 */ 3988 @Override 3989 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3990 if (!sUserManager.exists(userId)) { 3991 return; 3992 } 3993 3994 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3995 3996 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3997 "updatePermissionFlagsForAllApps"); 3998 3999 // Only the system can change system fixed flags. 4000 if (getCallingUid() != Process.SYSTEM_UID) { 4001 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4002 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4003 } 4004 4005 synchronized (mPackages) { 4006 boolean changed = false; 4007 final int packageCount = mPackages.size(); 4008 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4009 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4010 SettingBase sb = (SettingBase) pkg.mExtras; 4011 if (sb == null) { 4012 continue; 4013 } 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4016 userId, flagMask, flagValues); 4017 } 4018 if (changed) { 4019 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4020 } 4021 } 4022 } 4023 4024 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4025 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4026 != PackageManager.PERMISSION_GRANTED 4027 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4028 != PackageManager.PERMISSION_GRANTED) { 4029 throw new SecurityException(message + " requires " 4030 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4031 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4032 } 4033 } 4034 4035 @Override 4036 public boolean shouldShowRequestPermissionRationale(String permissionName, 4037 String packageName, int userId) { 4038 if (UserHandle.getCallingUserId() != userId) { 4039 mContext.enforceCallingPermission( 4040 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4041 "canShowRequestPermissionRationale for user " + userId); 4042 } 4043 4044 final int uid = getPackageUid(packageName, userId); 4045 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4046 return false; 4047 } 4048 4049 if (checkPermission(permissionName, packageName, userId) 4050 == PackageManager.PERMISSION_GRANTED) { 4051 return false; 4052 } 4053 4054 final int flags; 4055 4056 final long identity = Binder.clearCallingIdentity(); 4057 try { 4058 flags = getPermissionFlags(permissionName, 4059 packageName, userId); 4060 } finally { 4061 Binder.restoreCallingIdentity(identity); 4062 } 4063 4064 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4065 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4066 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4067 4068 if ((flags & fixedFlags) != 0) { 4069 return false; 4070 } 4071 4072 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4073 } 4074 4075 @Override 4076 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4077 mContext.enforceCallingOrSelfPermission( 4078 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4079 "addOnPermissionsChangeListener"); 4080 4081 synchronized (mPackages) { 4082 mOnPermissionChangeListeners.addListenerLocked(listener); 4083 } 4084 } 4085 4086 @Override 4087 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4088 synchronized (mPackages) { 4089 mOnPermissionChangeListeners.removeListenerLocked(listener); 4090 } 4091 } 4092 4093 @Override 4094 public boolean isProtectedBroadcast(String actionName) { 4095 synchronized (mPackages) { 4096 return mProtectedBroadcasts.contains(actionName); 4097 } 4098 } 4099 4100 @Override 4101 public int checkSignatures(String pkg1, String pkg2) { 4102 synchronized (mPackages) { 4103 final PackageParser.Package p1 = mPackages.get(pkg1); 4104 final PackageParser.Package p2 = mPackages.get(pkg2); 4105 if (p1 == null || p1.mExtras == null 4106 || p2 == null || p2.mExtras == null) { 4107 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4108 } 4109 return compareSignatures(p1.mSignatures, p2.mSignatures); 4110 } 4111 } 4112 4113 @Override 4114 public int checkUidSignatures(int uid1, int uid2) { 4115 // Map to base uids. 4116 uid1 = UserHandle.getAppId(uid1); 4117 uid2 = UserHandle.getAppId(uid2); 4118 // reader 4119 synchronized (mPackages) { 4120 Signature[] s1; 4121 Signature[] s2; 4122 Object obj = mSettings.getUserIdLPr(uid1); 4123 if (obj != null) { 4124 if (obj instanceof SharedUserSetting) { 4125 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4126 } else if (obj instanceof PackageSetting) { 4127 s1 = ((PackageSetting)obj).signatures.mSignatures; 4128 } else { 4129 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4130 } 4131 } else { 4132 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4133 } 4134 obj = mSettings.getUserIdLPr(uid2); 4135 if (obj != null) { 4136 if (obj instanceof SharedUserSetting) { 4137 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4138 } else if (obj instanceof PackageSetting) { 4139 s2 = ((PackageSetting)obj).signatures.mSignatures; 4140 } else { 4141 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4142 } 4143 } else { 4144 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4145 } 4146 return compareSignatures(s1, s2); 4147 } 4148 } 4149 4150 private void killUid(int appId, int userId, String reason) { 4151 final long identity = Binder.clearCallingIdentity(); 4152 try { 4153 IActivityManager am = ActivityManagerNative.getDefault(); 4154 if (am != null) { 4155 try { 4156 am.killUid(appId, userId, reason); 4157 } catch (RemoteException e) { 4158 /* ignore - same process */ 4159 } 4160 } 4161 } finally { 4162 Binder.restoreCallingIdentity(identity); 4163 } 4164 } 4165 4166 /** 4167 * Compares two sets of signatures. Returns: 4168 * <br /> 4169 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4170 * <br /> 4171 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4176 * <br /> 4177 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4178 */ 4179 static int compareSignatures(Signature[] s1, Signature[] s2) { 4180 if (s1 == null) { 4181 return s2 == null 4182 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4183 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4184 } 4185 4186 if (s2 == null) { 4187 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4188 } 4189 4190 if (s1.length != s2.length) { 4191 return PackageManager.SIGNATURE_NO_MATCH; 4192 } 4193 4194 // Since both signature sets are of size 1, we can compare without HashSets. 4195 if (s1.length == 1) { 4196 return s1[0].equals(s2[0]) ? 4197 PackageManager.SIGNATURE_MATCH : 4198 PackageManager.SIGNATURE_NO_MATCH; 4199 } 4200 4201 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4202 for (Signature sig : s1) { 4203 set1.add(sig); 4204 } 4205 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4206 for (Signature sig : s2) { 4207 set2.add(sig); 4208 } 4209 // Make sure s2 contains all signatures in s1. 4210 if (set1.equals(set2)) { 4211 return PackageManager.SIGNATURE_MATCH; 4212 } 4213 return PackageManager.SIGNATURE_NO_MATCH; 4214 } 4215 4216 /** 4217 * If the database version for this type of package (internal storage or 4218 * external storage) is less than the version where package signatures 4219 * were updated, return true. 4220 */ 4221 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4222 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4223 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4224 } 4225 4226 /** 4227 * Used for backward compatibility to make sure any packages with 4228 * certificate chains get upgraded to the new style. {@code existingSigs} 4229 * will be in the old format (since they were stored on disk from before the 4230 * system upgrade) and {@code scannedSigs} will be in the newer format. 4231 */ 4232 private int compareSignaturesCompat(PackageSignatures existingSigs, 4233 PackageParser.Package scannedPkg) { 4234 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4235 return PackageManager.SIGNATURE_NO_MATCH; 4236 } 4237 4238 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4239 for (Signature sig : existingSigs.mSignatures) { 4240 existingSet.add(sig); 4241 } 4242 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4243 for (Signature sig : scannedPkg.mSignatures) { 4244 try { 4245 Signature[] chainSignatures = sig.getChainSignatures(); 4246 for (Signature chainSig : chainSignatures) { 4247 scannedCompatSet.add(chainSig); 4248 } 4249 } catch (CertificateEncodingException e) { 4250 scannedCompatSet.add(sig); 4251 } 4252 } 4253 /* 4254 * Make sure the expanded scanned set contains all signatures in the 4255 * existing one. 4256 */ 4257 if (scannedCompatSet.equals(existingSet)) { 4258 // Migrate the old signatures to the new scheme. 4259 existingSigs.assignSignatures(scannedPkg.mSignatures); 4260 // The new KeySets will be re-added later in the scanning process. 4261 synchronized (mPackages) { 4262 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4263 } 4264 return PackageManager.SIGNATURE_MATCH; 4265 } 4266 return PackageManager.SIGNATURE_NO_MATCH; 4267 } 4268 4269 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4270 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4271 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4272 } 4273 4274 private int compareSignaturesRecover(PackageSignatures existingSigs, 4275 PackageParser.Package scannedPkg) { 4276 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4277 return PackageManager.SIGNATURE_NO_MATCH; 4278 } 4279 4280 String msg = null; 4281 try { 4282 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4283 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4284 + scannedPkg.packageName); 4285 return PackageManager.SIGNATURE_MATCH; 4286 } 4287 } catch (CertificateException e) { 4288 msg = e.getMessage(); 4289 } 4290 4291 logCriticalInfo(Log.INFO, 4292 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4293 return PackageManager.SIGNATURE_NO_MATCH; 4294 } 4295 4296 @Override 4297 public String[] getPackagesForUid(int uid) { 4298 uid = UserHandle.getAppId(uid); 4299 // reader 4300 synchronized (mPackages) { 4301 Object obj = mSettings.getUserIdLPr(uid); 4302 if (obj instanceof SharedUserSetting) { 4303 final SharedUserSetting sus = (SharedUserSetting) obj; 4304 final int N = sus.packages.size(); 4305 final String[] res = new String[N]; 4306 final Iterator<PackageSetting> it = sus.packages.iterator(); 4307 int i = 0; 4308 while (it.hasNext()) { 4309 res[i++] = it.next().name; 4310 } 4311 return res; 4312 } else if (obj instanceof PackageSetting) { 4313 final PackageSetting ps = (PackageSetting) obj; 4314 return new String[] { ps.name }; 4315 } 4316 } 4317 return null; 4318 } 4319 4320 @Override 4321 public String getNameForUid(int uid) { 4322 // reader 4323 synchronized (mPackages) { 4324 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4325 if (obj instanceof SharedUserSetting) { 4326 final SharedUserSetting sus = (SharedUserSetting) obj; 4327 return sus.name + ":" + sus.userId; 4328 } else if (obj instanceof PackageSetting) { 4329 final PackageSetting ps = (PackageSetting) obj; 4330 return ps.name; 4331 } 4332 } 4333 return null; 4334 } 4335 4336 @Override 4337 public int getUidForSharedUser(String sharedUserName) { 4338 if(sharedUserName == null) { 4339 return -1; 4340 } 4341 // reader 4342 synchronized (mPackages) { 4343 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4344 if (suid == null) { 4345 return -1; 4346 } 4347 return suid.userId; 4348 } 4349 } 4350 4351 @Override 4352 public int getFlagsForUid(int uid) { 4353 synchronized (mPackages) { 4354 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4355 if (obj instanceof SharedUserSetting) { 4356 final SharedUserSetting sus = (SharedUserSetting) obj; 4357 return sus.pkgFlags; 4358 } else if (obj instanceof PackageSetting) { 4359 final PackageSetting ps = (PackageSetting) obj; 4360 return ps.pkgFlags; 4361 } 4362 } 4363 return 0; 4364 } 4365 4366 @Override 4367 public int getPrivateFlagsForUid(int uid) { 4368 synchronized (mPackages) { 4369 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4370 if (obj instanceof SharedUserSetting) { 4371 final SharedUserSetting sus = (SharedUserSetting) obj; 4372 return sus.pkgPrivateFlags; 4373 } else if (obj instanceof PackageSetting) { 4374 final PackageSetting ps = (PackageSetting) obj; 4375 return ps.pkgPrivateFlags; 4376 } 4377 } 4378 return 0; 4379 } 4380 4381 @Override 4382 public boolean isUidPrivileged(int uid) { 4383 uid = UserHandle.getAppId(uid); 4384 // reader 4385 synchronized (mPackages) { 4386 Object obj = mSettings.getUserIdLPr(uid); 4387 if (obj instanceof SharedUserSetting) { 4388 final SharedUserSetting sus = (SharedUserSetting) obj; 4389 final Iterator<PackageSetting> it = sus.packages.iterator(); 4390 while (it.hasNext()) { 4391 if (it.next().isPrivileged()) { 4392 return true; 4393 } 4394 } 4395 } else if (obj instanceof PackageSetting) { 4396 final PackageSetting ps = (PackageSetting) obj; 4397 return ps.isPrivileged(); 4398 } 4399 } 4400 return false; 4401 } 4402 4403 @Override 4404 public String[] getAppOpPermissionPackages(String permissionName) { 4405 synchronized (mPackages) { 4406 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4407 if (pkgs == null) { 4408 return null; 4409 } 4410 return pkgs.toArray(new String[pkgs.size()]); 4411 } 4412 } 4413 4414 @Override 4415 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4416 int flags, int userId) { 4417 if (!sUserManager.exists(userId)) return null; 4418 flags = augmentFlagsForUser(flags, userId); 4419 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4420 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4421 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4422 } 4423 4424 @Override 4425 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4426 IntentFilter filter, int match, ComponentName activity) { 4427 final int userId = UserHandle.getCallingUserId(); 4428 if (DEBUG_PREFERRED) { 4429 Log.v(TAG, "setLastChosenActivity intent=" + intent 4430 + " resolvedType=" + resolvedType 4431 + " flags=" + flags 4432 + " filter=" + filter 4433 + " match=" + match 4434 + " activity=" + activity); 4435 filter.dump(new PrintStreamPrinter(System.out), " "); 4436 } 4437 intent.setComponent(null); 4438 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4439 // Find any earlier preferred or last chosen entries and nuke them 4440 findPreferredActivity(intent, resolvedType, 4441 flags, query, 0, false, true, false, userId); 4442 // Add the new activity as the last chosen for this filter 4443 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4444 "Setting last chosen"); 4445 } 4446 4447 @Override 4448 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4449 final int userId = UserHandle.getCallingUserId(); 4450 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4451 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4452 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4453 false, false, false, userId); 4454 } 4455 4456 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4457 MessageDigest digest = null; 4458 try { 4459 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4460 } catch (NoSuchAlgorithmException e) { 4461 // If we can't create a digest, ignore ephemeral apps. 4462 return false; 4463 } 4464 4465 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4466 final byte[] digestBytes = digest.digest(hostBytes); 4467 int shaPrefix = 4468 digestBytes[0] << 24 4469 | digestBytes[1] << 16 4470 | digestBytes[2] << 8 4471 | digestBytes[3] << 0; 4472 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4473 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4474 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4475 // No hash prefix match; there are no ephemeral apps for this domain. 4476 return false; 4477 } 4478 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4479 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4480 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4481 continue; 4482 } 4483 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4484 // No filters; this should never happen. 4485 if (filters.isEmpty()) { 4486 continue; 4487 } 4488 // We have a domain match; resolve the filters to see if anything matches. 4489 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4490 for (int j = filters.size() - 1; j >= 0; --j) { 4491 ephemeralResolver.addFilter(filters.get(j)); 4492 } 4493 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4494 intent, resolvedType, false /*defaultOnly*/, userId); 4495 return !ephemeralResolveList.isEmpty(); 4496 } 4497 // Hash or filter mis-match; no ephemeral apps for this domain. 4498 return false; 4499 } 4500 4501 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4502 int flags, List<ResolveInfo> query, int userId) { 4503 final boolean isWebUri = hasWebURI(intent); 4504 // Check whether or not an ephemeral app exists to handle the URI. 4505 if (isWebUri && mEphemeralResolverConnection != null) { 4506 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4507 boolean hasAlwaysHandler = false; 4508 synchronized (mPackages) { 4509 final int count = query.size(); 4510 for (int n=0; n<count; n++) { 4511 ResolveInfo info = query.get(n); 4512 String packageName = info.activityInfo.packageName; 4513 PackageSetting ps = mSettings.mPackages.get(packageName); 4514 if (ps != null) { 4515 // Try to get the status from User settings first 4516 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4517 int status = (int) (packedStatus >> 32); 4518 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4519 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4520 hasAlwaysHandler = true; 4521 break; 4522 } 4523 } 4524 } 4525 } 4526 4527 // Only consider installing an ephemeral app if there isn't already a verified handler. 4528 // We've determined that there's an ephemeral app available for the URI, ignore any 4529 // ResolveInfo's and just return the ephemeral installer 4530 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4531 if (DEBUG_EPHEMERAL) { 4532 Slog.v(TAG, "Resolving to the ephemeral installer"); 4533 } 4534 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4535 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4536 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4537 // make a deep copy of the applicationInfo 4538 ri.activityInfo.applicationInfo = new ApplicationInfo( 4539 ri.activityInfo.applicationInfo); 4540 if (userId != 0) { 4541 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4542 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4543 } 4544 return ri; 4545 } 4546 } 4547 if (query != null) { 4548 final int N = query.size(); 4549 if (N == 1) { 4550 return query.get(0); 4551 } else if (N > 1) { 4552 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4553 // If there is more than one activity with the same priority, 4554 // then let the user decide between them. 4555 ResolveInfo r0 = query.get(0); 4556 ResolveInfo r1 = query.get(1); 4557 if (DEBUG_INTENT_MATCHING || debug) { 4558 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4559 + r1.activityInfo.name + "=" + r1.priority); 4560 } 4561 // If the first activity has a higher priority, or a different 4562 // default, then it is always desireable to pick it. 4563 if (r0.priority != r1.priority 4564 || r0.preferredOrder != r1.preferredOrder 4565 || r0.isDefault != r1.isDefault) { 4566 return query.get(0); 4567 } 4568 // If we have saved a preference for a preferred activity for 4569 // this Intent, use that. 4570 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4571 flags, query, r0.priority, true, false, debug, userId); 4572 if (ri != null) { 4573 return ri; 4574 } 4575 ri = new ResolveInfo(mResolveInfo); 4576 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4577 ri.activityInfo.applicationInfo = new ApplicationInfo( 4578 ri.activityInfo.applicationInfo); 4579 if (userId != 0) { 4580 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4581 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4582 } 4583 // Make sure that the resolver is displayable in car mode 4584 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4585 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4586 return ri; 4587 } 4588 } 4589 return null; 4590 } 4591 4592 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4593 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4594 final int N = query.size(); 4595 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4596 .get(userId); 4597 // Get the list of persistent preferred activities that handle the intent 4598 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4599 List<PersistentPreferredActivity> pprefs = ppir != null 4600 ? ppir.queryIntent(intent, resolvedType, 4601 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4602 : null; 4603 if (pprefs != null && pprefs.size() > 0) { 4604 final int M = pprefs.size(); 4605 for (int i=0; i<M; i++) { 4606 final PersistentPreferredActivity ppa = pprefs.get(i); 4607 if (DEBUG_PREFERRED || debug) { 4608 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4609 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4610 + "\n component=" + ppa.mComponent); 4611 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4612 } 4613 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4614 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4615 if (DEBUG_PREFERRED || debug) { 4616 Slog.v(TAG, "Found persistent preferred activity:"); 4617 if (ai != null) { 4618 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4619 } else { 4620 Slog.v(TAG, " null"); 4621 } 4622 } 4623 if (ai == null) { 4624 // This previously registered persistent preferred activity 4625 // component is no longer known. Ignore it and do NOT remove it. 4626 continue; 4627 } 4628 for (int j=0; j<N; j++) { 4629 final ResolveInfo ri = query.get(j); 4630 if (!ri.activityInfo.applicationInfo.packageName 4631 .equals(ai.applicationInfo.packageName)) { 4632 continue; 4633 } 4634 if (!ri.activityInfo.name.equals(ai.name)) { 4635 continue; 4636 } 4637 // Found a persistent preference that can handle the intent. 4638 if (DEBUG_PREFERRED || debug) { 4639 Slog.v(TAG, "Returning persistent preferred activity: " + 4640 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4641 } 4642 return ri; 4643 } 4644 } 4645 } 4646 return null; 4647 } 4648 4649 // TODO: handle preferred activities missing while user has amnesia 4650 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4651 List<ResolveInfo> query, int priority, boolean always, 4652 boolean removeMatches, boolean debug, int userId) { 4653 if (!sUserManager.exists(userId)) return null; 4654 flags = augmentFlagsForUser(flags, userId); 4655 // writer 4656 synchronized (mPackages) { 4657 if (intent.getSelector() != null) { 4658 intent = intent.getSelector(); 4659 } 4660 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4661 4662 // Try to find a matching persistent preferred activity. 4663 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4664 debug, userId); 4665 4666 // If a persistent preferred activity matched, use it. 4667 if (pri != null) { 4668 return pri; 4669 } 4670 4671 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4672 // Get the list of preferred activities that handle the intent 4673 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4674 List<PreferredActivity> prefs = pir != null 4675 ? pir.queryIntent(intent, resolvedType, 4676 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4677 : null; 4678 if (prefs != null && prefs.size() > 0) { 4679 boolean changed = false; 4680 try { 4681 // First figure out how good the original match set is. 4682 // We will only allow preferred activities that came 4683 // from the same match quality. 4684 int match = 0; 4685 4686 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4687 4688 final int N = query.size(); 4689 for (int j=0; j<N; j++) { 4690 final ResolveInfo ri = query.get(j); 4691 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4692 + ": 0x" + Integer.toHexString(match)); 4693 if (ri.match > match) { 4694 match = ri.match; 4695 } 4696 } 4697 4698 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4699 + Integer.toHexString(match)); 4700 4701 match &= IntentFilter.MATCH_CATEGORY_MASK; 4702 final int M = prefs.size(); 4703 for (int i=0; i<M; i++) { 4704 final PreferredActivity pa = prefs.get(i); 4705 if (DEBUG_PREFERRED || debug) { 4706 Slog.v(TAG, "Checking PreferredActivity ds=" 4707 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4708 + "\n component=" + pa.mPref.mComponent); 4709 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4710 } 4711 if (pa.mPref.mMatch != match) { 4712 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4713 + Integer.toHexString(pa.mPref.mMatch)); 4714 continue; 4715 } 4716 // If it's not an "always" type preferred activity and that's what we're 4717 // looking for, skip it. 4718 if (always && !pa.mPref.mAlways) { 4719 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4720 continue; 4721 } 4722 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4723 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4724 if (DEBUG_PREFERRED || debug) { 4725 Slog.v(TAG, "Found preferred activity:"); 4726 if (ai != null) { 4727 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4728 } else { 4729 Slog.v(TAG, " null"); 4730 } 4731 } 4732 if (ai == null) { 4733 // This previously registered preferred activity 4734 // component is no longer known. Most likely an update 4735 // to the app was installed and in the new version this 4736 // component no longer exists. Clean it up by removing 4737 // it from the preferred activities list, and skip it. 4738 Slog.w(TAG, "Removing dangling preferred activity: " 4739 + pa.mPref.mComponent); 4740 pir.removeFilter(pa); 4741 changed = true; 4742 continue; 4743 } 4744 for (int j=0; j<N; j++) { 4745 final ResolveInfo ri = query.get(j); 4746 if (!ri.activityInfo.applicationInfo.packageName 4747 .equals(ai.applicationInfo.packageName)) { 4748 continue; 4749 } 4750 if (!ri.activityInfo.name.equals(ai.name)) { 4751 continue; 4752 } 4753 4754 if (removeMatches) { 4755 pir.removeFilter(pa); 4756 changed = true; 4757 if (DEBUG_PREFERRED) { 4758 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4759 } 4760 break; 4761 } 4762 4763 // Okay we found a previously set preferred or last chosen app. 4764 // If the result set is different from when this 4765 // was created, we need to clear it and re-ask the 4766 // user their preference, if we're looking for an "always" type entry. 4767 if (always && !pa.mPref.sameSet(query)) { 4768 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4769 + intent + " type " + resolvedType); 4770 if (DEBUG_PREFERRED) { 4771 Slog.v(TAG, "Removing preferred activity since set changed " 4772 + pa.mPref.mComponent); 4773 } 4774 pir.removeFilter(pa); 4775 // Re-add the filter as a "last chosen" entry (!always) 4776 PreferredActivity lastChosen = new PreferredActivity( 4777 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4778 pir.addFilter(lastChosen); 4779 changed = true; 4780 return null; 4781 } 4782 4783 // Yay! Either the set matched or we're looking for the last chosen 4784 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4785 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4786 return ri; 4787 } 4788 } 4789 } finally { 4790 if (changed) { 4791 if (DEBUG_PREFERRED) { 4792 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4793 } 4794 scheduleWritePackageRestrictionsLocked(userId); 4795 } 4796 } 4797 } 4798 } 4799 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4800 return null; 4801 } 4802 4803 /* 4804 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4805 */ 4806 @Override 4807 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4808 int targetUserId) { 4809 mContext.enforceCallingOrSelfPermission( 4810 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4811 List<CrossProfileIntentFilter> matches = 4812 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4813 if (matches != null) { 4814 int size = matches.size(); 4815 for (int i = 0; i < size; i++) { 4816 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4817 } 4818 } 4819 if (hasWebURI(intent)) { 4820 // cross-profile app linking works only towards the parent. 4821 final UserInfo parent = getProfileParent(sourceUserId); 4822 synchronized(mPackages) { 4823 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4824 intent, resolvedType, 0, sourceUserId, parent.id); 4825 return xpDomainInfo != null; 4826 } 4827 } 4828 return false; 4829 } 4830 4831 private UserInfo getProfileParent(int userId) { 4832 final long identity = Binder.clearCallingIdentity(); 4833 try { 4834 return sUserManager.getProfileParent(userId); 4835 } finally { 4836 Binder.restoreCallingIdentity(identity); 4837 } 4838 } 4839 4840 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4841 String resolvedType, int userId) { 4842 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4843 if (resolver != null) { 4844 return resolver.queryIntent(intent, resolvedType, false, userId); 4845 } 4846 return null; 4847 } 4848 4849 @Override 4850 public List<ResolveInfo> queryIntentActivities(Intent intent, 4851 String resolvedType, int flags, int userId) { 4852 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4853 flags = augmentFlagsForUser(flags, userId); 4854 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4855 ComponentName comp = intent.getComponent(); 4856 if (comp == null) { 4857 if (intent.getSelector() != null) { 4858 intent = intent.getSelector(); 4859 comp = intent.getComponent(); 4860 } 4861 } 4862 4863 if (comp != null) { 4864 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4865 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4866 if (ai != null) { 4867 final ResolveInfo ri = new ResolveInfo(); 4868 ri.activityInfo = ai; 4869 list.add(ri); 4870 } 4871 return list; 4872 } 4873 4874 // reader 4875 synchronized (mPackages) { 4876 final String pkgName = intent.getPackage(); 4877 if (pkgName == null) { 4878 List<CrossProfileIntentFilter> matchingFilters = 4879 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4880 // Check for results that need to skip the current profile. 4881 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4882 resolvedType, flags, userId); 4883 if (xpResolveInfo != null) { 4884 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4885 result.add(xpResolveInfo); 4886 return filterIfNotSystemUser(result, userId); 4887 } 4888 4889 // Check for results in the current profile. 4890 List<ResolveInfo> result = mActivities.queryIntent( 4891 intent, resolvedType, flags, userId); 4892 4893 // Check for cross profile results. 4894 xpResolveInfo = queryCrossProfileIntents( 4895 matchingFilters, intent, resolvedType, flags, userId); 4896 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4897 result.add(xpResolveInfo); 4898 Collections.sort(result, mResolvePrioritySorter); 4899 } 4900 result = filterIfNotSystemUser(result, userId); 4901 if (hasWebURI(intent)) { 4902 CrossProfileDomainInfo xpDomainInfo = null; 4903 final UserInfo parent = getProfileParent(userId); 4904 if (parent != null) { 4905 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4906 flags, userId, parent.id); 4907 } 4908 if (xpDomainInfo != null) { 4909 if (xpResolveInfo != null) { 4910 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4911 // in the result. 4912 result.remove(xpResolveInfo); 4913 } 4914 if (result.size() == 0) { 4915 result.add(xpDomainInfo.resolveInfo); 4916 return result; 4917 } 4918 } else if (result.size() <= 1) { 4919 return result; 4920 } 4921 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4922 xpDomainInfo, userId); 4923 Collections.sort(result, mResolvePrioritySorter); 4924 } 4925 return result; 4926 } 4927 final PackageParser.Package pkg = mPackages.get(pkgName); 4928 if (pkg != null) { 4929 return filterIfNotSystemUser( 4930 mActivities.queryIntentForPackage( 4931 intent, resolvedType, flags, pkg.activities, userId), 4932 userId); 4933 } 4934 return new ArrayList<ResolveInfo>(); 4935 } 4936 } 4937 4938 private static class CrossProfileDomainInfo { 4939 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4940 ResolveInfo resolveInfo; 4941 /* Best domain verification status of the activities found in the other profile */ 4942 int bestDomainVerificationStatus; 4943 } 4944 4945 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4946 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4947 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4948 sourceUserId)) { 4949 return null; 4950 } 4951 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4952 resolvedType, flags, parentUserId); 4953 4954 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4955 return null; 4956 } 4957 CrossProfileDomainInfo result = null; 4958 int size = resultTargetUser.size(); 4959 for (int i = 0; i < size; i++) { 4960 ResolveInfo riTargetUser = resultTargetUser.get(i); 4961 // Intent filter verification is only for filters that specify a host. So don't return 4962 // those that handle all web uris. 4963 if (riTargetUser.handleAllWebDataURI) { 4964 continue; 4965 } 4966 String packageName = riTargetUser.activityInfo.packageName; 4967 PackageSetting ps = mSettings.mPackages.get(packageName); 4968 if (ps == null) { 4969 continue; 4970 } 4971 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4972 int status = (int)(verificationState >> 32); 4973 if (result == null) { 4974 result = new CrossProfileDomainInfo(); 4975 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4976 sourceUserId, parentUserId); 4977 result.bestDomainVerificationStatus = status; 4978 } else { 4979 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4980 result.bestDomainVerificationStatus); 4981 } 4982 } 4983 // Don't consider matches with status NEVER across profiles. 4984 if (result != null && result.bestDomainVerificationStatus 4985 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4986 return null; 4987 } 4988 return result; 4989 } 4990 4991 /** 4992 * Verification statuses are ordered from the worse to the best, except for 4993 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4994 */ 4995 private int bestDomainVerificationStatus(int status1, int status2) { 4996 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4997 return status2; 4998 } 4999 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5000 return status1; 5001 } 5002 return (int) MathUtils.max(status1, status2); 5003 } 5004 5005 private boolean isUserEnabled(int userId) { 5006 long callingId = Binder.clearCallingIdentity(); 5007 try { 5008 UserInfo userInfo = sUserManager.getUserInfo(userId); 5009 return userInfo != null && userInfo.isEnabled(); 5010 } finally { 5011 Binder.restoreCallingIdentity(callingId); 5012 } 5013 } 5014 5015 /** 5016 * Filter out activities with systemUserOnly flag set, when current user is not System. 5017 * 5018 * @return filtered list 5019 */ 5020 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5021 if (userId == UserHandle.USER_SYSTEM) { 5022 return resolveInfos; 5023 } 5024 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5025 ResolveInfo info = resolveInfos.get(i); 5026 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5027 resolveInfos.remove(i); 5028 } 5029 } 5030 return resolveInfos; 5031 } 5032 5033 private static boolean hasWebURI(Intent intent) { 5034 if (intent.getData() == null) { 5035 return false; 5036 } 5037 final String scheme = intent.getScheme(); 5038 if (TextUtils.isEmpty(scheme)) { 5039 return false; 5040 } 5041 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5042 } 5043 5044 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5045 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5046 int userId) { 5047 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5048 5049 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5050 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5051 candidates.size()); 5052 } 5053 5054 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5055 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5056 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5057 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5058 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5059 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5060 5061 synchronized (mPackages) { 5062 final int count = candidates.size(); 5063 // First, try to use linked apps. Partition the candidates into four lists: 5064 // one for the final results, one for the "do not use ever", one for "undefined status" 5065 // and finally one for "browser app type". 5066 for (int n=0; n<count; n++) { 5067 ResolveInfo info = candidates.get(n); 5068 String packageName = info.activityInfo.packageName; 5069 PackageSetting ps = mSettings.mPackages.get(packageName); 5070 if (ps != null) { 5071 // Add to the special match all list (Browser use case) 5072 if (info.handleAllWebDataURI) { 5073 matchAllList.add(info); 5074 continue; 5075 } 5076 // Try to get the status from User settings first 5077 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5078 int status = (int)(packedStatus >> 32); 5079 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5080 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5081 if (DEBUG_DOMAIN_VERIFICATION) { 5082 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5083 + " : linkgen=" + linkGeneration); 5084 } 5085 // Use link-enabled generation as preferredOrder, i.e. 5086 // prefer newly-enabled over earlier-enabled. 5087 info.preferredOrder = linkGeneration; 5088 alwaysList.add(info); 5089 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5090 if (DEBUG_DOMAIN_VERIFICATION) { 5091 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5092 } 5093 neverList.add(info); 5094 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5095 if (DEBUG_DOMAIN_VERIFICATION) { 5096 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5097 } 5098 alwaysAskList.add(info); 5099 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5100 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5101 if (DEBUG_DOMAIN_VERIFICATION) { 5102 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5103 } 5104 undefinedList.add(info); 5105 } 5106 } 5107 } 5108 5109 // We'll want to include browser possibilities in a few cases 5110 boolean includeBrowser = false; 5111 5112 // First try to add the "always" resolution(s) for the current user, if any 5113 if (alwaysList.size() > 0) { 5114 result.addAll(alwaysList); 5115 } else { 5116 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5117 result.addAll(undefinedList); 5118 // Maybe add one for the other profile. 5119 if (xpDomainInfo != null && ( 5120 xpDomainInfo.bestDomainVerificationStatus 5121 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5122 result.add(xpDomainInfo.resolveInfo); 5123 } 5124 includeBrowser = true; 5125 } 5126 5127 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5128 // If there were 'always' entries their preferred order has been set, so we also 5129 // back that off to make the alternatives equivalent 5130 if (alwaysAskList.size() > 0) { 5131 for (ResolveInfo i : result) { 5132 i.preferredOrder = 0; 5133 } 5134 result.addAll(alwaysAskList); 5135 includeBrowser = true; 5136 } 5137 5138 if (includeBrowser) { 5139 // Also add browsers (all of them or only the default one) 5140 if (DEBUG_DOMAIN_VERIFICATION) { 5141 Slog.v(TAG, " ...including browsers in candidate set"); 5142 } 5143 if ((matchFlags & MATCH_ALL) != 0) { 5144 result.addAll(matchAllList); 5145 } else { 5146 // Browser/generic handling case. If there's a default browser, go straight 5147 // to that (but only if there is no other higher-priority match). 5148 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5149 int maxMatchPrio = 0; 5150 ResolveInfo defaultBrowserMatch = null; 5151 final int numCandidates = matchAllList.size(); 5152 for (int n = 0; n < numCandidates; n++) { 5153 ResolveInfo info = matchAllList.get(n); 5154 // track the highest overall match priority... 5155 if (info.priority > maxMatchPrio) { 5156 maxMatchPrio = info.priority; 5157 } 5158 // ...and the highest-priority default browser match 5159 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5160 if (defaultBrowserMatch == null 5161 || (defaultBrowserMatch.priority < info.priority)) { 5162 if (debug) { 5163 Slog.v(TAG, "Considering default browser match " + info); 5164 } 5165 defaultBrowserMatch = info; 5166 } 5167 } 5168 } 5169 if (defaultBrowserMatch != null 5170 && defaultBrowserMatch.priority >= maxMatchPrio 5171 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5172 { 5173 if (debug) { 5174 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5175 } 5176 result.add(defaultBrowserMatch); 5177 } else { 5178 result.addAll(matchAllList); 5179 } 5180 } 5181 5182 // If there is nothing selected, add all candidates and remove the ones that the user 5183 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5184 if (result.size() == 0) { 5185 result.addAll(candidates); 5186 result.removeAll(neverList); 5187 } 5188 } 5189 } 5190 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5191 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5192 result.size()); 5193 for (ResolveInfo info : result) { 5194 Slog.v(TAG, " + " + info.activityInfo); 5195 } 5196 } 5197 return result; 5198 } 5199 5200 // Returns a packed value as a long: 5201 // 5202 // high 'int'-sized word: link status: undefined/ask/never/always. 5203 // low 'int'-sized word: relative priority among 'always' results. 5204 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5205 long result = ps.getDomainVerificationStatusForUser(userId); 5206 // if none available, get the master status 5207 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5208 if (ps.getIntentFilterVerificationInfo() != null) { 5209 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5210 } 5211 } 5212 return result; 5213 } 5214 5215 private ResolveInfo querySkipCurrentProfileIntents( 5216 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5217 int flags, int sourceUserId) { 5218 if (matchingFilters != null) { 5219 int size = matchingFilters.size(); 5220 for (int i = 0; i < size; i ++) { 5221 CrossProfileIntentFilter filter = matchingFilters.get(i); 5222 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5223 // Checking if there are activities in the target user that can handle the 5224 // intent. 5225 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5226 resolvedType, flags, sourceUserId); 5227 if (resolveInfo != null) { 5228 return resolveInfo; 5229 } 5230 } 5231 } 5232 } 5233 return null; 5234 } 5235 5236 // Return matching ResolveInfo if any for skip current profile intent filters. 5237 private ResolveInfo queryCrossProfileIntents( 5238 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5239 int flags, int sourceUserId) { 5240 if (matchingFilters != null) { 5241 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5242 // match the same intent. For performance reasons, it is better not to 5243 // run queryIntent twice for the same userId 5244 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5245 int size = matchingFilters.size(); 5246 for (int i = 0; i < size; i++) { 5247 CrossProfileIntentFilter filter = matchingFilters.get(i); 5248 int targetUserId = filter.getTargetUserId(); 5249 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 5250 && !alreadyTriedUserIds.get(targetUserId)) { 5251 // Checking if there are activities in the target user that can handle the 5252 // intent. 5253 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5254 resolvedType, flags, sourceUserId); 5255 if (resolveInfo != null) return resolveInfo; 5256 alreadyTriedUserIds.put(targetUserId, true); 5257 } 5258 } 5259 } 5260 return null; 5261 } 5262 5263 /** 5264 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5265 * will forward the intent to the filter's target user. 5266 * Otherwise, returns null. 5267 */ 5268 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5269 String resolvedType, int flags, int sourceUserId) { 5270 int targetUserId = filter.getTargetUserId(); 5271 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5272 resolvedType, flags, targetUserId); 5273 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5274 && isUserEnabled(targetUserId)) { 5275 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5276 } 5277 return null; 5278 } 5279 5280 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5281 int sourceUserId, int targetUserId) { 5282 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5283 long ident = Binder.clearCallingIdentity(); 5284 boolean targetIsProfile; 5285 try { 5286 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5287 } finally { 5288 Binder.restoreCallingIdentity(ident); 5289 } 5290 String className; 5291 if (targetIsProfile) { 5292 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5293 } else { 5294 className = FORWARD_INTENT_TO_PARENT; 5295 } 5296 ComponentName forwardingActivityComponentName = new ComponentName( 5297 mAndroidApplication.packageName, className); 5298 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5299 sourceUserId); 5300 if (!targetIsProfile) { 5301 forwardingActivityInfo.showUserIcon = targetUserId; 5302 forwardingResolveInfo.noResourceId = true; 5303 } 5304 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5305 forwardingResolveInfo.priority = 0; 5306 forwardingResolveInfo.preferredOrder = 0; 5307 forwardingResolveInfo.match = 0; 5308 forwardingResolveInfo.isDefault = true; 5309 forwardingResolveInfo.filter = filter; 5310 forwardingResolveInfo.targetUserId = targetUserId; 5311 return forwardingResolveInfo; 5312 } 5313 5314 @Override 5315 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5316 Intent[] specifics, String[] specificTypes, Intent intent, 5317 String resolvedType, int flags, int userId) { 5318 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5319 flags = augmentFlagsForUser(flags, userId); 5320 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5321 false, "query intent activity options"); 5322 final String resultsAction = intent.getAction(); 5323 5324 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5325 | PackageManager.GET_RESOLVED_FILTER, userId); 5326 5327 if (DEBUG_INTENT_MATCHING) { 5328 Log.v(TAG, "Query " + intent + ": " + results); 5329 } 5330 5331 int specificsPos = 0; 5332 int N; 5333 5334 // todo: note that the algorithm used here is O(N^2). This 5335 // isn't a problem in our current environment, but if we start running 5336 // into situations where we have more than 5 or 10 matches then this 5337 // should probably be changed to something smarter... 5338 5339 // First we go through and resolve each of the specific items 5340 // that were supplied, taking care of removing any corresponding 5341 // duplicate items in the generic resolve list. 5342 if (specifics != null) { 5343 for (int i=0; i<specifics.length; i++) { 5344 final Intent sintent = specifics[i]; 5345 if (sintent == null) { 5346 continue; 5347 } 5348 5349 if (DEBUG_INTENT_MATCHING) { 5350 Log.v(TAG, "Specific #" + i + ": " + sintent); 5351 } 5352 5353 String action = sintent.getAction(); 5354 if (resultsAction != null && resultsAction.equals(action)) { 5355 // If this action was explicitly requested, then don't 5356 // remove things that have it. 5357 action = null; 5358 } 5359 5360 ResolveInfo ri = null; 5361 ActivityInfo ai = null; 5362 5363 ComponentName comp = sintent.getComponent(); 5364 if (comp == null) { 5365 ri = resolveIntent( 5366 sintent, 5367 specificTypes != null ? specificTypes[i] : null, 5368 flags, userId); 5369 if (ri == null) { 5370 continue; 5371 } 5372 if (ri == mResolveInfo) { 5373 // ACK! Must do something better with this. 5374 } 5375 ai = ri.activityInfo; 5376 comp = new ComponentName(ai.applicationInfo.packageName, 5377 ai.name); 5378 } else { 5379 ai = getActivityInfo(comp, flags, userId); 5380 if (ai == null) { 5381 continue; 5382 } 5383 } 5384 5385 // Look for any generic query activities that are duplicates 5386 // of this specific one, and remove them from the results. 5387 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5388 N = results.size(); 5389 int j; 5390 for (j=specificsPos; j<N; j++) { 5391 ResolveInfo sri = results.get(j); 5392 if ((sri.activityInfo.name.equals(comp.getClassName()) 5393 && sri.activityInfo.applicationInfo.packageName.equals( 5394 comp.getPackageName())) 5395 || (action != null && sri.filter.matchAction(action))) { 5396 results.remove(j); 5397 if (DEBUG_INTENT_MATCHING) Log.v( 5398 TAG, "Removing duplicate item from " + j 5399 + " due to specific " + specificsPos); 5400 if (ri == null) { 5401 ri = sri; 5402 } 5403 j--; 5404 N--; 5405 } 5406 } 5407 5408 // Add this specific item to its proper place. 5409 if (ri == null) { 5410 ri = new ResolveInfo(); 5411 ri.activityInfo = ai; 5412 } 5413 results.add(specificsPos, ri); 5414 ri.specificIndex = i; 5415 specificsPos++; 5416 } 5417 } 5418 5419 // Now we go through the remaining generic results and remove any 5420 // duplicate actions that are found here. 5421 N = results.size(); 5422 for (int i=specificsPos; i<N-1; i++) { 5423 final ResolveInfo rii = results.get(i); 5424 if (rii.filter == null) { 5425 continue; 5426 } 5427 5428 // Iterate over all of the actions of this result's intent 5429 // filter... typically this should be just one. 5430 final Iterator<String> it = rii.filter.actionsIterator(); 5431 if (it == null) { 5432 continue; 5433 } 5434 while (it.hasNext()) { 5435 final String action = it.next(); 5436 if (resultsAction != null && resultsAction.equals(action)) { 5437 // If this action was explicitly requested, then don't 5438 // remove things that have it. 5439 continue; 5440 } 5441 for (int j=i+1; j<N; j++) { 5442 final ResolveInfo rij = results.get(j); 5443 if (rij.filter != null && rij.filter.hasAction(action)) { 5444 results.remove(j); 5445 if (DEBUG_INTENT_MATCHING) Log.v( 5446 TAG, "Removing duplicate item from " + j 5447 + " due to action " + action + " at " + i); 5448 j--; 5449 N--; 5450 } 5451 } 5452 } 5453 5454 // If the caller didn't request filter information, drop it now 5455 // so we don't have to marshall/unmarshall it. 5456 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5457 rii.filter = null; 5458 } 5459 } 5460 5461 // Filter out the caller activity if so requested. 5462 if (caller != null) { 5463 N = results.size(); 5464 for (int i=0; i<N; i++) { 5465 ActivityInfo ainfo = results.get(i).activityInfo; 5466 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5467 && caller.getClassName().equals(ainfo.name)) { 5468 results.remove(i); 5469 break; 5470 } 5471 } 5472 } 5473 5474 // If the caller didn't request filter information, 5475 // drop them now so we don't have to 5476 // marshall/unmarshall it. 5477 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5478 N = results.size(); 5479 for (int i=0; i<N; i++) { 5480 results.get(i).filter = null; 5481 } 5482 } 5483 5484 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5485 return results; 5486 } 5487 5488 @Override 5489 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5490 int userId) { 5491 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5492 flags = augmentFlagsForUser(flags, userId); 5493 ComponentName comp = intent.getComponent(); 5494 if (comp == null) { 5495 if (intent.getSelector() != null) { 5496 intent = intent.getSelector(); 5497 comp = intent.getComponent(); 5498 } 5499 } 5500 if (comp != null) { 5501 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5502 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5503 if (ai != null) { 5504 ResolveInfo ri = new ResolveInfo(); 5505 ri.activityInfo = ai; 5506 list.add(ri); 5507 } 5508 return list; 5509 } 5510 5511 // reader 5512 synchronized (mPackages) { 5513 String pkgName = intent.getPackage(); 5514 if (pkgName == null) { 5515 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5516 } 5517 final PackageParser.Package pkg = mPackages.get(pkgName); 5518 if (pkg != null) { 5519 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5520 userId); 5521 } 5522 return null; 5523 } 5524 } 5525 5526 @Override 5527 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5528 if (!sUserManager.exists(userId)) return null; 5529 flags = augmentFlagsForUser(flags, userId); 5530 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5531 if (query != null) { 5532 if (query.size() >= 1) { 5533 // If there is more than one service with the same priority, 5534 // just arbitrarily pick the first one. 5535 return query.get(0); 5536 } 5537 } 5538 return null; 5539 } 5540 5541 @Override 5542 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5543 int userId) { 5544 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5545 flags = augmentFlagsForUser(flags, userId); 5546 ComponentName comp = intent.getComponent(); 5547 if (comp == null) { 5548 if (intent.getSelector() != null) { 5549 intent = intent.getSelector(); 5550 comp = intent.getComponent(); 5551 } 5552 } 5553 if (comp != null) { 5554 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5555 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5556 if (si != null) { 5557 final ResolveInfo ri = new ResolveInfo(); 5558 ri.serviceInfo = si; 5559 list.add(ri); 5560 } 5561 return list; 5562 } 5563 5564 // reader 5565 synchronized (mPackages) { 5566 String pkgName = intent.getPackage(); 5567 if (pkgName == null) { 5568 return mServices.queryIntent(intent, resolvedType, flags, userId); 5569 } 5570 final PackageParser.Package pkg = mPackages.get(pkgName); 5571 if (pkg != null) { 5572 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5573 userId); 5574 } 5575 return null; 5576 } 5577 } 5578 5579 @Override 5580 public List<ResolveInfo> queryIntentContentProviders( 5581 Intent intent, String resolvedType, int flags, int userId) { 5582 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5583 flags = augmentFlagsForUser(flags, userId); 5584 ComponentName comp = intent.getComponent(); 5585 if (comp == null) { 5586 if (intent.getSelector() != null) { 5587 intent = intent.getSelector(); 5588 comp = intent.getComponent(); 5589 } 5590 } 5591 if (comp != null) { 5592 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5593 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5594 if (pi != null) { 5595 final ResolveInfo ri = new ResolveInfo(); 5596 ri.providerInfo = pi; 5597 list.add(ri); 5598 } 5599 return list; 5600 } 5601 5602 // reader 5603 synchronized (mPackages) { 5604 String pkgName = intent.getPackage(); 5605 if (pkgName == null) { 5606 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5607 } 5608 final PackageParser.Package pkg = mPackages.get(pkgName); 5609 if (pkg != null) { 5610 return mProviders.queryIntentForPackage( 5611 intent, resolvedType, flags, pkg.providers, userId); 5612 } 5613 return null; 5614 } 5615 } 5616 5617 @Override 5618 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5619 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5620 5621 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5622 5623 // writer 5624 synchronized (mPackages) { 5625 ArrayList<PackageInfo> list; 5626 if (listUninstalled) { 5627 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5628 for (PackageSetting ps : mSettings.mPackages.values()) { 5629 PackageInfo pi; 5630 if (ps.pkg != null) { 5631 pi = generatePackageInfo(ps.pkg, flags, userId); 5632 } else { 5633 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5634 } 5635 if (pi != null) { 5636 list.add(pi); 5637 } 5638 } 5639 } else { 5640 list = new ArrayList<PackageInfo>(mPackages.size()); 5641 for (PackageParser.Package p : mPackages.values()) { 5642 PackageInfo pi = generatePackageInfo(p, flags, userId); 5643 if (pi != null) { 5644 list.add(pi); 5645 } 5646 } 5647 } 5648 5649 return new ParceledListSlice<PackageInfo>(list); 5650 } 5651 } 5652 5653 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5654 String[] permissions, boolean[] tmp, int flags, int userId) { 5655 int numMatch = 0; 5656 final PermissionsState permissionsState = ps.getPermissionsState(); 5657 for (int i=0; i<permissions.length; i++) { 5658 final String permission = permissions[i]; 5659 if (permissionsState.hasPermission(permission, userId)) { 5660 tmp[i] = true; 5661 numMatch++; 5662 } else { 5663 tmp[i] = false; 5664 } 5665 } 5666 if (numMatch == 0) { 5667 return; 5668 } 5669 PackageInfo pi; 5670 if (ps.pkg != null) { 5671 pi = generatePackageInfo(ps.pkg, flags, userId); 5672 } else { 5673 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5674 } 5675 // The above might return null in cases of uninstalled apps or install-state 5676 // skew across users/profiles. 5677 if (pi != null) { 5678 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5679 if (numMatch == permissions.length) { 5680 pi.requestedPermissions = permissions; 5681 } else { 5682 pi.requestedPermissions = new String[numMatch]; 5683 numMatch = 0; 5684 for (int i=0; i<permissions.length; i++) { 5685 if (tmp[i]) { 5686 pi.requestedPermissions[numMatch] = permissions[i]; 5687 numMatch++; 5688 } 5689 } 5690 } 5691 } 5692 list.add(pi); 5693 } 5694 } 5695 5696 @Override 5697 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5698 String[] permissions, int flags, int userId) { 5699 if (!sUserManager.exists(userId)) return null; 5700 flags = augmentFlagsForUser(flags, userId); 5701 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5702 5703 // writer 5704 synchronized (mPackages) { 5705 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5706 boolean[] tmpBools = new boolean[permissions.length]; 5707 if (listUninstalled) { 5708 for (PackageSetting ps : mSettings.mPackages.values()) { 5709 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5710 } 5711 } else { 5712 for (PackageParser.Package pkg : mPackages.values()) { 5713 PackageSetting ps = (PackageSetting)pkg.mExtras; 5714 if (ps != null) { 5715 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5716 userId); 5717 } 5718 } 5719 } 5720 5721 return new ParceledListSlice<PackageInfo>(list); 5722 } 5723 } 5724 5725 @Override 5726 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5727 if (!sUserManager.exists(userId)) return null; 5728 flags = augmentFlagsForUser(flags, userId); 5729 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5730 5731 // writer 5732 synchronized (mPackages) { 5733 ArrayList<ApplicationInfo> list; 5734 if (listUninstalled) { 5735 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5736 for (PackageSetting ps : mSettings.mPackages.values()) { 5737 ApplicationInfo ai; 5738 if (ps.pkg != null) { 5739 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5740 ps.readUserState(userId), userId); 5741 } else { 5742 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5743 } 5744 if (ai != null) { 5745 list.add(ai); 5746 } 5747 } 5748 } else { 5749 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5750 for (PackageParser.Package p : mPackages.values()) { 5751 if (p.mExtras != null) { 5752 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5753 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5754 if (ai != null) { 5755 list.add(ai); 5756 } 5757 } 5758 } 5759 } 5760 5761 return new ParceledListSlice<ApplicationInfo>(list); 5762 } 5763 } 5764 5765 public List<ApplicationInfo> getPersistentApplications(int flags) { 5766 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5767 5768 // reader 5769 synchronized (mPackages) { 5770 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5771 final int userId = UserHandle.getCallingUserId(); 5772 while (i.hasNext()) { 5773 final PackageParser.Package p = i.next(); 5774 if (p.applicationInfo != null 5775 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5776 && (!mSafeMode || isSystemApp(p))) { 5777 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5778 if (ps != null) { 5779 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5780 ps.readUserState(userId), userId); 5781 if (ai != null) { 5782 finalList.add(ai); 5783 } 5784 } 5785 } 5786 } 5787 } 5788 5789 return finalList; 5790 } 5791 5792 @Override 5793 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5794 if (!sUserManager.exists(userId)) return null; 5795 flags = augmentFlagsForUser(flags, userId); 5796 // reader 5797 synchronized (mPackages) { 5798 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5799 PackageSetting ps = provider != null 5800 ? mSettings.mPackages.get(provider.owner.packageName) 5801 : null; 5802 return ps != null 5803 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5804 && (!mSafeMode || (provider.info.applicationInfo.flags 5805 &ApplicationInfo.FLAG_SYSTEM) != 0) 5806 ? PackageParser.generateProviderInfo(provider, flags, 5807 ps.readUserState(userId), userId) 5808 : null; 5809 } 5810 } 5811 5812 /** 5813 * @deprecated 5814 */ 5815 @Deprecated 5816 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5817 // reader 5818 synchronized (mPackages) { 5819 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5820 .entrySet().iterator(); 5821 final int userId = UserHandle.getCallingUserId(); 5822 while (i.hasNext()) { 5823 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5824 PackageParser.Provider p = entry.getValue(); 5825 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5826 5827 if (ps != null && p.syncable 5828 && (!mSafeMode || (p.info.applicationInfo.flags 5829 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5830 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5831 ps.readUserState(userId), userId); 5832 if (info != null) { 5833 outNames.add(entry.getKey()); 5834 outInfo.add(info); 5835 } 5836 } 5837 } 5838 } 5839 } 5840 5841 @Override 5842 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5843 int uid, int flags) { 5844 final int userId = processName != null ? UserHandle.getUserId(uid) 5845 : UserHandle.getCallingUserId(); 5846 if (!sUserManager.exists(userId)) return null; 5847 flags = augmentFlagsForUser(flags, userId); 5848 5849 ArrayList<ProviderInfo> finalList = null; 5850 // reader 5851 synchronized (mPackages) { 5852 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5853 while (i.hasNext()) { 5854 final PackageParser.Provider p = i.next(); 5855 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5856 if (ps != null && p.info.authority != null 5857 && (processName == null 5858 || (p.info.processName.equals(processName) 5859 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5860 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5861 && (!mSafeMode 5862 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5863 if (finalList == null) { 5864 finalList = new ArrayList<ProviderInfo>(3); 5865 } 5866 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5867 ps.readUserState(userId), userId); 5868 if (info != null) { 5869 finalList.add(info); 5870 } 5871 } 5872 } 5873 } 5874 5875 if (finalList != null) { 5876 Collections.sort(finalList, mProviderInitOrderSorter); 5877 return new ParceledListSlice<ProviderInfo>(finalList); 5878 } 5879 5880 return null; 5881 } 5882 5883 @Override 5884 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5885 int flags) { 5886 // reader 5887 synchronized (mPackages) { 5888 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5889 return PackageParser.generateInstrumentationInfo(i, flags); 5890 } 5891 } 5892 5893 @Override 5894 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5895 int flags) { 5896 ArrayList<InstrumentationInfo> finalList = 5897 new ArrayList<InstrumentationInfo>(); 5898 5899 // reader 5900 synchronized (mPackages) { 5901 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5902 while (i.hasNext()) { 5903 final PackageParser.Instrumentation p = i.next(); 5904 if (targetPackage == null 5905 || targetPackage.equals(p.info.targetPackage)) { 5906 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5907 flags); 5908 if (ii != null) { 5909 finalList.add(ii); 5910 } 5911 } 5912 } 5913 } 5914 5915 return finalList; 5916 } 5917 5918 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5919 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5920 if (overlays == null) { 5921 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5922 return; 5923 } 5924 for (PackageParser.Package opkg : overlays.values()) { 5925 // Not much to do if idmap fails: we already logged the error 5926 // and we certainly don't want to abort installation of pkg simply 5927 // because an overlay didn't fit properly. For these reasons, 5928 // ignore the return value of createIdmapForPackagePairLI. 5929 createIdmapForPackagePairLI(pkg, opkg); 5930 } 5931 } 5932 5933 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5934 PackageParser.Package opkg) { 5935 if (!opkg.mTrustedOverlay) { 5936 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5937 opkg.baseCodePath + ": overlay not trusted"); 5938 return false; 5939 } 5940 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5941 if (overlaySet == null) { 5942 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5943 opkg.baseCodePath + " but target package has no known overlays"); 5944 return false; 5945 } 5946 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5947 // TODO: generate idmap for split APKs 5948 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5949 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5950 + opkg.baseCodePath); 5951 return false; 5952 } 5953 PackageParser.Package[] overlayArray = 5954 overlaySet.values().toArray(new PackageParser.Package[0]); 5955 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5956 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5957 return p1.mOverlayPriority - p2.mOverlayPriority; 5958 } 5959 }; 5960 Arrays.sort(overlayArray, cmp); 5961 5962 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5963 int i = 0; 5964 for (PackageParser.Package p : overlayArray) { 5965 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5966 } 5967 return true; 5968 } 5969 5970 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5971 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5972 try { 5973 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5974 } finally { 5975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5976 } 5977 } 5978 5979 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5980 final File[] files = dir.listFiles(); 5981 if (ArrayUtils.isEmpty(files)) { 5982 Log.d(TAG, "No files in app dir " + dir); 5983 return; 5984 } 5985 5986 if (DEBUG_PACKAGE_SCANNING) { 5987 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5988 + " flags=0x" + Integer.toHexString(parseFlags)); 5989 } 5990 5991 for (File file : files) { 5992 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5993 && !PackageInstallerService.isStageName(file.getName()); 5994 if (!isPackage) { 5995 // Ignore entries which are not packages 5996 continue; 5997 } 5998 try { 5999 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6000 scanFlags, currentTime, null); 6001 } catch (PackageManagerException e) { 6002 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6003 6004 // Delete invalid userdata apps 6005 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6006 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6007 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6008 if (file.isDirectory()) { 6009 mInstaller.rmPackageDir(file.getAbsolutePath()); 6010 } else { 6011 file.delete(); 6012 } 6013 } 6014 } 6015 } 6016 } 6017 6018 private static File getSettingsProblemFile() { 6019 File dataDir = Environment.getDataDirectory(); 6020 File systemDir = new File(dataDir, "system"); 6021 File fname = new File(systemDir, "uiderrors.txt"); 6022 return fname; 6023 } 6024 6025 static void reportSettingsProblem(int priority, String msg) { 6026 logCriticalInfo(priority, msg); 6027 } 6028 6029 static void logCriticalInfo(int priority, String msg) { 6030 Slog.println(priority, TAG, msg); 6031 EventLogTags.writePmCriticalInfo(msg); 6032 try { 6033 File fname = getSettingsProblemFile(); 6034 FileOutputStream out = new FileOutputStream(fname, true); 6035 PrintWriter pw = new FastPrintWriter(out); 6036 SimpleDateFormat formatter = new SimpleDateFormat(); 6037 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6038 pw.println(dateString + ": " + msg); 6039 pw.close(); 6040 FileUtils.setPermissions( 6041 fname.toString(), 6042 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6043 -1, -1); 6044 } catch (java.io.IOException e) { 6045 } 6046 } 6047 6048 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6049 PackageParser.Package pkg, File srcFile, int parseFlags) 6050 throws PackageManagerException { 6051 if (ps != null 6052 && ps.codePath.equals(srcFile) 6053 && ps.timeStamp == srcFile.lastModified() 6054 && !isCompatSignatureUpdateNeeded(pkg) 6055 && !isRecoverSignatureUpdateNeeded(pkg)) { 6056 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6057 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6058 ArraySet<PublicKey> signingKs; 6059 synchronized (mPackages) { 6060 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6061 } 6062 if (ps.signatures.mSignatures != null 6063 && ps.signatures.mSignatures.length != 0 6064 && signingKs != null) { 6065 // Optimization: reuse the existing cached certificates 6066 // if the package appears to be unchanged. 6067 pkg.mSignatures = ps.signatures.mSignatures; 6068 pkg.mSigningKeys = signingKs; 6069 return; 6070 } 6071 6072 Slog.w(TAG, "PackageSetting for " + ps.name 6073 + " is missing signatures. Collecting certs again to recover them."); 6074 } else { 6075 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6076 } 6077 6078 try { 6079 pp.collectCertificates(pkg, parseFlags); 6080 pp.collectManifestDigest(pkg); 6081 } catch (PackageParserException e) { 6082 throw PackageManagerException.from(e); 6083 } 6084 } 6085 6086 /** 6087 * Traces a package scan. 6088 * @see #scanPackageLI(File, int, int, long, UserHandle) 6089 */ 6090 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6091 long currentTime, UserHandle user) throws PackageManagerException { 6092 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6093 try { 6094 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6095 } finally { 6096 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6097 } 6098 } 6099 6100 /** 6101 * Scans a package and returns the newly parsed package. 6102 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6103 */ 6104 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6105 long currentTime, UserHandle user) throws PackageManagerException { 6106 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6107 parseFlags |= mDefParseFlags; 6108 PackageParser pp = new PackageParser(); 6109 pp.setSeparateProcesses(mSeparateProcesses); 6110 pp.setOnlyCoreApps(mOnlyCore); 6111 pp.setDisplayMetrics(mMetrics); 6112 6113 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6114 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6115 } 6116 6117 final PackageParser.Package pkg; 6118 try { 6119 pkg = pp.parsePackage(scanFile, parseFlags); 6120 } catch (PackageParserException e) { 6121 throw PackageManagerException.from(e); 6122 } 6123 6124 PackageSetting ps = null; 6125 PackageSetting updatedPkg; 6126 // reader 6127 synchronized (mPackages) { 6128 // Look to see if we already know about this package. 6129 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6130 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6131 // This package has been renamed to its original name. Let's 6132 // use that. 6133 ps = mSettings.peekPackageLPr(oldName); 6134 } 6135 // If there was no original package, see one for the real package name. 6136 if (ps == null) { 6137 ps = mSettings.peekPackageLPr(pkg.packageName); 6138 } 6139 // Check to see if this package could be hiding/updating a system 6140 // package. Must look for it either under the original or real 6141 // package name depending on our state. 6142 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6143 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6144 } 6145 boolean updatedPkgBetter = false; 6146 // First check if this is a system package that may involve an update 6147 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6148 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6149 // it needs to drop FLAG_PRIVILEGED. 6150 if (locationIsPrivileged(scanFile)) { 6151 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6152 } else { 6153 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6154 } 6155 6156 if (ps != null && !ps.codePath.equals(scanFile)) { 6157 // The path has changed from what was last scanned... check the 6158 // version of the new path against what we have stored to determine 6159 // what to do. 6160 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6161 if (pkg.mVersionCode <= ps.versionCode) { 6162 // The system package has been updated and the code path does not match 6163 // Ignore entry. Skip it. 6164 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6165 + " ignored: updated version " + ps.versionCode 6166 + " better than this " + pkg.mVersionCode); 6167 if (!updatedPkg.codePath.equals(scanFile)) { 6168 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6169 + ps.name + " changing from " + updatedPkg.codePathString 6170 + " to " + scanFile); 6171 updatedPkg.codePath = scanFile; 6172 updatedPkg.codePathString = scanFile.toString(); 6173 updatedPkg.resourcePath = scanFile; 6174 updatedPkg.resourcePathString = scanFile.toString(); 6175 } 6176 updatedPkg.pkg = pkg; 6177 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6178 "Package " + ps.name + " at " + scanFile 6179 + " ignored: updated version " + ps.versionCode 6180 + " better than this " + pkg.mVersionCode); 6181 } else { 6182 // The current app on the system partition is better than 6183 // what we have updated to on the data partition; switch 6184 // back to the system partition version. 6185 // At this point, its safely assumed that package installation for 6186 // apps in system partition will go through. If not there won't be a working 6187 // version of the app 6188 // writer 6189 synchronized (mPackages) { 6190 // Just remove the loaded entries from package lists. 6191 mPackages.remove(ps.name); 6192 } 6193 6194 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6195 + " reverting from " + ps.codePathString 6196 + ": new version " + pkg.mVersionCode 6197 + " better than installed " + ps.versionCode); 6198 6199 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6200 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6201 synchronized (mInstallLock) { 6202 args.cleanUpResourcesLI(); 6203 } 6204 synchronized (mPackages) { 6205 mSettings.enableSystemPackageLPw(ps.name); 6206 } 6207 updatedPkgBetter = true; 6208 } 6209 } 6210 } 6211 6212 if (updatedPkg != null) { 6213 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6214 // initially 6215 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6216 6217 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6218 // flag set initially 6219 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6220 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6221 } 6222 } 6223 6224 // Verify certificates against what was last scanned 6225 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6226 6227 /* 6228 * A new system app appeared, but we already had a non-system one of the 6229 * same name installed earlier. 6230 */ 6231 boolean shouldHideSystemApp = false; 6232 if (updatedPkg == null && ps != null 6233 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6234 /* 6235 * Check to make sure the signatures match first. If they don't, 6236 * wipe the installed application and its data. 6237 */ 6238 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6239 != PackageManager.SIGNATURE_MATCH) { 6240 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6241 + " signatures don't match existing userdata copy; removing"); 6242 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6243 ps = null; 6244 } else { 6245 /* 6246 * If the newly-added system app is an older version than the 6247 * already installed version, hide it. It will be scanned later 6248 * and re-added like an update. 6249 */ 6250 if (pkg.mVersionCode <= ps.versionCode) { 6251 shouldHideSystemApp = true; 6252 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6253 + " but new version " + pkg.mVersionCode + " better than installed " 6254 + ps.versionCode + "; hiding system"); 6255 } else { 6256 /* 6257 * The newly found system app is a newer version that the 6258 * one previously installed. Simply remove the 6259 * already-installed application and replace it with our own 6260 * while keeping the application data. 6261 */ 6262 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6263 + " reverting from " + ps.codePathString + ": new version " 6264 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6265 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6266 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6267 synchronized (mInstallLock) { 6268 args.cleanUpResourcesLI(); 6269 } 6270 } 6271 } 6272 } 6273 6274 // The apk is forward locked (not public) if its code and resources 6275 // are kept in different files. (except for app in either system or 6276 // vendor path). 6277 // TODO grab this value from PackageSettings 6278 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6279 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6280 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6281 } 6282 } 6283 6284 // TODO: extend to support forward-locked splits 6285 String resourcePath = null; 6286 String baseResourcePath = null; 6287 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6288 if (ps != null && ps.resourcePathString != null) { 6289 resourcePath = ps.resourcePathString; 6290 baseResourcePath = ps.resourcePathString; 6291 } else { 6292 // Should not happen at all. Just log an error. 6293 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6294 } 6295 } else { 6296 resourcePath = pkg.codePath; 6297 baseResourcePath = pkg.baseCodePath; 6298 } 6299 6300 // Set application objects path explicitly. 6301 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6302 pkg.applicationInfo.setCodePath(pkg.codePath); 6303 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6304 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6305 pkg.applicationInfo.setResourcePath(resourcePath); 6306 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6307 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6308 6309 // Note that we invoke the following method only if we are about to unpack an application 6310 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6311 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6312 6313 /* 6314 * If the system app should be overridden by a previously installed 6315 * data, hide the system app now and let the /data/app scan pick it up 6316 * again. 6317 */ 6318 if (shouldHideSystemApp) { 6319 synchronized (mPackages) { 6320 mSettings.disableSystemPackageLPw(pkg.packageName); 6321 } 6322 } 6323 6324 return scannedPkg; 6325 } 6326 6327 private static String fixProcessName(String defProcessName, 6328 String processName, int uid) { 6329 if (processName == null) { 6330 return defProcessName; 6331 } 6332 return processName; 6333 } 6334 6335 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6336 throws PackageManagerException { 6337 if (pkgSetting.signatures.mSignatures != null) { 6338 // Already existing package. Make sure signatures match 6339 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6340 == PackageManager.SIGNATURE_MATCH; 6341 if (!match) { 6342 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6343 == PackageManager.SIGNATURE_MATCH; 6344 } 6345 if (!match) { 6346 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6347 == PackageManager.SIGNATURE_MATCH; 6348 } 6349 if (!match) { 6350 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6351 + pkg.packageName + " signatures do not match the " 6352 + "previously installed version; ignoring!"); 6353 } 6354 } 6355 6356 // Check for shared user signatures 6357 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6358 // Already existing package. Make sure signatures match 6359 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6360 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6361 if (!match) { 6362 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6363 == PackageManager.SIGNATURE_MATCH; 6364 } 6365 if (!match) { 6366 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6367 == PackageManager.SIGNATURE_MATCH; 6368 } 6369 if (!match) { 6370 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6371 "Package " + pkg.packageName 6372 + " has no signatures that match those in shared user " 6373 + pkgSetting.sharedUser.name + "; ignoring!"); 6374 } 6375 } 6376 } 6377 6378 /** 6379 * Enforces that only the system UID or root's UID can call a method exposed 6380 * via Binder. 6381 * 6382 * @param message used as message if SecurityException is thrown 6383 * @throws SecurityException if the caller is not system or root 6384 */ 6385 private static final void enforceSystemOrRoot(String message) { 6386 final int uid = Binder.getCallingUid(); 6387 if (uid != Process.SYSTEM_UID && uid != 0) { 6388 throw new SecurityException(message); 6389 } 6390 } 6391 6392 @Override 6393 public void performFstrimIfNeeded() { 6394 enforceSystemOrRoot("Only the system can request fstrim"); 6395 6396 // Before everything else, see whether we need to fstrim. 6397 try { 6398 IMountService ms = PackageHelper.getMountService(); 6399 if (ms != null) { 6400 final boolean isUpgrade = isUpgrade(); 6401 boolean doTrim = isUpgrade; 6402 if (doTrim) { 6403 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6404 } else { 6405 final long interval = android.provider.Settings.Global.getLong( 6406 mContext.getContentResolver(), 6407 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6408 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6409 if (interval > 0) { 6410 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6411 if (timeSinceLast > interval) { 6412 doTrim = true; 6413 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6414 + "; running immediately"); 6415 } 6416 } 6417 } 6418 if (doTrim) { 6419 if (!isFirstBoot()) { 6420 try { 6421 ActivityManagerNative.getDefault().showBootMessage( 6422 mContext.getResources().getString( 6423 R.string.android_upgrading_fstrim), true); 6424 } catch (RemoteException e) { 6425 } 6426 } 6427 ms.runMaintenance(); 6428 } 6429 } else { 6430 Slog.e(TAG, "Mount service unavailable!"); 6431 } 6432 } catch (RemoteException e) { 6433 // Can't happen; MountService is local 6434 } 6435 } 6436 6437 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6438 List<ResolveInfo> ris = null; 6439 try { 6440 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6441 intent, null, 0, userId); 6442 } catch (RemoteException e) { 6443 } 6444 ArraySet<String> pkgNames = new ArraySet<String>(); 6445 if (ris != null) { 6446 for (ResolveInfo ri : ris) { 6447 pkgNames.add(ri.activityInfo.packageName); 6448 } 6449 } 6450 return pkgNames; 6451 } 6452 6453 @Override 6454 public void notifyPackageUse(String packageName) { 6455 synchronized (mPackages) { 6456 PackageParser.Package p = mPackages.get(packageName); 6457 if (p == null) { 6458 return; 6459 } 6460 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6461 } 6462 } 6463 6464 @Override 6465 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6466 return performDexOptTraced(packageName, instructionSet); 6467 } 6468 6469 public boolean performDexOpt(String packageName, String instructionSet) { 6470 return performDexOptTraced(packageName, instructionSet); 6471 } 6472 6473 private boolean performDexOptTraced(String packageName, String instructionSet) { 6474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6475 try { 6476 return performDexOptInternal(packageName, instructionSet); 6477 } finally { 6478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6479 } 6480 } 6481 6482 private boolean performDexOptInternal(String packageName, String instructionSet) { 6483 PackageParser.Package p; 6484 final String targetInstructionSet; 6485 synchronized (mPackages) { 6486 p = mPackages.get(packageName); 6487 if (p == null) { 6488 return false; 6489 } 6490 mPackageUsage.write(false); 6491 6492 targetInstructionSet = instructionSet != null ? instructionSet : 6493 getPrimaryInstructionSet(p.applicationInfo); 6494 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6495 return false; 6496 } 6497 } 6498 long callingId = Binder.clearCallingIdentity(); 6499 try { 6500 synchronized (mInstallLock) { 6501 final String[] instructionSets = new String[] { targetInstructionSet }; 6502 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6503 true /* inclDependencies */); 6504 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6505 } 6506 } finally { 6507 Binder.restoreCallingIdentity(callingId); 6508 } 6509 } 6510 6511 public ArraySet<String> getPackagesThatNeedDexOpt() { 6512 ArraySet<String> pkgs = null; 6513 synchronized (mPackages) { 6514 for (PackageParser.Package p : mPackages.values()) { 6515 if (DEBUG_DEXOPT) { 6516 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6517 } 6518 if (!p.mDexOptPerformed.isEmpty()) { 6519 continue; 6520 } 6521 if (pkgs == null) { 6522 pkgs = new ArraySet<String>(); 6523 } 6524 pkgs.add(p.packageName); 6525 } 6526 } 6527 return pkgs; 6528 } 6529 6530 public void shutdown() { 6531 mPackageUsage.write(true); 6532 } 6533 6534 @Override 6535 public void forceDexOpt(String packageName) { 6536 enforceSystemOrRoot("forceDexOpt"); 6537 6538 PackageParser.Package pkg; 6539 synchronized (mPackages) { 6540 pkg = mPackages.get(packageName); 6541 if (pkg == null) { 6542 throw new IllegalArgumentException("Missing package: " + packageName); 6543 } 6544 } 6545 6546 synchronized (mInstallLock) { 6547 final String[] instructionSets = new String[] { 6548 getPrimaryInstructionSet(pkg.applicationInfo) }; 6549 6550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6551 6552 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6553 true /* inclDependencies */); 6554 6555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6556 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6557 throw new IllegalStateException("Failed to dexopt: " + res); 6558 } 6559 } 6560 } 6561 6562 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6563 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6564 Slog.w(TAG, "Unable to update from " + oldPkg.name 6565 + " to " + newPkg.packageName 6566 + ": old package not in system partition"); 6567 return false; 6568 } else if (mPackages.get(oldPkg.name) != null) { 6569 Slog.w(TAG, "Unable to update from " + oldPkg.name 6570 + " to " + newPkg.packageName 6571 + ": old package still exists"); 6572 return false; 6573 } 6574 return true; 6575 } 6576 6577 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6578 throws PackageManagerException { 6579 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6580 if (res != 0) { 6581 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6582 "Failed to install " + packageName + ": " + res); 6583 } 6584 6585 final int[] users = sUserManager.getUserIds(); 6586 for (int user : users) { 6587 if (user != 0) { 6588 res = mInstaller.createUserData(volumeUuid, packageName, 6589 UserHandle.getUid(user, uid), user, seinfo); 6590 if (res != 0) { 6591 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6592 "Failed to createUserData " + packageName + ": " + res); 6593 } 6594 } 6595 } 6596 } 6597 6598 private int removeDataDirsLI(String volumeUuid, String packageName) { 6599 int[] users = sUserManager.getUserIds(); 6600 int res = 0; 6601 for (int user : users) { 6602 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6603 if (resInner < 0) { 6604 res = resInner; 6605 } 6606 } 6607 6608 return res; 6609 } 6610 6611 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6612 int[] users = sUserManager.getUserIds(); 6613 int res = 0; 6614 for (int user : users) { 6615 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6616 if (resInner < 0) { 6617 res = resInner; 6618 } 6619 } 6620 return res; 6621 } 6622 6623 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6624 PackageParser.Package changingLib) { 6625 if (file.path != null) { 6626 usesLibraryFiles.add(file.path); 6627 return; 6628 } 6629 PackageParser.Package p = mPackages.get(file.apk); 6630 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6631 // If we are doing this while in the middle of updating a library apk, 6632 // then we need to make sure to use that new apk for determining the 6633 // dependencies here. (We haven't yet finished committing the new apk 6634 // to the package manager state.) 6635 if (p == null || p.packageName.equals(changingLib.packageName)) { 6636 p = changingLib; 6637 } 6638 } 6639 if (p != null) { 6640 usesLibraryFiles.addAll(p.getAllCodePaths()); 6641 } 6642 } 6643 6644 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6645 PackageParser.Package changingLib) throws PackageManagerException { 6646 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6647 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6648 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6649 for (int i=0; i<N; i++) { 6650 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6651 if (file == null) { 6652 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6653 "Package " + pkg.packageName + " requires unavailable shared library " 6654 + pkg.usesLibraries.get(i) + "; failing!"); 6655 } 6656 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6657 } 6658 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6659 for (int i=0; i<N; i++) { 6660 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6661 if (file == null) { 6662 Slog.w(TAG, "Package " + pkg.packageName 6663 + " desires unavailable shared library " 6664 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6665 } else { 6666 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6667 } 6668 } 6669 N = usesLibraryFiles.size(); 6670 if (N > 0) { 6671 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6672 } else { 6673 pkg.usesLibraryFiles = null; 6674 } 6675 } 6676 } 6677 6678 private static boolean hasString(List<String> list, List<String> which) { 6679 if (list == null) { 6680 return false; 6681 } 6682 for (int i=list.size()-1; i>=0; i--) { 6683 for (int j=which.size()-1; j>=0; j--) { 6684 if (which.get(j).equals(list.get(i))) { 6685 return true; 6686 } 6687 } 6688 } 6689 return false; 6690 } 6691 6692 private void updateAllSharedLibrariesLPw() { 6693 for (PackageParser.Package pkg : mPackages.values()) { 6694 try { 6695 updateSharedLibrariesLPw(pkg, null); 6696 } catch (PackageManagerException e) { 6697 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6698 } 6699 } 6700 } 6701 6702 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6703 PackageParser.Package changingPkg) { 6704 ArrayList<PackageParser.Package> res = null; 6705 for (PackageParser.Package pkg : mPackages.values()) { 6706 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6707 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6708 if (res == null) { 6709 res = new ArrayList<PackageParser.Package>(); 6710 } 6711 res.add(pkg); 6712 try { 6713 updateSharedLibrariesLPw(pkg, changingPkg); 6714 } catch (PackageManagerException e) { 6715 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6716 } 6717 } 6718 } 6719 return res; 6720 } 6721 6722 /** 6723 * Derive the value of the {@code cpuAbiOverride} based on the provided 6724 * value and an optional stored value from the package settings. 6725 */ 6726 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6727 String cpuAbiOverride = null; 6728 6729 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6730 cpuAbiOverride = null; 6731 } else if (abiOverride != null) { 6732 cpuAbiOverride = abiOverride; 6733 } else if (settings != null) { 6734 cpuAbiOverride = settings.cpuAbiOverrideString; 6735 } 6736 6737 return cpuAbiOverride; 6738 } 6739 6740 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6741 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6742 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6743 try { 6744 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6745 } finally { 6746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6747 } 6748 } 6749 6750 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6751 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6752 boolean success = false; 6753 try { 6754 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6755 currentTime, user); 6756 success = true; 6757 return res; 6758 } finally { 6759 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6760 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6761 } 6762 } 6763 } 6764 6765 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6766 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6767 final File scanFile = new File(pkg.codePath); 6768 if (pkg.applicationInfo.getCodePath() == null || 6769 pkg.applicationInfo.getResourcePath() == null) { 6770 // Bail out. The resource and code paths haven't been set. 6771 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6772 "Code and resource paths haven't been set correctly"); 6773 } 6774 6775 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6776 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6777 } else { 6778 // Only allow system apps to be flagged as core apps. 6779 pkg.coreApp = false; 6780 } 6781 6782 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6783 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6784 } 6785 6786 if (mCustomResolverComponentName != null && 6787 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6788 setUpCustomResolverActivity(pkg); 6789 } 6790 6791 if (pkg.packageName.equals("android")) { 6792 synchronized (mPackages) { 6793 if (mAndroidApplication != null) { 6794 Slog.w(TAG, "*************************************************"); 6795 Slog.w(TAG, "Core android package being redefined. Skipping."); 6796 Slog.w(TAG, " file=" + scanFile); 6797 Slog.w(TAG, "*************************************************"); 6798 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6799 "Core android package being redefined. Skipping."); 6800 } 6801 6802 // Set up information for our fall-back user intent resolution activity. 6803 mPlatformPackage = pkg; 6804 pkg.mVersionCode = mSdkVersion; 6805 mAndroidApplication = pkg.applicationInfo; 6806 6807 if (!mResolverReplaced) { 6808 mResolveActivity.applicationInfo = mAndroidApplication; 6809 mResolveActivity.name = ResolverActivity.class.getName(); 6810 mResolveActivity.packageName = mAndroidApplication.packageName; 6811 mResolveActivity.processName = "system:ui"; 6812 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6813 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6814 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6815 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6816 mResolveActivity.exported = true; 6817 mResolveActivity.enabled = true; 6818 mResolveInfo.activityInfo = mResolveActivity; 6819 mResolveInfo.priority = 0; 6820 mResolveInfo.preferredOrder = 0; 6821 mResolveInfo.match = 0; 6822 mResolveComponentName = new ComponentName( 6823 mAndroidApplication.packageName, mResolveActivity.name); 6824 } 6825 } 6826 } 6827 6828 if (DEBUG_PACKAGE_SCANNING) { 6829 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6830 Log.d(TAG, "Scanning package " + pkg.packageName); 6831 } 6832 6833 if (mPackages.containsKey(pkg.packageName) 6834 || mSharedLibraries.containsKey(pkg.packageName)) { 6835 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6836 "Application package " + pkg.packageName 6837 + " already installed. Skipping duplicate."); 6838 } 6839 6840 // If we're only installing presumed-existing packages, require that the 6841 // scanned APK is both already known and at the path previously established 6842 // for it. Previously unknown packages we pick up normally, but if we have an 6843 // a priori expectation about this package's install presence, enforce it. 6844 // With a singular exception for new system packages. When an OTA contains 6845 // a new system package, we allow the codepath to change from a system location 6846 // to the user-installed location. If we don't allow this change, any newer, 6847 // user-installed version of the application will be ignored. 6848 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6849 if (mExpectingBetter.containsKey(pkg.packageName)) { 6850 logCriticalInfo(Log.WARN, 6851 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6852 } else { 6853 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6854 if (known != null) { 6855 if (DEBUG_PACKAGE_SCANNING) { 6856 Log.d(TAG, "Examining " + pkg.codePath 6857 + " and requiring known paths " + known.codePathString 6858 + " & " + known.resourcePathString); 6859 } 6860 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6861 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6862 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6863 "Application package " + pkg.packageName 6864 + " found at " + pkg.applicationInfo.getCodePath() 6865 + " but expected at " + known.codePathString + "; ignoring."); 6866 } 6867 } 6868 } 6869 } 6870 6871 // Initialize package source and resource directories 6872 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6873 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6874 6875 SharedUserSetting suid = null; 6876 PackageSetting pkgSetting = null; 6877 6878 if (!isSystemApp(pkg)) { 6879 // Only system apps can use these features. 6880 pkg.mOriginalPackages = null; 6881 pkg.mRealPackage = null; 6882 pkg.mAdoptPermissions = null; 6883 } 6884 6885 // writer 6886 synchronized (mPackages) { 6887 if (pkg.mSharedUserId != null) { 6888 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6889 if (suid == null) { 6890 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6891 "Creating application package " + pkg.packageName 6892 + " for shared user failed"); 6893 } 6894 if (DEBUG_PACKAGE_SCANNING) { 6895 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6896 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6897 + "): packages=" + suid.packages); 6898 } 6899 } 6900 6901 // Check if we are renaming from an original package name. 6902 PackageSetting origPackage = null; 6903 String realName = null; 6904 if (pkg.mOriginalPackages != null) { 6905 // This package may need to be renamed to a previously 6906 // installed name. Let's check on that... 6907 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6908 if (pkg.mOriginalPackages.contains(renamed)) { 6909 // This package had originally been installed as the 6910 // original name, and we have already taken care of 6911 // transitioning to the new one. Just update the new 6912 // one to continue using the old name. 6913 realName = pkg.mRealPackage; 6914 if (!pkg.packageName.equals(renamed)) { 6915 // Callers into this function may have already taken 6916 // care of renaming the package; only do it here if 6917 // it is not already done. 6918 pkg.setPackageName(renamed); 6919 } 6920 6921 } else { 6922 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6923 if ((origPackage = mSettings.peekPackageLPr( 6924 pkg.mOriginalPackages.get(i))) != null) { 6925 // We do have the package already installed under its 6926 // original name... should we use it? 6927 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6928 // New package is not compatible with original. 6929 origPackage = null; 6930 continue; 6931 } else if (origPackage.sharedUser != null) { 6932 // Make sure uid is compatible between packages. 6933 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6934 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6935 + " to " + pkg.packageName + ": old uid " 6936 + origPackage.sharedUser.name 6937 + " differs from " + pkg.mSharedUserId); 6938 origPackage = null; 6939 continue; 6940 } 6941 } else { 6942 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6943 + pkg.packageName + " to old name " + origPackage.name); 6944 } 6945 break; 6946 } 6947 } 6948 } 6949 } 6950 6951 if (mTransferedPackages.contains(pkg.packageName)) { 6952 Slog.w(TAG, "Package " + pkg.packageName 6953 + " was transferred to another, but its .apk remains"); 6954 } 6955 6956 // Just create the setting, don't add it yet. For already existing packages 6957 // the PkgSetting exists already and doesn't have to be created. 6958 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6959 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6960 pkg.applicationInfo.primaryCpuAbi, 6961 pkg.applicationInfo.secondaryCpuAbi, 6962 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6963 user, false); 6964 if (pkgSetting == null) { 6965 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6966 "Creating application package " + pkg.packageName + " failed"); 6967 } 6968 6969 if (pkgSetting.origPackage != null) { 6970 // If we are first transitioning from an original package, 6971 // fix up the new package's name now. We need to do this after 6972 // looking up the package under its new name, so getPackageLP 6973 // can take care of fiddling things correctly. 6974 pkg.setPackageName(origPackage.name); 6975 6976 // File a report about this. 6977 String msg = "New package " + pkgSetting.realName 6978 + " renamed to replace old package " + pkgSetting.name; 6979 reportSettingsProblem(Log.WARN, msg); 6980 6981 // Make a note of it. 6982 mTransferedPackages.add(origPackage.name); 6983 6984 // No longer need to retain this. 6985 pkgSetting.origPackage = null; 6986 } 6987 6988 if (realName != null) { 6989 // Make a note of it. 6990 mTransferedPackages.add(pkg.packageName); 6991 } 6992 6993 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6994 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6995 } 6996 6997 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6998 // Check all shared libraries and map to their actual file path. 6999 // We only do this here for apps not on a system dir, because those 7000 // are the only ones that can fail an install due to this. We 7001 // will take care of the system apps by updating all of their 7002 // library paths after the scan is done. 7003 updateSharedLibrariesLPw(pkg, null); 7004 } 7005 7006 if (mFoundPolicyFile) { 7007 SELinuxMMAC.assignSeinfoValue(pkg); 7008 } 7009 7010 pkg.applicationInfo.uid = pkgSetting.appId; 7011 pkg.mExtras = pkgSetting; 7012 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7013 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7014 // We just determined the app is signed correctly, so bring 7015 // over the latest parsed certs. 7016 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7017 } else { 7018 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7019 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7020 "Package " + pkg.packageName + " upgrade keys do not match the " 7021 + "previously installed version"); 7022 } else { 7023 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7024 String msg = "System package " + pkg.packageName 7025 + " signature changed; retaining data."; 7026 reportSettingsProblem(Log.WARN, msg); 7027 } 7028 } 7029 } else { 7030 try { 7031 verifySignaturesLP(pkgSetting, pkg); 7032 // We just determined the app is signed correctly, so bring 7033 // over the latest parsed certs. 7034 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7035 } catch (PackageManagerException e) { 7036 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7037 throw e; 7038 } 7039 // The signature has changed, but this package is in the system 7040 // image... let's recover! 7041 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7042 // However... if this package is part of a shared user, but it 7043 // doesn't match the signature of the shared user, let's fail. 7044 // What this means is that you can't change the signatures 7045 // associated with an overall shared user, which doesn't seem all 7046 // that unreasonable. 7047 if (pkgSetting.sharedUser != null) { 7048 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7049 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7050 throw new PackageManagerException( 7051 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7052 "Signature mismatch for shared user : " 7053 + pkgSetting.sharedUser); 7054 } 7055 } 7056 // File a report about this. 7057 String msg = "System package " + pkg.packageName 7058 + " signature changed; retaining data."; 7059 reportSettingsProblem(Log.WARN, msg); 7060 } 7061 } 7062 // Verify that this new package doesn't have any content providers 7063 // that conflict with existing packages. Only do this if the 7064 // package isn't already installed, since we don't want to break 7065 // things that are installed. 7066 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7067 final int N = pkg.providers.size(); 7068 int i; 7069 for (i=0; i<N; i++) { 7070 PackageParser.Provider p = pkg.providers.get(i); 7071 if (p.info.authority != null) { 7072 String names[] = p.info.authority.split(";"); 7073 for (int j = 0; j < names.length; j++) { 7074 if (mProvidersByAuthority.containsKey(names[j])) { 7075 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7076 final String otherPackageName = 7077 ((other != null && other.getComponentName() != null) ? 7078 other.getComponentName().getPackageName() : "?"); 7079 throw new PackageManagerException( 7080 INSTALL_FAILED_CONFLICTING_PROVIDER, 7081 "Can't install because provider name " + names[j] 7082 + " (in package " + pkg.applicationInfo.packageName 7083 + ") is already used by " + otherPackageName); 7084 } 7085 } 7086 } 7087 } 7088 } 7089 7090 if (pkg.mAdoptPermissions != null) { 7091 // This package wants to adopt ownership of permissions from 7092 // another package. 7093 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7094 final String origName = pkg.mAdoptPermissions.get(i); 7095 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7096 if (orig != null) { 7097 if (verifyPackageUpdateLPr(orig, pkg)) { 7098 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7099 + pkg.packageName); 7100 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7101 } 7102 } 7103 } 7104 } 7105 } 7106 7107 final String pkgName = pkg.packageName; 7108 7109 final long scanFileTime = scanFile.lastModified(); 7110 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7111 pkg.applicationInfo.processName = fixProcessName( 7112 pkg.applicationInfo.packageName, 7113 pkg.applicationInfo.processName, 7114 pkg.applicationInfo.uid); 7115 7116 if (pkg != mPlatformPackage) { 7117 // This is a normal package, need to make its data directory. 7118 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7119 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7120 7121 boolean uidError = false; 7122 if (dataPath.exists()) { 7123 int currentUid = 0; 7124 try { 7125 StructStat stat = Os.stat(dataPath.getPath()); 7126 currentUid = stat.st_uid; 7127 } catch (ErrnoException e) { 7128 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7129 } 7130 7131 // If we have mismatched owners for the data path, we have a problem. 7132 if (currentUid != pkg.applicationInfo.uid) { 7133 boolean recovered = false; 7134 if (currentUid == 0) { 7135 // The directory somehow became owned by root. Wow. 7136 // This is probably because the system was stopped while 7137 // installd was in the middle of messing with its libs 7138 // directory. Ask installd to fix that. 7139 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7140 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7141 if (ret >= 0) { 7142 recovered = true; 7143 String msg = "Package " + pkg.packageName 7144 + " unexpectedly changed to uid 0; recovered to " + 7145 + pkg.applicationInfo.uid; 7146 reportSettingsProblem(Log.WARN, msg); 7147 } 7148 } 7149 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7150 || (scanFlags&SCAN_BOOTING) != 0)) { 7151 // If this is a system app, we can at least delete its 7152 // current data so the application will still work. 7153 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7154 if (ret >= 0) { 7155 // TODO: Kill the processes first 7156 // Old data gone! 7157 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7158 ? "System package " : "Third party package "; 7159 String msg = prefix + pkg.packageName 7160 + " has changed from uid: " 7161 + currentUid + " to " 7162 + pkg.applicationInfo.uid + "; old data erased"; 7163 reportSettingsProblem(Log.WARN, msg); 7164 recovered = true; 7165 } 7166 if (!recovered) { 7167 mHasSystemUidErrors = true; 7168 } 7169 } else if (!recovered) { 7170 // If we allow this install to proceed, we will be broken. 7171 // Abort, abort! 7172 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7173 "scanPackageLI"); 7174 } 7175 if (!recovered) { 7176 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7177 + pkg.applicationInfo.uid + "/fs_" 7178 + currentUid; 7179 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7180 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7181 String msg = "Package " + pkg.packageName 7182 + " has mismatched uid: " 7183 + currentUid + " on disk, " 7184 + pkg.applicationInfo.uid + " in settings"; 7185 // writer 7186 synchronized (mPackages) { 7187 mSettings.mReadMessages.append(msg); 7188 mSettings.mReadMessages.append('\n'); 7189 uidError = true; 7190 if (!pkgSetting.uidError) { 7191 reportSettingsProblem(Log.ERROR, msg); 7192 } 7193 } 7194 } 7195 } 7196 7197 // Ensure that directories are prepared 7198 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7199 pkg.applicationInfo.seinfo); 7200 7201 if (mShouldRestoreconData) { 7202 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7203 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7204 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7205 } 7206 } else { 7207 if (DEBUG_PACKAGE_SCANNING) { 7208 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7209 Log.v(TAG, "Want this data dir: " + dataPath); 7210 } 7211 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7212 pkg.applicationInfo.seinfo); 7213 } 7214 7215 // Get all of our default paths setup 7216 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7217 7218 pkgSetting.uidError = uidError; 7219 } 7220 7221 final String path = scanFile.getPath(); 7222 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7223 7224 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7225 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7226 7227 // Some system apps still use directory structure for native libraries 7228 // in which case we might end up not detecting abi solely based on apk 7229 // structure. Try to detect abi based on directory structure. 7230 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7231 pkg.applicationInfo.primaryCpuAbi == null) { 7232 setBundledAppAbisAndRoots(pkg, pkgSetting); 7233 setNativeLibraryPaths(pkg); 7234 } 7235 7236 } else { 7237 if ((scanFlags & SCAN_MOVE) != 0) { 7238 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7239 // but we already have this packages package info in the PackageSetting. We just 7240 // use that and derive the native library path based on the new codepath. 7241 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7242 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7243 } 7244 7245 // Set native library paths again. For moves, the path will be updated based on the 7246 // ABIs we've determined above. For non-moves, the path will be updated based on the 7247 // ABIs we determined during compilation, but the path will depend on the final 7248 // package path (after the rename away from the stage path). 7249 setNativeLibraryPaths(pkg); 7250 } 7251 7252 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7253 final int[] userIds = sUserManager.getUserIds(); 7254 synchronized (mInstallLock) { 7255 // Make sure all user data directories are ready to roll; we're okay 7256 // if they already exist 7257 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7258 for (int userId : userIds) { 7259 if (userId != UserHandle.USER_SYSTEM) { 7260 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7261 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7262 pkg.applicationInfo.seinfo); 7263 } 7264 } 7265 } 7266 7267 // Create a native library symlink only if we have native libraries 7268 // and if the native libraries are 32 bit libraries. We do not provide 7269 // this symlink for 64 bit libraries. 7270 if (pkg.applicationInfo.primaryCpuAbi != null && 7271 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7273 try { 7274 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7275 for (int userId : userIds) { 7276 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7277 nativeLibPath, userId) < 0) { 7278 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7279 "Failed linking native library dir (user=" + userId + ")"); 7280 } 7281 } 7282 } finally { 7283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7284 } 7285 } 7286 } 7287 7288 // This is a special case for the "system" package, where the ABI is 7289 // dictated by the zygote configuration (and init.rc). We should keep track 7290 // of this ABI so that we can deal with "normal" applications that run under 7291 // the same UID correctly. 7292 if (mPlatformPackage == pkg) { 7293 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7294 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7295 } 7296 7297 // If there's a mismatch between the abi-override in the package setting 7298 // and the abiOverride specified for the install. Warn about this because we 7299 // would've already compiled the app without taking the package setting into 7300 // account. 7301 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7302 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7303 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7304 " for package: " + pkg.packageName); 7305 } 7306 } 7307 7308 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7309 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7310 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7311 7312 // Copy the derived override back to the parsed package, so that we can 7313 // update the package settings accordingly. 7314 pkg.cpuAbiOverride = cpuAbiOverride; 7315 7316 if (DEBUG_ABI_SELECTION) { 7317 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7318 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7319 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7320 } 7321 7322 // Push the derived path down into PackageSettings so we know what to 7323 // clean up at uninstall time. 7324 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7325 7326 if (DEBUG_ABI_SELECTION) { 7327 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7328 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7329 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7330 } 7331 7332 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7333 // We don't do this here during boot because we can do it all 7334 // at once after scanning all existing packages. 7335 // 7336 // We also do this *before* we perform dexopt on this package, so that 7337 // we can avoid redundant dexopts, and also to make sure we've got the 7338 // code and package path correct. 7339 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7340 pkg, true /* boot complete */); 7341 } 7342 7343 if (mFactoryTest && pkg.requestedPermissions.contains( 7344 android.Manifest.permission.FACTORY_TEST)) { 7345 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7346 } 7347 7348 ArrayList<PackageParser.Package> clientLibPkgs = null; 7349 7350 // writer 7351 synchronized (mPackages) { 7352 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7353 // Only system apps can add new shared libraries. 7354 if (pkg.libraryNames != null) { 7355 for (int i=0; i<pkg.libraryNames.size(); i++) { 7356 String name = pkg.libraryNames.get(i); 7357 boolean allowed = false; 7358 if (pkg.isUpdatedSystemApp()) { 7359 // New library entries can only be added through the 7360 // system image. This is important to get rid of a lot 7361 // of nasty edge cases: for example if we allowed a non- 7362 // system update of the app to add a library, then uninstalling 7363 // the update would make the library go away, and assumptions 7364 // we made such as through app install filtering would now 7365 // have allowed apps on the device which aren't compatible 7366 // with it. Better to just have the restriction here, be 7367 // conservative, and create many fewer cases that can negatively 7368 // impact the user experience. 7369 final PackageSetting sysPs = mSettings 7370 .getDisabledSystemPkgLPr(pkg.packageName); 7371 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7372 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7373 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7374 allowed = true; 7375 break; 7376 } 7377 } 7378 } 7379 } else { 7380 allowed = true; 7381 } 7382 if (allowed) { 7383 if (!mSharedLibraries.containsKey(name)) { 7384 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7385 } else if (!name.equals(pkg.packageName)) { 7386 Slog.w(TAG, "Package " + pkg.packageName + " library " 7387 + name + " already exists; skipping"); 7388 } 7389 } else { 7390 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7391 + name + " that is not declared on system image; skipping"); 7392 } 7393 } 7394 if ((scanFlags & SCAN_BOOTING) == 0) { 7395 // If we are not booting, we need to update any applications 7396 // that are clients of our shared library. If we are booting, 7397 // this will all be done once the scan is complete. 7398 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7399 } 7400 } 7401 } 7402 } 7403 7404 // Request the ActivityManager to kill the process(only for existing packages) 7405 // so that we do not end up in a confused state while the user is still using the older 7406 // version of the application while the new one gets installed. 7407 if ((scanFlags & SCAN_REPLACING) != 0) { 7408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7409 7410 killApplication(pkg.applicationInfo.packageName, 7411 pkg.applicationInfo.uid, "replace pkg"); 7412 7413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7414 } 7415 7416 // Also need to kill any apps that are dependent on the library. 7417 if (clientLibPkgs != null) { 7418 for (int i=0; i<clientLibPkgs.size(); i++) { 7419 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7420 killApplication(clientPkg.applicationInfo.packageName, 7421 clientPkg.applicationInfo.uid, "update lib"); 7422 } 7423 } 7424 7425 // Make sure we're not adding any bogus keyset info 7426 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7427 ksms.assertScannedPackageValid(pkg); 7428 7429 // writer 7430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7431 7432 boolean createIdmapFailed = false; 7433 synchronized (mPackages) { 7434 // We don't expect installation to fail beyond this point 7435 7436 // Add the new setting to mSettings 7437 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7438 // Add the new setting to mPackages 7439 mPackages.put(pkg.applicationInfo.packageName, pkg); 7440 // Make sure we don't accidentally delete its data. 7441 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7442 while (iter.hasNext()) { 7443 PackageCleanItem item = iter.next(); 7444 if (pkgName.equals(item.packageName)) { 7445 iter.remove(); 7446 } 7447 } 7448 7449 // Take care of first install / last update times. 7450 if (currentTime != 0) { 7451 if (pkgSetting.firstInstallTime == 0) { 7452 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7453 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7454 pkgSetting.lastUpdateTime = currentTime; 7455 } 7456 } else if (pkgSetting.firstInstallTime == 0) { 7457 // We need *something*. Take time time stamp of the file. 7458 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7459 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7460 if (scanFileTime != pkgSetting.timeStamp) { 7461 // A package on the system image has changed; consider this 7462 // to be an update. 7463 pkgSetting.lastUpdateTime = scanFileTime; 7464 } 7465 } 7466 7467 // Add the package's KeySets to the global KeySetManagerService 7468 ksms.addScannedPackageLPw(pkg); 7469 7470 int N = pkg.providers.size(); 7471 StringBuilder r = null; 7472 int i; 7473 for (i=0; i<N; i++) { 7474 PackageParser.Provider p = pkg.providers.get(i); 7475 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7476 p.info.processName, pkg.applicationInfo.uid); 7477 mProviders.addProvider(p); 7478 p.syncable = p.info.isSyncable; 7479 if (p.info.authority != null) { 7480 String names[] = p.info.authority.split(";"); 7481 p.info.authority = null; 7482 for (int j = 0; j < names.length; j++) { 7483 if (j == 1 && p.syncable) { 7484 // We only want the first authority for a provider to possibly be 7485 // syncable, so if we already added this provider using a different 7486 // authority clear the syncable flag. We copy the provider before 7487 // changing it because the mProviders object contains a reference 7488 // to a provider that we don't want to change. 7489 // Only do this for the second authority since the resulting provider 7490 // object can be the same for all future authorities for this provider. 7491 p = new PackageParser.Provider(p); 7492 p.syncable = false; 7493 } 7494 if (!mProvidersByAuthority.containsKey(names[j])) { 7495 mProvidersByAuthority.put(names[j], p); 7496 if (p.info.authority == null) { 7497 p.info.authority = names[j]; 7498 } else { 7499 p.info.authority = p.info.authority + ";" + names[j]; 7500 } 7501 if (DEBUG_PACKAGE_SCANNING) { 7502 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7503 Log.d(TAG, "Registered content provider: " + names[j] 7504 + ", className = " + p.info.name + ", isSyncable = " 7505 + p.info.isSyncable); 7506 } 7507 } else { 7508 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7509 Slog.w(TAG, "Skipping provider name " + names[j] + 7510 " (in package " + pkg.applicationInfo.packageName + 7511 "): name already used by " 7512 + ((other != null && other.getComponentName() != null) 7513 ? other.getComponentName().getPackageName() : "?")); 7514 } 7515 } 7516 } 7517 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7518 if (r == null) { 7519 r = new StringBuilder(256); 7520 } else { 7521 r.append(' '); 7522 } 7523 r.append(p.info.name); 7524 } 7525 } 7526 if (r != null) { 7527 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7528 } 7529 7530 N = pkg.services.size(); 7531 r = null; 7532 for (i=0; i<N; i++) { 7533 PackageParser.Service s = pkg.services.get(i); 7534 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7535 s.info.processName, pkg.applicationInfo.uid); 7536 mServices.addService(s); 7537 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7538 if (r == null) { 7539 r = new StringBuilder(256); 7540 } else { 7541 r.append(' '); 7542 } 7543 r.append(s.info.name); 7544 } 7545 } 7546 if (r != null) { 7547 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7548 } 7549 7550 N = pkg.receivers.size(); 7551 r = null; 7552 for (i=0; i<N; i++) { 7553 PackageParser.Activity a = pkg.receivers.get(i); 7554 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7555 a.info.processName, pkg.applicationInfo.uid); 7556 mReceivers.addActivity(a, "receiver"); 7557 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7558 if (r == null) { 7559 r = new StringBuilder(256); 7560 } else { 7561 r.append(' '); 7562 } 7563 r.append(a.info.name); 7564 } 7565 } 7566 if (r != null) { 7567 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7568 } 7569 7570 N = pkg.activities.size(); 7571 r = null; 7572 for (i=0; i<N; i++) { 7573 PackageParser.Activity a = pkg.activities.get(i); 7574 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7575 a.info.processName, pkg.applicationInfo.uid); 7576 mActivities.addActivity(a, "activity"); 7577 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7578 if (r == null) { 7579 r = new StringBuilder(256); 7580 } else { 7581 r.append(' '); 7582 } 7583 r.append(a.info.name); 7584 } 7585 } 7586 if (r != null) { 7587 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7588 } 7589 7590 N = pkg.permissionGroups.size(); 7591 r = null; 7592 for (i=0; i<N; i++) { 7593 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7594 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7595 if (cur == null) { 7596 mPermissionGroups.put(pg.info.name, pg); 7597 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7598 if (r == null) { 7599 r = new StringBuilder(256); 7600 } else { 7601 r.append(' '); 7602 } 7603 r.append(pg.info.name); 7604 } 7605 } else { 7606 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7607 + pg.info.packageName + " ignored: original from " 7608 + cur.info.packageName); 7609 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7610 if (r == null) { 7611 r = new StringBuilder(256); 7612 } else { 7613 r.append(' '); 7614 } 7615 r.append("DUP:"); 7616 r.append(pg.info.name); 7617 } 7618 } 7619 } 7620 if (r != null) { 7621 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7622 } 7623 7624 N = pkg.permissions.size(); 7625 r = null; 7626 for (i=0; i<N; i++) { 7627 PackageParser.Permission p = pkg.permissions.get(i); 7628 7629 // Assume by default that we did not install this permission into the system. 7630 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7631 7632 // Now that permission groups have a special meaning, we ignore permission 7633 // groups for legacy apps to prevent unexpected behavior. In particular, 7634 // permissions for one app being granted to someone just becuase they happen 7635 // to be in a group defined by another app (before this had no implications). 7636 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7637 p.group = mPermissionGroups.get(p.info.group); 7638 // Warn for a permission in an unknown group. 7639 if (p.info.group != null && p.group == null) { 7640 Slog.w(TAG, "Permission " + p.info.name + " from package " 7641 + p.info.packageName + " in an unknown group " + p.info.group); 7642 } 7643 } 7644 7645 ArrayMap<String, BasePermission> permissionMap = 7646 p.tree ? mSettings.mPermissionTrees 7647 : mSettings.mPermissions; 7648 BasePermission bp = permissionMap.get(p.info.name); 7649 7650 // Allow system apps to redefine non-system permissions 7651 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7652 final boolean currentOwnerIsSystem = (bp.perm != null 7653 && isSystemApp(bp.perm.owner)); 7654 if (isSystemApp(p.owner)) { 7655 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7656 // It's a built-in permission and no owner, take ownership now 7657 bp.packageSetting = pkgSetting; 7658 bp.perm = p; 7659 bp.uid = pkg.applicationInfo.uid; 7660 bp.sourcePackage = p.info.packageName; 7661 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7662 } else if (!currentOwnerIsSystem) { 7663 String msg = "New decl " + p.owner + " of permission " 7664 + p.info.name + " is system; overriding " + bp.sourcePackage; 7665 reportSettingsProblem(Log.WARN, msg); 7666 bp = null; 7667 } 7668 } 7669 } 7670 7671 if (bp == null) { 7672 bp = new BasePermission(p.info.name, p.info.packageName, 7673 BasePermission.TYPE_NORMAL); 7674 permissionMap.put(p.info.name, bp); 7675 } 7676 7677 if (bp.perm == null) { 7678 if (bp.sourcePackage == null 7679 || bp.sourcePackage.equals(p.info.packageName)) { 7680 BasePermission tree = findPermissionTreeLP(p.info.name); 7681 if (tree == null 7682 || tree.sourcePackage.equals(p.info.packageName)) { 7683 bp.packageSetting = pkgSetting; 7684 bp.perm = p; 7685 bp.uid = pkg.applicationInfo.uid; 7686 bp.sourcePackage = p.info.packageName; 7687 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7688 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7689 if (r == null) { 7690 r = new StringBuilder(256); 7691 } else { 7692 r.append(' '); 7693 } 7694 r.append(p.info.name); 7695 } 7696 } else { 7697 Slog.w(TAG, "Permission " + p.info.name + " from package " 7698 + p.info.packageName + " ignored: base tree " 7699 + tree.name + " is from package " 7700 + tree.sourcePackage); 7701 } 7702 } else { 7703 Slog.w(TAG, "Permission " + p.info.name + " from package " 7704 + p.info.packageName + " ignored: original from " 7705 + bp.sourcePackage); 7706 } 7707 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7708 if (r == null) { 7709 r = new StringBuilder(256); 7710 } else { 7711 r.append(' '); 7712 } 7713 r.append("DUP:"); 7714 r.append(p.info.name); 7715 } 7716 if (bp.perm == p) { 7717 bp.protectionLevel = p.info.protectionLevel; 7718 } 7719 } 7720 7721 if (r != null) { 7722 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7723 } 7724 7725 N = pkg.instrumentation.size(); 7726 r = null; 7727 for (i=0; i<N; i++) { 7728 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7729 a.info.packageName = pkg.applicationInfo.packageName; 7730 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7731 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7732 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7733 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7734 a.info.dataDir = pkg.applicationInfo.dataDir; 7735 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7736 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7737 7738 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7739 // need other information about the application, like the ABI and what not ? 7740 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7741 mInstrumentation.put(a.getComponentName(), a); 7742 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7743 if (r == null) { 7744 r = new StringBuilder(256); 7745 } else { 7746 r.append(' '); 7747 } 7748 r.append(a.info.name); 7749 } 7750 } 7751 if (r != null) { 7752 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7753 } 7754 7755 if (pkg.protectedBroadcasts != null) { 7756 N = pkg.protectedBroadcasts.size(); 7757 for (i=0; i<N; i++) { 7758 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7759 } 7760 } 7761 7762 pkgSetting.setTimeStamp(scanFileTime); 7763 7764 // Create idmap files for pairs of (packages, overlay packages). 7765 // Note: "android", ie framework-res.apk, is handled by native layers. 7766 if (pkg.mOverlayTarget != null) { 7767 // This is an overlay package. 7768 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7769 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7770 mOverlays.put(pkg.mOverlayTarget, 7771 new ArrayMap<String, PackageParser.Package>()); 7772 } 7773 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7774 map.put(pkg.packageName, pkg); 7775 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7776 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7777 createIdmapFailed = true; 7778 } 7779 } 7780 } else if (mOverlays.containsKey(pkg.packageName) && 7781 !pkg.packageName.equals("android")) { 7782 // This is a regular package, with one or more known overlay packages. 7783 createIdmapsForPackageLI(pkg); 7784 } 7785 } 7786 7787 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7788 7789 if (createIdmapFailed) { 7790 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7791 "scanPackageLI failed to createIdmap"); 7792 } 7793 return pkg; 7794 } 7795 7796 /** 7797 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7798 * is derived purely on the basis of the contents of {@code scanFile} and 7799 * {@code cpuAbiOverride}. 7800 * 7801 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7802 */ 7803 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7804 String cpuAbiOverride, boolean extractLibs) 7805 throws PackageManagerException { 7806 // TODO: We can probably be smarter about this stuff. For installed apps, 7807 // we can calculate this information at install time once and for all. For 7808 // system apps, we can probably assume that this information doesn't change 7809 // after the first boot scan. As things stand, we do lots of unnecessary work. 7810 7811 // Give ourselves some initial paths; we'll come back for another 7812 // pass once we've determined ABI below. 7813 setNativeLibraryPaths(pkg); 7814 7815 // We would never need to extract libs for forward-locked and external packages, 7816 // since the container service will do it for us. We shouldn't attempt to 7817 // extract libs from system app when it was not updated. 7818 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7819 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7820 extractLibs = false; 7821 } 7822 7823 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7824 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7825 7826 NativeLibraryHelper.Handle handle = null; 7827 try { 7828 handle = NativeLibraryHelper.Handle.create(pkg); 7829 // TODO(multiArch): This can be null for apps that didn't go through the 7830 // usual installation process. We can calculate it again, like we 7831 // do during install time. 7832 // 7833 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7834 // unnecessary. 7835 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7836 7837 // Null out the abis so that they can be recalculated. 7838 pkg.applicationInfo.primaryCpuAbi = null; 7839 pkg.applicationInfo.secondaryCpuAbi = null; 7840 if (isMultiArch(pkg.applicationInfo)) { 7841 // Warn if we've set an abiOverride for multi-lib packages.. 7842 // By definition, we need to copy both 32 and 64 bit libraries for 7843 // such packages. 7844 if (pkg.cpuAbiOverride != null 7845 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7846 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7847 } 7848 7849 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7850 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7851 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7852 if (extractLibs) { 7853 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7854 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7855 useIsaSpecificSubdirs); 7856 } else { 7857 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7858 } 7859 } 7860 7861 maybeThrowExceptionForMultiArchCopy( 7862 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7863 7864 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7865 if (extractLibs) { 7866 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7867 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7868 useIsaSpecificSubdirs); 7869 } else { 7870 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7871 } 7872 } 7873 7874 maybeThrowExceptionForMultiArchCopy( 7875 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7876 7877 if (abi64 >= 0) { 7878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7879 } 7880 7881 if (abi32 >= 0) { 7882 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7883 if (abi64 >= 0) { 7884 pkg.applicationInfo.secondaryCpuAbi = abi; 7885 } else { 7886 pkg.applicationInfo.primaryCpuAbi = abi; 7887 } 7888 } 7889 } else { 7890 String[] abiList = (cpuAbiOverride != null) ? 7891 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7892 7893 // Enable gross and lame hacks for apps that are built with old 7894 // SDK tools. We must scan their APKs for renderscript bitcode and 7895 // not launch them if it's present. Don't bother checking on devices 7896 // that don't have 64 bit support. 7897 boolean needsRenderScriptOverride = false; 7898 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7899 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7900 abiList = Build.SUPPORTED_32_BIT_ABIS; 7901 needsRenderScriptOverride = true; 7902 } 7903 7904 final int copyRet; 7905 if (extractLibs) { 7906 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7907 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7908 } else { 7909 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7910 } 7911 7912 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7913 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7914 "Error unpackaging native libs for app, errorCode=" + copyRet); 7915 } 7916 7917 if (copyRet >= 0) { 7918 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7919 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7920 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7921 } else if (needsRenderScriptOverride) { 7922 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7923 } 7924 } 7925 } catch (IOException ioe) { 7926 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7927 } finally { 7928 IoUtils.closeQuietly(handle); 7929 } 7930 7931 // Now that we've calculated the ABIs and determined if it's an internal app, 7932 // we will go ahead and populate the nativeLibraryPath. 7933 setNativeLibraryPaths(pkg); 7934 } 7935 7936 /** 7937 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7938 * i.e, so that all packages can be run inside a single process if required. 7939 * 7940 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7941 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7942 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7943 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7944 * updating a package that belongs to a shared user. 7945 * 7946 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7947 * adds unnecessary complexity. 7948 */ 7949 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7950 PackageParser.Package scannedPackage, boolean bootComplete) { 7951 String requiredInstructionSet = null; 7952 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7953 requiredInstructionSet = VMRuntime.getInstructionSet( 7954 scannedPackage.applicationInfo.primaryCpuAbi); 7955 } 7956 7957 PackageSetting requirer = null; 7958 for (PackageSetting ps : packagesForUser) { 7959 // If packagesForUser contains scannedPackage, we skip it. This will happen 7960 // when scannedPackage is an update of an existing package. Without this check, 7961 // we will never be able to change the ABI of any package belonging to a shared 7962 // user, even if it's compatible with other packages. 7963 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7964 if (ps.primaryCpuAbiString == null) { 7965 continue; 7966 } 7967 7968 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7969 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7970 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7971 // this but there's not much we can do. 7972 String errorMessage = "Instruction set mismatch, " 7973 + ((requirer == null) ? "[caller]" : requirer) 7974 + " requires " + requiredInstructionSet + " whereas " + ps 7975 + " requires " + instructionSet; 7976 Slog.w(TAG, errorMessage); 7977 } 7978 7979 if (requiredInstructionSet == null) { 7980 requiredInstructionSet = instructionSet; 7981 requirer = ps; 7982 } 7983 } 7984 } 7985 7986 if (requiredInstructionSet != null) { 7987 String adjustedAbi; 7988 if (requirer != null) { 7989 // requirer != null implies that either scannedPackage was null or that scannedPackage 7990 // did not require an ABI, in which case we have to adjust scannedPackage to match 7991 // the ABI of the set (which is the same as requirer's ABI) 7992 adjustedAbi = requirer.primaryCpuAbiString; 7993 if (scannedPackage != null) { 7994 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7995 } 7996 } else { 7997 // requirer == null implies that we're updating all ABIs in the set to 7998 // match scannedPackage. 7999 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8000 } 8001 8002 for (PackageSetting ps : packagesForUser) { 8003 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8004 if (ps.primaryCpuAbiString != null) { 8005 continue; 8006 } 8007 8008 ps.primaryCpuAbiString = adjustedAbi; 8009 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8010 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8011 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8012 mInstaller.rmdex(ps.codePathString, 8013 getDexCodeInstructionSet(getPreferredInstructionSet())); 8014 } 8015 } 8016 } 8017 } 8018 } 8019 8020 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8021 synchronized (mPackages) { 8022 mResolverReplaced = true; 8023 // Set up information for custom user intent resolution activity. 8024 mResolveActivity.applicationInfo = pkg.applicationInfo; 8025 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8026 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8027 mResolveActivity.processName = pkg.applicationInfo.packageName; 8028 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8029 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8030 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8031 mResolveActivity.theme = 0; 8032 mResolveActivity.exported = true; 8033 mResolveActivity.enabled = true; 8034 mResolveInfo.activityInfo = mResolveActivity; 8035 mResolveInfo.priority = 0; 8036 mResolveInfo.preferredOrder = 0; 8037 mResolveInfo.match = 0; 8038 mResolveComponentName = mCustomResolverComponentName; 8039 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8040 mResolveComponentName); 8041 } 8042 } 8043 8044 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8045 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8046 8047 // Set up information for ephemeral installer activity 8048 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8049 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8050 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8051 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8052 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8053 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8054 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8055 mEphemeralInstallerActivity.theme = 0; 8056 mEphemeralInstallerActivity.exported = true; 8057 mEphemeralInstallerActivity.enabled = true; 8058 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8059 mEphemeralInstallerInfo.priority = 0; 8060 mEphemeralInstallerInfo.preferredOrder = 0; 8061 mEphemeralInstallerInfo.match = 0; 8062 8063 if (DEBUG_EPHEMERAL) { 8064 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8065 } 8066 } 8067 8068 private static String calculateBundledApkRoot(final String codePathString) { 8069 final File codePath = new File(codePathString); 8070 final File codeRoot; 8071 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8072 codeRoot = Environment.getRootDirectory(); 8073 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8074 codeRoot = Environment.getOemDirectory(); 8075 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8076 codeRoot = Environment.getVendorDirectory(); 8077 } else { 8078 // Unrecognized code path; take its top real segment as the apk root: 8079 // e.g. /something/app/blah.apk => /something 8080 try { 8081 File f = codePath.getCanonicalFile(); 8082 File parent = f.getParentFile(); // non-null because codePath is a file 8083 File tmp; 8084 while ((tmp = parent.getParentFile()) != null) { 8085 f = parent; 8086 parent = tmp; 8087 } 8088 codeRoot = f; 8089 Slog.w(TAG, "Unrecognized code path " 8090 + codePath + " - using " + codeRoot); 8091 } catch (IOException e) { 8092 // Can't canonicalize the code path -- shenanigans? 8093 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8094 return Environment.getRootDirectory().getPath(); 8095 } 8096 } 8097 return codeRoot.getPath(); 8098 } 8099 8100 /** 8101 * Derive and set the location of native libraries for the given package, 8102 * which varies depending on where and how the package was installed. 8103 */ 8104 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8105 final ApplicationInfo info = pkg.applicationInfo; 8106 final String codePath = pkg.codePath; 8107 final File codeFile = new File(codePath); 8108 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8109 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8110 8111 info.nativeLibraryRootDir = null; 8112 info.nativeLibraryRootRequiresIsa = false; 8113 info.nativeLibraryDir = null; 8114 info.secondaryNativeLibraryDir = null; 8115 8116 if (isApkFile(codeFile)) { 8117 // Monolithic install 8118 if (bundledApp) { 8119 // If "/system/lib64/apkname" exists, assume that is the per-package 8120 // native library directory to use; otherwise use "/system/lib/apkname". 8121 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8122 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8123 getPrimaryInstructionSet(info)); 8124 8125 // This is a bundled system app so choose the path based on the ABI. 8126 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8127 // is just the default path. 8128 final String apkName = deriveCodePathName(codePath); 8129 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8130 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8131 apkName).getAbsolutePath(); 8132 8133 if (info.secondaryCpuAbi != null) { 8134 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8135 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8136 secondaryLibDir, apkName).getAbsolutePath(); 8137 } 8138 } else if (asecApp) { 8139 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8140 .getAbsolutePath(); 8141 } else { 8142 final String apkName = deriveCodePathName(codePath); 8143 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8144 .getAbsolutePath(); 8145 } 8146 8147 info.nativeLibraryRootRequiresIsa = false; 8148 info.nativeLibraryDir = info.nativeLibraryRootDir; 8149 } else { 8150 // Cluster install 8151 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8152 info.nativeLibraryRootRequiresIsa = true; 8153 8154 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8155 getPrimaryInstructionSet(info)).getAbsolutePath(); 8156 8157 if (info.secondaryCpuAbi != null) { 8158 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8159 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8160 } 8161 } 8162 } 8163 8164 /** 8165 * Calculate the abis and roots for a bundled app. These can uniquely 8166 * be determined from the contents of the system partition, i.e whether 8167 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8168 * of this information, and instead assume that the system was built 8169 * sensibly. 8170 */ 8171 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8172 PackageSetting pkgSetting) { 8173 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8174 8175 // If "/system/lib64/apkname" exists, assume that is the per-package 8176 // native library directory to use; otherwise use "/system/lib/apkname". 8177 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8178 setBundledAppAbi(pkg, apkRoot, apkName); 8179 // pkgSetting might be null during rescan following uninstall of updates 8180 // to a bundled app, so accommodate that possibility. The settings in 8181 // that case will be established later from the parsed package. 8182 // 8183 // If the settings aren't null, sync them up with what we've just derived. 8184 // note that apkRoot isn't stored in the package settings. 8185 if (pkgSetting != null) { 8186 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8187 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8188 } 8189 } 8190 8191 /** 8192 * Deduces the ABI of a bundled app and sets the relevant fields on the 8193 * parsed pkg object. 8194 * 8195 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8196 * under which system libraries are installed. 8197 * @param apkName the name of the installed package. 8198 */ 8199 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8200 final File codeFile = new File(pkg.codePath); 8201 8202 final boolean has64BitLibs; 8203 final boolean has32BitLibs; 8204 if (isApkFile(codeFile)) { 8205 // Monolithic install 8206 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8207 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8208 } else { 8209 // Cluster install 8210 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8211 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8212 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8213 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8214 has64BitLibs = (new File(rootDir, isa)).exists(); 8215 } else { 8216 has64BitLibs = false; 8217 } 8218 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8219 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8220 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8221 has32BitLibs = (new File(rootDir, isa)).exists(); 8222 } else { 8223 has32BitLibs = false; 8224 } 8225 } 8226 8227 if (has64BitLibs && !has32BitLibs) { 8228 // The package has 64 bit libs, but not 32 bit libs. Its primary 8229 // ABI should be 64 bit. We can safely assume here that the bundled 8230 // native libraries correspond to the most preferred ABI in the list. 8231 8232 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8233 pkg.applicationInfo.secondaryCpuAbi = null; 8234 } else if (has32BitLibs && !has64BitLibs) { 8235 // The package has 32 bit libs but not 64 bit libs. Its primary 8236 // ABI should be 32 bit. 8237 8238 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8239 pkg.applicationInfo.secondaryCpuAbi = null; 8240 } else if (has32BitLibs && has64BitLibs) { 8241 // The application has both 64 and 32 bit bundled libraries. We check 8242 // here that the app declares multiArch support, and warn if it doesn't. 8243 // 8244 // We will be lenient here and record both ABIs. The primary will be the 8245 // ABI that's higher on the list, i.e, a device that's configured to prefer 8246 // 64 bit apps will see a 64 bit primary ABI, 8247 8248 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8249 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8250 } 8251 8252 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8254 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8255 } else { 8256 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8257 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8258 } 8259 } else { 8260 pkg.applicationInfo.primaryCpuAbi = null; 8261 pkg.applicationInfo.secondaryCpuAbi = null; 8262 } 8263 } 8264 8265 private void killApplication(String pkgName, int appId, String reason) { 8266 // Request the ActivityManager to kill the process(only for existing packages) 8267 // so that we do not end up in a confused state while the user is still using the older 8268 // version of the application while the new one gets installed. 8269 IActivityManager am = ActivityManagerNative.getDefault(); 8270 if (am != null) { 8271 try { 8272 am.killApplicationWithAppId(pkgName, appId, reason); 8273 } catch (RemoteException e) { 8274 } 8275 } 8276 } 8277 8278 void removePackageLI(PackageSetting ps, boolean chatty) { 8279 if (DEBUG_INSTALL) { 8280 if (chatty) 8281 Log.d(TAG, "Removing package " + ps.name); 8282 } 8283 8284 // writer 8285 synchronized (mPackages) { 8286 mPackages.remove(ps.name); 8287 final PackageParser.Package pkg = ps.pkg; 8288 if (pkg != null) { 8289 cleanPackageDataStructuresLILPw(pkg, chatty); 8290 } 8291 } 8292 } 8293 8294 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8295 if (DEBUG_INSTALL) { 8296 if (chatty) 8297 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8298 } 8299 8300 // writer 8301 synchronized (mPackages) { 8302 mPackages.remove(pkg.applicationInfo.packageName); 8303 cleanPackageDataStructuresLILPw(pkg, chatty); 8304 } 8305 } 8306 8307 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8308 int N = pkg.providers.size(); 8309 StringBuilder r = null; 8310 int i; 8311 for (i=0; i<N; i++) { 8312 PackageParser.Provider p = pkg.providers.get(i); 8313 mProviders.removeProvider(p); 8314 if (p.info.authority == null) { 8315 8316 /* There was another ContentProvider with this authority when 8317 * this app was installed so this authority is null, 8318 * Ignore it as we don't have to unregister the provider. 8319 */ 8320 continue; 8321 } 8322 String names[] = p.info.authority.split(";"); 8323 for (int j = 0; j < names.length; j++) { 8324 if (mProvidersByAuthority.get(names[j]) == p) { 8325 mProvidersByAuthority.remove(names[j]); 8326 if (DEBUG_REMOVE) { 8327 if (chatty) 8328 Log.d(TAG, "Unregistered content provider: " + names[j] 8329 + ", className = " + p.info.name + ", isSyncable = " 8330 + p.info.isSyncable); 8331 } 8332 } 8333 } 8334 if (DEBUG_REMOVE && chatty) { 8335 if (r == null) { 8336 r = new StringBuilder(256); 8337 } else { 8338 r.append(' '); 8339 } 8340 r.append(p.info.name); 8341 } 8342 } 8343 if (r != null) { 8344 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8345 } 8346 8347 N = pkg.services.size(); 8348 r = null; 8349 for (i=0; i<N; i++) { 8350 PackageParser.Service s = pkg.services.get(i); 8351 mServices.removeService(s); 8352 if (chatty) { 8353 if (r == null) { 8354 r = new StringBuilder(256); 8355 } else { 8356 r.append(' '); 8357 } 8358 r.append(s.info.name); 8359 } 8360 } 8361 if (r != null) { 8362 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8363 } 8364 8365 N = pkg.receivers.size(); 8366 r = null; 8367 for (i=0; i<N; i++) { 8368 PackageParser.Activity a = pkg.receivers.get(i); 8369 mReceivers.removeActivity(a, "receiver"); 8370 if (DEBUG_REMOVE && chatty) { 8371 if (r == null) { 8372 r = new StringBuilder(256); 8373 } else { 8374 r.append(' '); 8375 } 8376 r.append(a.info.name); 8377 } 8378 } 8379 if (r != null) { 8380 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8381 } 8382 8383 N = pkg.activities.size(); 8384 r = null; 8385 for (i=0; i<N; i++) { 8386 PackageParser.Activity a = pkg.activities.get(i); 8387 mActivities.removeActivity(a, "activity"); 8388 if (DEBUG_REMOVE && chatty) { 8389 if (r == null) { 8390 r = new StringBuilder(256); 8391 } else { 8392 r.append(' '); 8393 } 8394 r.append(a.info.name); 8395 } 8396 } 8397 if (r != null) { 8398 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8399 } 8400 8401 N = pkg.permissions.size(); 8402 r = null; 8403 for (i=0; i<N; i++) { 8404 PackageParser.Permission p = pkg.permissions.get(i); 8405 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8406 if (bp == null) { 8407 bp = mSettings.mPermissionTrees.get(p.info.name); 8408 } 8409 if (bp != null && bp.perm == p) { 8410 bp.perm = null; 8411 if (DEBUG_REMOVE && chatty) { 8412 if (r == null) { 8413 r = new StringBuilder(256); 8414 } else { 8415 r.append(' '); 8416 } 8417 r.append(p.info.name); 8418 } 8419 } 8420 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8421 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8422 if (appOpPerms != null) { 8423 appOpPerms.remove(pkg.packageName); 8424 } 8425 } 8426 } 8427 if (r != null) { 8428 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8429 } 8430 8431 N = pkg.requestedPermissions.size(); 8432 r = null; 8433 for (i=0; i<N; i++) { 8434 String perm = pkg.requestedPermissions.get(i); 8435 BasePermission bp = mSettings.mPermissions.get(perm); 8436 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8437 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8438 if (appOpPerms != null) { 8439 appOpPerms.remove(pkg.packageName); 8440 if (appOpPerms.isEmpty()) { 8441 mAppOpPermissionPackages.remove(perm); 8442 } 8443 } 8444 } 8445 } 8446 if (r != null) { 8447 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8448 } 8449 8450 N = pkg.instrumentation.size(); 8451 r = null; 8452 for (i=0; i<N; i++) { 8453 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8454 mInstrumentation.remove(a.getComponentName()); 8455 if (DEBUG_REMOVE && chatty) { 8456 if (r == null) { 8457 r = new StringBuilder(256); 8458 } else { 8459 r.append(' '); 8460 } 8461 r.append(a.info.name); 8462 } 8463 } 8464 if (r != null) { 8465 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8466 } 8467 8468 r = null; 8469 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8470 // Only system apps can hold shared libraries. 8471 if (pkg.libraryNames != null) { 8472 for (i=0; i<pkg.libraryNames.size(); i++) { 8473 String name = pkg.libraryNames.get(i); 8474 SharedLibraryEntry cur = mSharedLibraries.get(name); 8475 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8476 mSharedLibraries.remove(name); 8477 if (DEBUG_REMOVE && chatty) { 8478 if (r == null) { 8479 r = new StringBuilder(256); 8480 } else { 8481 r.append(' '); 8482 } 8483 r.append(name); 8484 } 8485 } 8486 } 8487 } 8488 } 8489 if (r != null) { 8490 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8491 } 8492 } 8493 8494 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8495 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8496 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8497 return true; 8498 } 8499 } 8500 return false; 8501 } 8502 8503 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8504 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8505 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8506 8507 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8508 int flags) { 8509 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8510 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8511 } 8512 8513 private void updatePermissionsLPw(String changingPkg, 8514 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8515 // Make sure there are no dangling permission trees. 8516 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8517 while (it.hasNext()) { 8518 final BasePermission bp = it.next(); 8519 if (bp.packageSetting == null) { 8520 // We may not yet have parsed the package, so just see if 8521 // we still know about its settings. 8522 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8523 } 8524 if (bp.packageSetting == null) { 8525 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8526 + " from package " + bp.sourcePackage); 8527 it.remove(); 8528 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8529 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8530 Slog.i(TAG, "Removing old permission tree: " + bp.name 8531 + " from package " + bp.sourcePackage); 8532 flags |= UPDATE_PERMISSIONS_ALL; 8533 it.remove(); 8534 } 8535 } 8536 } 8537 8538 // Make sure all dynamic permissions have been assigned to a package, 8539 // and make sure there are no dangling permissions. 8540 it = mSettings.mPermissions.values().iterator(); 8541 while (it.hasNext()) { 8542 final BasePermission bp = it.next(); 8543 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8544 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8545 + bp.name + " pkg=" + bp.sourcePackage 8546 + " info=" + bp.pendingInfo); 8547 if (bp.packageSetting == null && bp.pendingInfo != null) { 8548 final BasePermission tree = findPermissionTreeLP(bp.name); 8549 if (tree != null && tree.perm != null) { 8550 bp.packageSetting = tree.packageSetting; 8551 bp.perm = new PackageParser.Permission(tree.perm.owner, 8552 new PermissionInfo(bp.pendingInfo)); 8553 bp.perm.info.packageName = tree.perm.info.packageName; 8554 bp.perm.info.name = bp.name; 8555 bp.uid = tree.uid; 8556 } 8557 } 8558 } 8559 if (bp.packageSetting == null) { 8560 // We may not yet have parsed the package, so just see if 8561 // we still know about its settings. 8562 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8563 } 8564 if (bp.packageSetting == null) { 8565 Slog.w(TAG, "Removing dangling permission: " + bp.name 8566 + " from package " + bp.sourcePackage); 8567 it.remove(); 8568 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8569 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8570 Slog.i(TAG, "Removing old permission: " + bp.name 8571 + " from package " + bp.sourcePackage); 8572 flags |= UPDATE_PERMISSIONS_ALL; 8573 it.remove(); 8574 } 8575 } 8576 } 8577 8578 // Now update the permissions for all packages, in particular 8579 // replace the granted permissions of the system packages. 8580 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8581 for (PackageParser.Package pkg : mPackages.values()) { 8582 if (pkg != pkgInfo) { 8583 // Only replace for packages on requested volume 8584 final String volumeUuid = getVolumeUuidForPackage(pkg); 8585 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8586 && Objects.equals(replaceVolumeUuid, volumeUuid); 8587 grantPermissionsLPw(pkg, replace, changingPkg); 8588 } 8589 } 8590 } 8591 8592 if (pkgInfo != null) { 8593 // Only replace for packages on requested volume 8594 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8595 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8596 && Objects.equals(replaceVolumeUuid, volumeUuid); 8597 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8598 } 8599 } 8600 8601 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8602 String packageOfInterest) { 8603 // IMPORTANT: There are two types of permissions: install and runtime. 8604 // Install time permissions are granted when the app is installed to 8605 // all device users and users added in the future. Runtime permissions 8606 // are granted at runtime explicitly to specific users. Normal and signature 8607 // protected permissions are install time permissions. Dangerous permissions 8608 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8609 // otherwise they are runtime permissions. This function does not manage 8610 // runtime permissions except for the case an app targeting Lollipop MR1 8611 // being upgraded to target a newer SDK, in which case dangerous permissions 8612 // are transformed from install time to runtime ones. 8613 8614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8615 if (ps == null) { 8616 return; 8617 } 8618 8619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8620 8621 PermissionsState permissionsState = ps.getPermissionsState(); 8622 PermissionsState origPermissions = permissionsState; 8623 8624 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8625 8626 boolean runtimePermissionsRevoked = false; 8627 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8628 8629 boolean changedInstallPermission = false; 8630 8631 if (replace) { 8632 ps.installPermissionsFixed = false; 8633 if (!ps.isSharedUser()) { 8634 origPermissions = new PermissionsState(permissionsState); 8635 permissionsState.reset(); 8636 } else { 8637 // We need to know only about runtime permission changes since the 8638 // calling code always writes the install permissions state but 8639 // the runtime ones are written only if changed. The only cases of 8640 // changed runtime permissions here are promotion of an install to 8641 // runtime and revocation of a runtime from a shared user. 8642 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8643 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8644 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8645 runtimePermissionsRevoked = true; 8646 } 8647 } 8648 } 8649 8650 permissionsState.setGlobalGids(mGlobalGids); 8651 8652 final int N = pkg.requestedPermissions.size(); 8653 for (int i=0; i<N; i++) { 8654 final String name = pkg.requestedPermissions.get(i); 8655 final BasePermission bp = mSettings.mPermissions.get(name); 8656 8657 if (DEBUG_INSTALL) { 8658 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8659 } 8660 8661 if (bp == null || bp.packageSetting == null) { 8662 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8663 Slog.w(TAG, "Unknown permission " + name 8664 + " in package " + pkg.packageName); 8665 } 8666 continue; 8667 } 8668 8669 final String perm = bp.name; 8670 boolean allowedSig = false; 8671 int grant = GRANT_DENIED; 8672 8673 // Keep track of app op permissions. 8674 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8675 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8676 if (pkgs == null) { 8677 pkgs = new ArraySet<>(); 8678 mAppOpPermissionPackages.put(bp.name, pkgs); 8679 } 8680 pkgs.add(pkg.packageName); 8681 } 8682 8683 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8684 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8685 >= Build.VERSION_CODES.M; 8686 switch (level) { 8687 case PermissionInfo.PROTECTION_NORMAL: { 8688 // For all apps normal permissions are install time ones. 8689 grant = GRANT_INSTALL; 8690 } break; 8691 8692 case PermissionInfo.PROTECTION_DANGEROUS: { 8693 // If a permission review is required for legacy apps we represent 8694 // their permissions as always granted runtime ones since we need 8695 // to keep the review required permission flag per user while an 8696 // install permission's state is shared across all users. 8697 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8698 // For legacy apps dangerous permissions are install time ones. 8699 grant = GRANT_INSTALL; 8700 } else if (origPermissions.hasInstallPermission(bp.name)) { 8701 // For legacy apps that became modern, install becomes runtime. 8702 grant = GRANT_UPGRADE; 8703 } else if (mPromoteSystemApps 8704 && isSystemApp(ps) 8705 && mExistingSystemPackages.contains(ps.name)) { 8706 // For legacy system apps, install becomes runtime. 8707 // We cannot check hasInstallPermission() for system apps since those 8708 // permissions were granted implicitly and not persisted pre-M. 8709 grant = GRANT_UPGRADE; 8710 } else { 8711 // For modern apps keep runtime permissions unchanged. 8712 grant = GRANT_RUNTIME; 8713 } 8714 } break; 8715 8716 case PermissionInfo.PROTECTION_SIGNATURE: { 8717 // For all apps signature permissions are install time ones. 8718 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8719 if (allowedSig) { 8720 grant = GRANT_INSTALL; 8721 } 8722 } break; 8723 } 8724 8725 if (DEBUG_INSTALL) { 8726 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8727 } 8728 8729 if (grant != GRANT_DENIED) { 8730 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8731 // If this is an existing, non-system package, then 8732 // we can't add any new permissions to it. 8733 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8734 // Except... if this is a permission that was added 8735 // to the platform (note: need to only do this when 8736 // updating the platform). 8737 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8738 grant = GRANT_DENIED; 8739 } 8740 } 8741 } 8742 8743 switch (grant) { 8744 case GRANT_INSTALL: { 8745 // Revoke this as runtime permission to handle the case of 8746 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8747 for (int userId : UserManagerService.getInstance().getUserIds()) { 8748 if (origPermissions.getRuntimePermissionState( 8749 bp.name, userId) != null) { 8750 // Revoke the runtime permission and clear the flags. 8751 origPermissions.revokeRuntimePermission(bp, userId); 8752 origPermissions.updatePermissionFlags(bp, userId, 8753 PackageManager.MASK_PERMISSION_FLAGS, 0); 8754 // If we revoked a permission permission, we have to write. 8755 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8756 changedRuntimePermissionUserIds, userId); 8757 } 8758 } 8759 // Grant an install permission. 8760 if (permissionsState.grantInstallPermission(bp) != 8761 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8762 changedInstallPermission = true; 8763 } 8764 } break; 8765 8766 case GRANT_RUNTIME: { 8767 // Grant previously granted runtime permissions. 8768 for (int userId : UserManagerService.getInstance().getUserIds()) { 8769 PermissionState permissionState = origPermissions 8770 .getRuntimePermissionState(bp.name, userId); 8771 int flags = permissionState != null 8772 ? permissionState.getFlags() : 0; 8773 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8774 if (permissionsState.grantRuntimePermission(bp, userId) == 8775 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8776 // If we cannot put the permission as it was, we have to write. 8777 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8778 changedRuntimePermissionUserIds, userId); 8779 } 8780 // If the app supports runtime permissions no need for a review. 8781 if (Build.PERMISSIONS_REVIEW_REQUIRED 8782 && appSupportsRuntimePermissions 8783 && (flags & PackageManager 8784 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8785 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8786 // Since we changed the flags, we have to write. 8787 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8788 changedRuntimePermissionUserIds, userId); 8789 } 8790 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8791 && !appSupportsRuntimePermissions) { 8792 // For legacy apps that need a permission review, every new 8793 // runtime permission is granted but it is pending a review. 8794 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8795 permissionsState.grantRuntimePermission(bp, userId); 8796 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8797 // We changed the permission and flags, hence have to write. 8798 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8799 changedRuntimePermissionUserIds, userId); 8800 } 8801 } 8802 // Propagate the permission flags. 8803 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8804 } 8805 } break; 8806 8807 case GRANT_UPGRADE: { 8808 // Grant runtime permissions for a previously held install permission. 8809 PermissionState permissionState = origPermissions 8810 .getInstallPermissionState(bp.name); 8811 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8812 8813 if (origPermissions.revokeInstallPermission(bp) 8814 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8815 // We will be transferring the permission flags, so clear them. 8816 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8817 PackageManager.MASK_PERMISSION_FLAGS, 0); 8818 changedInstallPermission = true; 8819 } 8820 8821 // If the permission is not to be promoted to runtime we ignore it and 8822 // also its other flags as they are not applicable to install permissions. 8823 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8824 for (int userId : currentUserIds) { 8825 if (permissionsState.grantRuntimePermission(bp, userId) != 8826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8827 // Transfer the permission flags. 8828 permissionsState.updatePermissionFlags(bp, userId, 8829 flags, flags); 8830 // If we granted the permission, we have to write. 8831 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8832 changedRuntimePermissionUserIds, userId); 8833 } 8834 } 8835 } 8836 } break; 8837 8838 default: { 8839 if (packageOfInterest == null 8840 || packageOfInterest.equals(pkg.packageName)) { 8841 Slog.w(TAG, "Not granting permission " + perm 8842 + " to package " + pkg.packageName 8843 + " because it was previously installed without"); 8844 } 8845 } break; 8846 } 8847 } else { 8848 if (permissionsState.revokeInstallPermission(bp) != 8849 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8850 // Also drop the permission flags. 8851 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8852 PackageManager.MASK_PERMISSION_FLAGS, 0); 8853 changedInstallPermission = true; 8854 Slog.i(TAG, "Un-granting permission " + perm 8855 + " from package " + pkg.packageName 8856 + " (protectionLevel=" + bp.protectionLevel 8857 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8858 + ")"); 8859 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8860 // Don't print warning for app op permissions, since it is fine for them 8861 // not to be granted, there is a UI for the user to decide. 8862 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8863 Slog.w(TAG, "Not granting permission " + perm 8864 + " to package " + pkg.packageName 8865 + " (protectionLevel=" + bp.protectionLevel 8866 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8867 + ")"); 8868 } 8869 } 8870 } 8871 } 8872 8873 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8874 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8875 // This is the first that we have heard about this package, so the 8876 // permissions we have now selected are fixed until explicitly 8877 // changed. 8878 ps.installPermissionsFixed = true; 8879 } 8880 8881 // Persist the runtime permissions state for users with changes. If permissions 8882 // were revoked because no app in the shared user declares them we have to 8883 // write synchronously to avoid losing runtime permissions state. 8884 for (int userId : changedRuntimePermissionUserIds) { 8885 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8886 } 8887 8888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8889 } 8890 8891 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8892 boolean allowed = false; 8893 final int NP = PackageParser.NEW_PERMISSIONS.length; 8894 for (int ip=0; ip<NP; ip++) { 8895 final PackageParser.NewPermissionInfo npi 8896 = PackageParser.NEW_PERMISSIONS[ip]; 8897 if (npi.name.equals(perm) 8898 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8899 allowed = true; 8900 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8901 + pkg.packageName); 8902 break; 8903 } 8904 } 8905 return allowed; 8906 } 8907 8908 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8909 BasePermission bp, PermissionsState origPermissions) { 8910 boolean allowed; 8911 allowed = (compareSignatures( 8912 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8913 == PackageManager.SIGNATURE_MATCH) 8914 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8915 == PackageManager.SIGNATURE_MATCH); 8916 if (!allowed && (bp.protectionLevel 8917 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8918 if (isSystemApp(pkg)) { 8919 // For updated system applications, a system permission 8920 // is granted only if it had been defined by the original application. 8921 if (pkg.isUpdatedSystemApp()) { 8922 final PackageSetting sysPs = mSettings 8923 .getDisabledSystemPkgLPr(pkg.packageName); 8924 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8925 // If the original was granted this permission, we take 8926 // that grant decision as read and propagate it to the 8927 // update. 8928 if (sysPs.isPrivileged()) { 8929 allowed = true; 8930 } 8931 } else { 8932 // The system apk may have been updated with an older 8933 // version of the one on the data partition, but which 8934 // granted a new system permission that it didn't have 8935 // before. In this case we do want to allow the app to 8936 // now get the new permission if the ancestral apk is 8937 // privileged to get it. 8938 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8939 for (int j=0; 8940 j<sysPs.pkg.requestedPermissions.size(); j++) { 8941 if (perm.equals( 8942 sysPs.pkg.requestedPermissions.get(j))) { 8943 allowed = true; 8944 break; 8945 } 8946 } 8947 } 8948 } 8949 } else { 8950 allowed = isPrivilegedApp(pkg); 8951 } 8952 } 8953 } 8954 if (!allowed) { 8955 if (!allowed && (bp.protectionLevel 8956 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8957 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8958 // If this was a previously normal/dangerous permission that got moved 8959 // to a system permission as part of the runtime permission redesign, then 8960 // we still want to blindly grant it to old apps. 8961 allowed = true; 8962 } 8963 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8964 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8965 // If this permission is to be granted to the system installer and 8966 // this app is an installer, then it gets the permission. 8967 allowed = true; 8968 } 8969 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8970 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8971 // If this permission is to be granted to the system verifier and 8972 // this app is a verifier, then it gets the permission. 8973 allowed = true; 8974 } 8975 if (!allowed && (bp.protectionLevel 8976 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8977 && isSystemApp(pkg)) { 8978 // Any pre-installed system app is allowed to get this permission. 8979 allowed = true; 8980 } 8981 if (!allowed && (bp.protectionLevel 8982 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8983 // For development permissions, a development permission 8984 // is granted only if it was already granted. 8985 allowed = origPermissions.hasInstallPermission(perm); 8986 } 8987 } 8988 return allowed; 8989 } 8990 8991 final class ActivityIntentResolver 8992 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8993 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8994 boolean defaultOnly, int userId) { 8995 if (!sUserManager.exists(userId)) return null; 8996 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8997 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8998 } 8999 9000 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9001 int userId) { 9002 if (!sUserManager.exists(userId)) return null; 9003 mFlags = flags; 9004 return super.queryIntent(intent, resolvedType, 9005 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9006 } 9007 9008 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9009 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9010 if (!sUserManager.exists(userId)) return null; 9011 if (packageActivities == null) { 9012 return null; 9013 } 9014 mFlags = flags; 9015 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9016 final int N = packageActivities.size(); 9017 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9018 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9019 9020 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9021 for (int i = 0; i < N; ++i) { 9022 intentFilters = packageActivities.get(i).intents; 9023 if (intentFilters != null && intentFilters.size() > 0) { 9024 PackageParser.ActivityIntentInfo[] array = 9025 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9026 intentFilters.toArray(array); 9027 listCut.add(array); 9028 } 9029 } 9030 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9031 } 9032 9033 public final void addActivity(PackageParser.Activity a, String type) { 9034 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9035 mActivities.put(a.getComponentName(), a); 9036 if (DEBUG_SHOW_INFO) 9037 Log.v( 9038 TAG, " " + type + " " + 9039 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9040 if (DEBUG_SHOW_INFO) 9041 Log.v(TAG, " Class=" + a.info.name); 9042 final int NI = a.intents.size(); 9043 for (int j=0; j<NI; j++) { 9044 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9045 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9046 intent.setPriority(0); 9047 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9048 + a.className + " with priority > 0, forcing to 0"); 9049 } 9050 if (DEBUG_SHOW_INFO) { 9051 Log.v(TAG, " IntentFilter:"); 9052 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9053 } 9054 if (!intent.debugCheck()) { 9055 Log.w(TAG, "==> For Activity " + a.info.name); 9056 } 9057 addFilter(intent); 9058 } 9059 } 9060 9061 public final void removeActivity(PackageParser.Activity a, String type) { 9062 mActivities.remove(a.getComponentName()); 9063 if (DEBUG_SHOW_INFO) { 9064 Log.v(TAG, " " + type + " " 9065 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9066 : a.info.name) + ":"); 9067 Log.v(TAG, " Class=" + a.info.name); 9068 } 9069 final int NI = a.intents.size(); 9070 for (int j=0; j<NI; j++) { 9071 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9072 if (DEBUG_SHOW_INFO) { 9073 Log.v(TAG, " IntentFilter:"); 9074 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9075 } 9076 removeFilter(intent); 9077 } 9078 } 9079 9080 @Override 9081 protected boolean allowFilterResult( 9082 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9083 ActivityInfo filterAi = filter.activity.info; 9084 for (int i=dest.size()-1; i>=0; i--) { 9085 ActivityInfo destAi = dest.get(i).activityInfo; 9086 if (destAi.name == filterAi.name 9087 && destAi.packageName == filterAi.packageName) { 9088 return false; 9089 } 9090 } 9091 return true; 9092 } 9093 9094 @Override 9095 protected ActivityIntentInfo[] newArray(int size) { 9096 return new ActivityIntentInfo[size]; 9097 } 9098 9099 @Override 9100 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9101 if (!sUserManager.exists(userId)) return true; 9102 PackageParser.Package p = filter.activity.owner; 9103 if (p != null) { 9104 PackageSetting ps = (PackageSetting)p.mExtras; 9105 if (ps != null) { 9106 // System apps are never considered stopped for purposes of 9107 // filtering, because there may be no way for the user to 9108 // actually re-launch them. 9109 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9110 && ps.getStopped(userId); 9111 } 9112 } 9113 return false; 9114 } 9115 9116 @Override 9117 protected boolean isPackageForFilter(String packageName, 9118 PackageParser.ActivityIntentInfo info) { 9119 return packageName.equals(info.activity.owner.packageName); 9120 } 9121 9122 @Override 9123 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9124 int match, int userId) { 9125 if (!sUserManager.exists(userId)) return null; 9126 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9127 return null; 9128 } 9129 final PackageParser.Activity activity = info.activity; 9130 if (mSafeMode && (activity.info.applicationInfo.flags 9131 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9132 return null; 9133 } 9134 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9135 if (ps == null) { 9136 return null; 9137 } 9138 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9139 ps.readUserState(userId), userId); 9140 if (ai == null) { 9141 return null; 9142 } 9143 final ResolveInfo res = new ResolveInfo(); 9144 res.activityInfo = ai; 9145 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9146 res.filter = info; 9147 } 9148 if (info != null) { 9149 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9150 } 9151 res.priority = info.getPriority(); 9152 res.preferredOrder = activity.owner.mPreferredOrder; 9153 //System.out.println("Result: " + res.activityInfo.className + 9154 // " = " + res.priority); 9155 res.match = match; 9156 res.isDefault = info.hasDefault; 9157 res.labelRes = info.labelRes; 9158 res.nonLocalizedLabel = info.nonLocalizedLabel; 9159 if (userNeedsBadging(userId)) { 9160 res.noResourceId = true; 9161 } else { 9162 res.icon = info.icon; 9163 } 9164 res.iconResourceId = info.icon; 9165 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9166 return res; 9167 } 9168 9169 @Override 9170 protected void sortResults(List<ResolveInfo> results) { 9171 Collections.sort(results, mResolvePrioritySorter); 9172 } 9173 9174 @Override 9175 protected void dumpFilter(PrintWriter out, String prefix, 9176 PackageParser.ActivityIntentInfo filter) { 9177 out.print(prefix); out.print( 9178 Integer.toHexString(System.identityHashCode(filter.activity))); 9179 out.print(' '); 9180 filter.activity.printComponentShortName(out); 9181 out.print(" filter "); 9182 out.println(Integer.toHexString(System.identityHashCode(filter))); 9183 } 9184 9185 @Override 9186 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9187 return filter.activity; 9188 } 9189 9190 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9191 PackageParser.Activity activity = (PackageParser.Activity)label; 9192 out.print(prefix); out.print( 9193 Integer.toHexString(System.identityHashCode(activity))); 9194 out.print(' '); 9195 activity.printComponentShortName(out); 9196 if (count > 1) { 9197 out.print(" ("); out.print(count); out.print(" filters)"); 9198 } 9199 out.println(); 9200 } 9201 9202// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9203// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9204// final List<ResolveInfo> retList = Lists.newArrayList(); 9205// while (i.hasNext()) { 9206// final ResolveInfo resolveInfo = i.next(); 9207// if (isEnabledLP(resolveInfo.activityInfo)) { 9208// retList.add(resolveInfo); 9209// } 9210// } 9211// return retList; 9212// } 9213 9214 // Keys are String (activity class name), values are Activity. 9215 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9216 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9217 private int mFlags; 9218 } 9219 9220 private final class ServiceIntentResolver 9221 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9222 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9223 boolean defaultOnly, int userId) { 9224 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9225 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9226 } 9227 9228 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9229 int userId) { 9230 if (!sUserManager.exists(userId)) return null; 9231 mFlags = flags; 9232 return super.queryIntent(intent, resolvedType, 9233 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9234 } 9235 9236 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9237 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9238 if (!sUserManager.exists(userId)) return null; 9239 if (packageServices == null) { 9240 return null; 9241 } 9242 mFlags = flags; 9243 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9244 final int N = packageServices.size(); 9245 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9246 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9247 9248 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9249 for (int i = 0; i < N; ++i) { 9250 intentFilters = packageServices.get(i).intents; 9251 if (intentFilters != null && intentFilters.size() > 0) { 9252 PackageParser.ServiceIntentInfo[] array = 9253 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9254 intentFilters.toArray(array); 9255 listCut.add(array); 9256 } 9257 } 9258 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9259 } 9260 9261 public final void addService(PackageParser.Service s) { 9262 mServices.put(s.getComponentName(), s); 9263 if (DEBUG_SHOW_INFO) { 9264 Log.v(TAG, " " 9265 + (s.info.nonLocalizedLabel != null 9266 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9267 Log.v(TAG, " Class=" + s.info.name); 9268 } 9269 final int NI = s.intents.size(); 9270 int j; 9271 for (j=0; j<NI; j++) { 9272 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9273 if (DEBUG_SHOW_INFO) { 9274 Log.v(TAG, " IntentFilter:"); 9275 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9276 } 9277 if (!intent.debugCheck()) { 9278 Log.w(TAG, "==> For Service " + s.info.name); 9279 } 9280 addFilter(intent); 9281 } 9282 } 9283 9284 public final void removeService(PackageParser.Service s) { 9285 mServices.remove(s.getComponentName()); 9286 if (DEBUG_SHOW_INFO) { 9287 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9288 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9289 Log.v(TAG, " Class=" + s.info.name); 9290 } 9291 final int NI = s.intents.size(); 9292 int j; 9293 for (j=0; j<NI; j++) { 9294 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9295 if (DEBUG_SHOW_INFO) { 9296 Log.v(TAG, " IntentFilter:"); 9297 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9298 } 9299 removeFilter(intent); 9300 } 9301 } 9302 9303 @Override 9304 protected boolean allowFilterResult( 9305 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9306 ServiceInfo filterSi = filter.service.info; 9307 for (int i=dest.size()-1; i>=0; i--) { 9308 ServiceInfo destAi = dest.get(i).serviceInfo; 9309 if (destAi.name == filterSi.name 9310 && destAi.packageName == filterSi.packageName) { 9311 return false; 9312 } 9313 } 9314 return true; 9315 } 9316 9317 @Override 9318 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9319 return new PackageParser.ServiceIntentInfo[size]; 9320 } 9321 9322 @Override 9323 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9324 if (!sUserManager.exists(userId)) return true; 9325 PackageParser.Package p = filter.service.owner; 9326 if (p != null) { 9327 PackageSetting ps = (PackageSetting)p.mExtras; 9328 if (ps != null) { 9329 // System apps are never considered stopped for purposes of 9330 // filtering, because there may be no way for the user to 9331 // actually re-launch them. 9332 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9333 && ps.getStopped(userId); 9334 } 9335 } 9336 return false; 9337 } 9338 9339 @Override 9340 protected boolean isPackageForFilter(String packageName, 9341 PackageParser.ServiceIntentInfo info) { 9342 return packageName.equals(info.service.owner.packageName); 9343 } 9344 9345 @Override 9346 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9347 int match, int userId) { 9348 if (!sUserManager.exists(userId)) return null; 9349 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9350 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9351 return null; 9352 } 9353 final PackageParser.Service service = info.service; 9354 if (mSafeMode && (service.info.applicationInfo.flags 9355 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9356 return null; 9357 } 9358 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9359 if (ps == null) { 9360 return null; 9361 } 9362 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9363 ps.readUserState(userId), userId); 9364 if (si == null) { 9365 return null; 9366 } 9367 final ResolveInfo res = new ResolveInfo(); 9368 res.serviceInfo = si; 9369 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9370 res.filter = filter; 9371 } 9372 res.priority = info.getPriority(); 9373 res.preferredOrder = service.owner.mPreferredOrder; 9374 res.match = match; 9375 res.isDefault = info.hasDefault; 9376 res.labelRes = info.labelRes; 9377 res.nonLocalizedLabel = info.nonLocalizedLabel; 9378 res.icon = info.icon; 9379 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9380 return res; 9381 } 9382 9383 @Override 9384 protected void sortResults(List<ResolveInfo> results) { 9385 Collections.sort(results, mResolvePrioritySorter); 9386 } 9387 9388 @Override 9389 protected void dumpFilter(PrintWriter out, String prefix, 9390 PackageParser.ServiceIntentInfo filter) { 9391 out.print(prefix); out.print( 9392 Integer.toHexString(System.identityHashCode(filter.service))); 9393 out.print(' '); 9394 filter.service.printComponentShortName(out); 9395 out.print(" filter "); 9396 out.println(Integer.toHexString(System.identityHashCode(filter))); 9397 } 9398 9399 @Override 9400 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9401 return filter.service; 9402 } 9403 9404 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9405 PackageParser.Service service = (PackageParser.Service)label; 9406 out.print(prefix); out.print( 9407 Integer.toHexString(System.identityHashCode(service))); 9408 out.print(' '); 9409 service.printComponentShortName(out); 9410 if (count > 1) { 9411 out.print(" ("); out.print(count); out.print(" filters)"); 9412 } 9413 out.println(); 9414 } 9415 9416// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9417// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9418// final List<ResolveInfo> retList = Lists.newArrayList(); 9419// while (i.hasNext()) { 9420// final ResolveInfo resolveInfo = (ResolveInfo) i; 9421// if (isEnabledLP(resolveInfo.serviceInfo)) { 9422// retList.add(resolveInfo); 9423// } 9424// } 9425// return retList; 9426// } 9427 9428 // Keys are String (activity class name), values are Activity. 9429 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9430 = new ArrayMap<ComponentName, PackageParser.Service>(); 9431 private int mFlags; 9432 }; 9433 9434 private final class ProviderIntentResolver 9435 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9436 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9437 boolean defaultOnly, int userId) { 9438 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9439 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9440 } 9441 9442 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9443 int userId) { 9444 if (!sUserManager.exists(userId)) 9445 return null; 9446 mFlags = flags; 9447 return super.queryIntent(intent, resolvedType, 9448 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9449 } 9450 9451 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9452 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9453 if (!sUserManager.exists(userId)) 9454 return null; 9455 if (packageProviders == null) { 9456 return null; 9457 } 9458 mFlags = flags; 9459 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9460 final int N = packageProviders.size(); 9461 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9462 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9463 9464 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9465 for (int i = 0; i < N; ++i) { 9466 intentFilters = packageProviders.get(i).intents; 9467 if (intentFilters != null && intentFilters.size() > 0) { 9468 PackageParser.ProviderIntentInfo[] array = 9469 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9470 intentFilters.toArray(array); 9471 listCut.add(array); 9472 } 9473 } 9474 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9475 } 9476 9477 public final void addProvider(PackageParser.Provider p) { 9478 if (mProviders.containsKey(p.getComponentName())) { 9479 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9480 return; 9481 } 9482 9483 mProviders.put(p.getComponentName(), p); 9484 if (DEBUG_SHOW_INFO) { 9485 Log.v(TAG, " " 9486 + (p.info.nonLocalizedLabel != null 9487 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9488 Log.v(TAG, " Class=" + p.info.name); 9489 } 9490 final int NI = p.intents.size(); 9491 int j; 9492 for (j = 0; j < NI; j++) { 9493 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9494 if (DEBUG_SHOW_INFO) { 9495 Log.v(TAG, " IntentFilter:"); 9496 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9497 } 9498 if (!intent.debugCheck()) { 9499 Log.w(TAG, "==> For Provider " + p.info.name); 9500 } 9501 addFilter(intent); 9502 } 9503 } 9504 9505 public final void removeProvider(PackageParser.Provider p) { 9506 mProviders.remove(p.getComponentName()); 9507 if (DEBUG_SHOW_INFO) { 9508 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9509 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9510 Log.v(TAG, " Class=" + p.info.name); 9511 } 9512 final int NI = p.intents.size(); 9513 int j; 9514 for (j = 0; j < NI; j++) { 9515 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9516 if (DEBUG_SHOW_INFO) { 9517 Log.v(TAG, " IntentFilter:"); 9518 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9519 } 9520 removeFilter(intent); 9521 } 9522 } 9523 9524 @Override 9525 protected boolean allowFilterResult( 9526 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9527 ProviderInfo filterPi = filter.provider.info; 9528 for (int i = dest.size() - 1; i >= 0; i--) { 9529 ProviderInfo destPi = dest.get(i).providerInfo; 9530 if (destPi.name == filterPi.name 9531 && destPi.packageName == filterPi.packageName) { 9532 return false; 9533 } 9534 } 9535 return true; 9536 } 9537 9538 @Override 9539 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9540 return new PackageParser.ProviderIntentInfo[size]; 9541 } 9542 9543 @Override 9544 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9545 if (!sUserManager.exists(userId)) 9546 return true; 9547 PackageParser.Package p = filter.provider.owner; 9548 if (p != null) { 9549 PackageSetting ps = (PackageSetting) p.mExtras; 9550 if (ps != null) { 9551 // System apps are never considered stopped for purposes of 9552 // filtering, because there may be no way for the user to 9553 // actually re-launch them. 9554 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9555 && ps.getStopped(userId); 9556 } 9557 } 9558 return false; 9559 } 9560 9561 @Override 9562 protected boolean isPackageForFilter(String packageName, 9563 PackageParser.ProviderIntentInfo info) { 9564 return packageName.equals(info.provider.owner.packageName); 9565 } 9566 9567 @Override 9568 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9569 int match, int userId) { 9570 if (!sUserManager.exists(userId)) 9571 return null; 9572 final PackageParser.ProviderIntentInfo info = filter; 9573 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9574 return null; 9575 } 9576 final PackageParser.Provider provider = info.provider; 9577 if (mSafeMode && (provider.info.applicationInfo.flags 9578 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9579 return null; 9580 } 9581 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9582 if (ps == null) { 9583 return null; 9584 } 9585 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9586 ps.readUserState(userId), userId); 9587 if (pi == null) { 9588 return null; 9589 } 9590 final ResolveInfo res = new ResolveInfo(); 9591 res.providerInfo = pi; 9592 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9593 res.filter = filter; 9594 } 9595 res.priority = info.getPriority(); 9596 res.preferredOrder = provider.owner.mPreferredOrder; 9597 res.match = match; 9598 res.isDefault = info.hasDefault; 9599 res.labelRes = info.labelRes; 9600 res.nonLocalizedLabel = info.nonLocalizedLabel; 9601 res.icon = info.icon; 9602 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9603 return res; 9604 } 9605 9606 @Override 9607 protected void sortResults(List<ResolveInfo> results) { 9608 Collections.sort(results, mResolvePrioritySorter); 9609 } 9610 9611 @Override 9612 protected void dumpFilter(PrintWriter out, String prefix, 9613 PackageParser.ProviderIntentInfo filter) { 9614 out.print(prefix); 9615 out.print( 9616 Integer.toHexString(System.identityHashCode(filter.provider))); 9617 out.print(' '); 9618 filter.provider.printComponentShortName(out); 9619 out.print(" filter "); 9620 out.println(Integer.toHexString(System.identityHashCode(filter))); 9621 } 9622 9623 @Override 9624 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9625 return filter.provider; 9626 } 9627 9628 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9629 PackageParser.Provider provider = (PackageParser.Provider)label; 9630 out.print(prefix); out.print( 9631 Integer.toHexString(System.identityHashCode(provider))); 9632 out.print(' '); 9633 provider.printComponentShortName(out); 9634 if (count > 1) { 9635 out.print(" ("); out.print(count); out.print(" filters)"); 9636 } 9637 out.println(); 9638 } 9639 9640 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9641 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9642 private int mFlags; 9643 } 9644 9645 private static final class EphemeralIntentResolver 9646 extends IntentResolver<IntentFilter, ResolveInfo> { 9647 @Override 9648 protected IntentFilter[] newArray(int size) { 9649 return new IntentFilter[size]; 9650 } 9651 9652 @Override 9653 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9654 return true; 9655 } 9656 9657 @Override 9658 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9659 if (!sUserManager.exists(userId)) return null; 9660 final ResolveInfo res = new ResolveInfo(); 9661 res.filter = info; 9662 return res; 9663 } 9664 } 9665 9666 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9667 new Comparator<ResolveInfo>() { 9668 public int compare(ResolveInfo r1, ResolveInfo r2) { 9669 int v1 = r1.priority; 9670 int v2 = r2.priority; 9671 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9672 if (v1 != v2) { 9673 return (v1 > v2) ? -1 : 1; 9674 } 9675 v1 = r1.preferredOrder; 9676 v2 = r2.preferredOrder; 9677 if (v1 != v2) { 9678 return (v1 > v2) ? -1 : 1; 9679 } 9680 if (r1.isDefault != r2.isDefault) { 9681 return r1.isDefault ? -1 : 1; 9682 } 9683 v1 = r1.match; 9684 v2 = r2.match; 9685 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9686 if (v1 != v2) { 9687 return (v1 > v2) ? -1 : 1; 9688 } 9689 if (r1.system != r2.system) { 9690 return r1.system ? -1 : 1; 9691 } 9692 return 0; 9693 } 9694 }; 9695 9696 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9697 new Comparator<ProviderInfo>() { 9698 public int compare(ProviderInfo p1, ProviderInfo p2) { 9699 final int v1 = p1.initOrder; 9700 final int v2 = p2.initOrder; 9701 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9702 } 9703 }; 9704 9705 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9706 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9707 final int[] userIds) { 9708 mHandler.post(new Runnable() { 9709 @Override 9710 public void run() { 9711 try { 9712 final IActivityManager am = ActivityManagerNative.getDefault(); 9713 if (am == null) return; 9714 final int[] resolvedUserIds; 9715 if (userIds == null) { 9716 resolvedUserIds = am.getRunningUserIds(); 9717 } else { 9718 resolvedUserIds = userIds; 9719 } 9720 for (int id : resolvedUserIds) { 9721 final Intent intent = new Intent(action, 9722 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9723 if (extras != null) { 9724 intent.putExtras(extras); 9725 } 9726 if (targetPkg != null) { 9727 intent.setPackage(targetPkg); 9728 } 9729 // Modify the UID when posting to other users 9730 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9731 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9732 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9733 intent.putExtra(Intent.EXTRA_UID, uid); 9734 } 9735 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9736 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9737 if (DEBUG_BROADCASTS) { 9738 RuntimeException here = new RuntimeException("here"); 9739 here.fillInStackTrace(); 9740 Slog.d(TAG, "Sending to user " + id + ": " 9741 + intent.toShortString(false, true, false, false) 9742 + " " + intent.getExtras(), here); 9743 } 9744 am.broadcastIntent(null, intent, null, finishedReceiver, 9745 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9746 null, finishedReceiver != null, false, id); 9747 } 9748 } catch (RemoteException ex) { 9749 } 9750 } 9751 }); 9752 } 9753 9754 /** 9755 * Check if the external storage media is available. This is true if there 9756 * is a mounted external storage medium or if the external storage is 9757 * emulated. 9758 */ 9759 private boolean isExternalMediaAvailable() { 9760 return mMediaMounted || Environment.isExternalStorageEmulated(); 9761 } 9762 9763 @Override 9764 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9765 // writer 9766 synchronized (mPackages) { 9767 if (!isExternalMediaAvailable()) { 9768 // If the external storage is no longer mounted at this point, 9769 // the caller may not have been able to delete all of this 9770 // packages files and can not delete any more. Bail. 9771 return null; 9772 } 9773 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9774 if (lastPackage != null) { 9775 pkgs.remove(lastPackage); 9776 } 9777 if (pkgs.size() > 0) { 9778 return pkgs.get(0); 9779 } 9780 } 9781 return null; 9782 } 9783 9784 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9785 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9786 userId, andCode ? 1 : 0, packageName); 9787 if (mSystemReady) { 9788 msg.sendToTarget(); 9789 } else { 9790 if (mPostSystemReadyMessages == null) { 9791 mPostSystemReadyMessages = new ArrayList<>(); 9792 } 9793 mPostSystemReadyMessages.add(msg); 9794 } 9795 } 9796 9797 void startCleaningPackages() { 9798 // reader 9799 synchronized (mPackages) { 9800 if (!isExternalMediaAvailable()) { 9801 return; 9802 } 9803 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9804 return; 9805 } 9806 } 9807 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9808 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9809 IActivityManager am = ActivityManagerNative.getDefault(); 9810 if (am != null) { 9811 try { 9812 am.startService(null, intent, null, mContext.getOpPackageName(), 9813 UserHandle.USER_SYSTEM); 9814 } catch (RemoteException e) { 9815 } 9816 } 9817 } 9818 9819 @Override 9820 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9821 int installFlags, String installerPackageName, VerificationParams verificationParams, 9822 String packageAbiOverride) { 9823 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9824 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9825 } 9826 9827 @Override 9828 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9829 int installFlags, String installerPackageName, VerificationParams verificationParams, 9830 String packageAbiOverride, int userId) { 9831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9832 9833 final int callingUid = Binder.getCallingUid(); 9834 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9835 9836 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9837 try { 9838 if (observer != null) { 9839 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9840 } 9841 } catch (RemoteException re) { 9842 } 9843 return; 9844 } 9845 9846 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9847 installFlags |= PackageManager.INSTALL_FROM_ADB; 9848 9849 } else { 9850 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9851 // about installerPackageName. 9852 9853 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9854 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9855 } 9856 9857 UserHandle user; 9858 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9859 user = UserHandle.ALL; 9860 } else { 9861 user = new UserHandle(userId); 9862 } 9863 9864 // Only system components can circumvent runtime permissions when installing. 9865 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9866 && mContext.checkCallingOrSelfPermission(Manifest.permission 9867 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9868 throw new SecurityException("You need the " 9869 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9870 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9871 } 9872 9873 verificationParams.setInstallerUid(callingUid); 9874 9875 final File originFile = new File(originPath); 9876 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9877 9878 final Message msg = mHandler.obtainMessage(INIT_COPY); 9879 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9880 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9881 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9882 msg.obj = params; 9883 9884 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9885 System.identityHashCode(msg.obj)); 9886 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9887 System.identityHashCode(msg.obj)); 9888 9889 mHandler.sendMessage(msg); 9890 } 9891 9892 void installStage(String packageName, File stagedDir, String stagedCid, 9893 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9894 String installerPackageName, int installerUid, UserHandle user) { 9895 if (DEBUG_EPHEMERAL) { 9896 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9897 Slog.d(TAG, "Ephemeral install of " + packageName); 9898 } 9899 } 9900 final VerificationParams verifParams = new VerificationParams( 9901 null, sessionParams.originatingUri, sessionParams.referrerUri, 9902 sessionParams.originatingUid, null); 9903 verifParams.setInstallerUid(installerUid); 9904 9905 final OriginInfo origin; 9906 if (stagedDir != null) { 9907 origin = OriginInfo.fromStagedFile(stagedDir); 9908 } else { 9909 origin = OriginInfo.fromStagedContainer(stagedCid); 9910 } 9911 9912 final Message msg = mHandler.obtainMessage(INIT_COPY); 9913 final InstallParams params = new InstallParams(origin, null, observer, 9914 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9915 verifParams, user, sessionParams.abiOverride, 9916 sessionParams.grantedRuntimePermissions); 9917 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9918 msg.obj = params; 9919 9920 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9921 System.identityHashCode(msg.obj)); 9922 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9923 System.identityHashCode(msg.obj)); 9924 9925 mHandler.sendMessage(msg); 9926 } 9927 9928 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9929 Bundle extras = new Bundle(1); 9930 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9931 9932 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9933 packageName, extras, 0, null, null, new int[] {userId}); 9934 try { 9935 IActivityManager am = ActivityManagerNative.getDefault(); 9936 final boolean isSystem = 9937 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9938 if (isSystem && am.isUserRunning(userId, 0)) { 9939 // The just-installed/enabled app is bundled on the system, so presumed 9940 // to be able to run automatically without needing an explicit launch. 9941 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9942 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9943 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9944 .setPackage(packageName); 9945 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9946 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9947 } 9948 } catch (RemoteException e) { 9949 // shouldn't happen 9950 Slog.w(TAG, "Unable to bootstrap installed package", e); 9951 } 9952 } 9953 9954 @Override 9955 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9956 int userId) { 9957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9958 PackageSetting pkgSetting; 9959 final int uid = Binder.getCallingUid(); 9960 enforceCrossUserPermission(uid, userId, true, true, 9961 "setApplicationHiddenSetting for user " + userId); 9962 9963 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9964 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9965 return false; 9966 } 9967 9968 long callingId = Binder.clearCallingIdentity(); 9969 try { 9970 boolean sendAdded = false; 9971 boolean sendRemoved = false; 9972 // writer 9973 synchronized (mPackages) { 9974 pkgSetting = mSettings.mPackages.get(packageName); 9975 if (pkgSetting == null) { 9976 return false; 9977 } 9978 if (pkgSetting.getHidden(userId) != hidden) { 9979 pkgSetting.setHidden(hidden, userId); 9980 mSettings.writePackageRestrictionsLPr(userId); 9981 if (hidden) { 9982 sendRemoved = true; 9983 } else { 9984 sendAdded = true; 9985 } 9986 } 9987 } 9988 if (sendAdded) { 9989 sendPackageAddedForUser(packageName, pkgSetting, userId); 9990 return true; 9991 } 9992 if (sendRemoved) { 9993 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9994 "hiding pkg"); 9995 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9996 return true; 9997 } 9998 } finally { 9999 Binder.restoreCallingIdentity(callingId); 10000 } 10001 return false; 10002 } 10003 10004 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10005 int userId) { 10006 final PackageRemovedInfo info = new PackageRemovedInfo(); 10007 info.removedPackage = packageName; 10008 info.removedUsers = new int[] {userId}; 10009 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10010 info.sendBroadcast(false, false, false); 10011 } 10012 10013 /** 10014 * Returns true if application is not found or there was an error. Otherwise it returns 10015 * the hidden state of the package for the given user. 10016 */ 10017 @Override 10018 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10019 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10020 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10021 false, "getApplicationHidden for user " + userId); 10022 PackageSetting pkgSetting; 10023 long callingId = Binder.clearCallingIdentity(); 10024 try { 10025 // writer 10026 synchronized (mPackages) { 10027 pkgSetting = mSettings.mPackages.get(packageName); 10028 if (pkgSetting == null) { 10029 return true; 10030 } 10031 return pkgSetting.getHidden(userId); 10032 } 10033 } finally { 10034 Binder.restoreCallingIdentity(callingId); 10035 } 10036 } 10037 10038 /** 10039 * @hide 10040 */ 10041 @Override 10042 public int installExistingPackageAsUser(String packageName, int userId) { 10043 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10044 null); 10045 PackageSetting pkgSetting; 10046 final int uid = Binder.getCallingUid(); 10047 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10048 + userId); 10049 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10050 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10051 } 10052 10053 long callingId = Binder.clearCallingIdentity(); 10054 try { 10055 boolean sendAdded = false; 10056 10057 // writer 10058 synchronized (mPackages) { 10059 pkgSetting = mSettings.mPackages.get(packageName); 10060 if (pkgSetting == null) { 10061 return PackageManager.INSTALL_FAILED_INVALID_URI; 10062 } 10063 if (!pkgSetting.getInstalled(userId)) { 10064 pkgSetting.setInstalled(true, userId); 10065 pkgSetting.setHidden(false, userId); 10066 mSettings.writePackageRestrictionsLPr(userId); 10067 sendAdded = true; 10068 } 10069 } 10070 10071 if (sendAdded) { 10072 sendPackageAddedForUser(packageName, pkgSetting, userId); 10073 } 10074 } finally { 10075 Binder.restoreCallingIdentity(callingId); 10076 } 10077 10078 return PackageManager.INSTALL_SUCCEEDED; 10079 } 10080 10081 boolean isUserRestricted(int userId, String restrictionKey) { 10082 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10083 if (restrictions.getBoolean(restrictionKey, false)) { 10084 Log.w(TAG, "User is restricted: " + restrictionKey); 10085 return true; 10086 } 10087 return false; 10088 } 10089 10090 @Override 10091 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10092 mContext.enforceCallingOrSelfPermission( 10093 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10094 "Only package verification agents can verify applications"); 10095 10096 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10097 final PackageVerificationResponse response = new PackageVerificationResponse( 10098 verificationCode, Binder.getCallingUid()); 10099 msg.arg1 = id; 10100 msg.obj = response; 10101 mHandler.sendMessage(msg); 10102 } 10103 10104 @Override 10105 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10106 long millisecondsToDelay) { 10107 mContext.enforceCallingOrSelfPermission( 10108 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10109 "Only package verification agents can extend verification timeouts"); 10110 10111 final PackageVerificationState state = mPendingVerification.get(id); 10112 final PackageVerificationResponse response = new PackageVerificationResponse( 10113 verificationCodeAtTimeout, Binder.getCallingUid()); 10114 10115 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10116 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10117 } 10118 if (millisecondsToDelay < 0) { 10119 millisecondsToDelay = 0; 10120 } 10121 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10122 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10123 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10124 } 10125 10126 if ((state != null) && !state.timeoutExtended()) { 10127 state.extendTimeout(); 10128 10129 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10130 msg.arg1 = id; 10131 msg.obj = response; 10132 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10133 } 10134 } 10135 10136 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10137 int verificationCode, UserHandle user) { 10138 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10139 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10140 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10141 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10142 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10143 10144 mContext.sendBroadcastAsUser(intent, user, 10145 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10146 } 10147 10148 private ComponentName matchComponentForVerifier(String packageName, 10149 List<ResolveInfo> receivers) { 10150 ActivityInfo targetReceiver = null; 10151 10152 final int NR = receivers.size(); 10153 for (int i = 0; i < NR; i++) { 10154 final ResolveInfo info = receivers.get(i); 10155 if (info.activityInfo == null) { 10156 continue; 10157 } 10158 10159 if (packageName.equals(info.activityInfo.packageName)) { 10160 targetReceiver = info.activityInfo; 10161 break; 10162 } 10163 } 10164 10165 if (targetReceiver == null) { 10166 return null; 10167 } 10168 10169 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10170 } 10171 10172 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10173 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10174 if (pkgInfo.verifiers.length == 0) { 10175 return null; 10176 } 10177 10178 final int N = pkgInfo.verifiers.length; 10179 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10180 for (int i = 0; i < N; i++) { 10181 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10182 10183 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10184 receivers); 10185 if (comp == null) { 10186 continue; 10187 } 10188 10189 final int verifierUid = getUidForVerifier(verifierInfo); 10190 if (verifierUid == -1) { 10191 continue; 10192 } 10193 10194 if (DEBUG_VERIFY) { 10195 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10196 + " with the correct signature"); 10197 } 10198 sufficientVerifiers.add(comp); 10199 verificationState.addSufficientVerifier(verifierUid); 10200 } 10201 10202 return sufficientVerifiers; 10203 } 10204 10205 private int getUidForVerifier(VerifierInfo verifierInfo) { 10206 synchronized (mPackages) { 10207 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10208 if (pkg == null) { 10209 return -1; 10210 } else if (pkg.mSignatures.length != 1) { 10211 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10212 + " has more than one signature; ignoring"); 10213 return -1; 10214 } 10215 10216 /* 10217 * If the public key of the package's signature does not match 10218 * our expected public key, then this is a different package and 10219 * we should skip. 10220 */ 10221 10222 final byte[] expectedPublicKey; 10223 try { 10224 final Signature verifierSig = pkg.mSignatures[0]; 10225 final PublicKey publicKey = verifierSig.getPublicKey(); 10226 expectedPublicKey = publicKey.getEncoded(); 10227 } catch (CertificateException e) { 10228 return -1; 10229 } 10230 10231 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10232 10233 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10234 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10235 + " does not have the expected public key; ignoring"); 10236 return -1; 10237 } 10238 10239 return pkg.applicationInfo.uid; 10240 } 10241 } 10242 10243 @Override 10244 public void finishPackageInstall(int token) { 10245 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10246 10247 if (DEBUG_INSTALL) { 10248 Slog.v(TAG, "BM finishing package install for " + token); 10249 } 10250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10251 10252 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10253 mHandler.sendMessage(msg); 10254 } 10255 10256 /** 10257 * Get the verification agent timeout. 10258 * 10259 * @return verification timeout in milliseconds 10260 */ 10261 private long getVerificationTimeout() { 10262 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10263 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10264 DEFAULT_VERIFICATION_TIMEOUT); 10265 } 10266 10267 /** 10268 * Get the default verification agent response code. 10269 * 10270 * @return default verification response code 10271 */ 10272 private int getDefaultVerificationResponse() { 10273 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10274 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10275 DEFAULT_VERIFICATION_RESPONSE); 10276 } 10277 10278 /** 10279 * Check whether or not package verification has been enabled. 10280 * 10281 * @return true if verification should be performed 10282 */ 10283 private boolean isVerificationEnabled(int userId, int installFlags) { 10284 if (!DEFAULT_VERIFY_ENABLE) { 10285 return false; 10286 } 10287 // TODO: fix b/25118622; don't bypass verification 10288 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10289 return false; 10290 } 10291 // Ephemeral apps don't get the full verification treatment 10292 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10293 if (DEBUG_EPHEMERAL) { 10294 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10295 } 10296 return false; 10297 } 10298 10299 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10300 10301 // Check if installing from ADB 10302 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10303 // Do not run verification in a test harness environment 10304 if (ActivityManager.isRunningInTestHarness()) { 10305 return false; 10306 } 10307 if (ensureVerifyAppsEnabled) { 10308 return true; 10309 } 10310 // Check if the developer does not want package verification for ADB installs 10311 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10312 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10313 return false; 10314 } 10315 } 10316 10317 if (ensureVerifyAppsEnabled) { 10318 return true; 10319 } 10320 10321 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10322 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10323 } 10324 10325 @Override 10326 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10327 throws RemoteException { 10328 mContext.enforceCallingOrSelfPermission( 10329 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10330 "Only intentfilter verification agents can verify applications"); 10331 10332 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10333 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10334 Binder.getCallingUid(), verificationCode, failedDomains); 10335 msg.arg1 = id; 10336 msg.obj = response; 10337 mHandler.sendMessage(msg); 10338 } 10339 10340 @Override 10341 public int getIntentVerificationStatus(String packageName, int userId) { 10342 synchronized (mPackages) { 10343 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10344 } 10345 } 10346 10347 @Override 10348 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10349 mContext.enforceCallingOrSelfPermission( 10350 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10351 10352 boolean result = false; 10353 synchronized (mPackages) { 10354 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10355 } 10356 if (result) { 10357 scheduleWritePackageRestrictionsLocked(userId); 10358 } 10359 return result; 10360 } 10361 10362 @Override 10363 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10364 synchronized (mPackages) { 10365 return mSettings.getIntentFilterVerificationsLPr(packageName); 10366 } 10367 } 10368 10369 @Override 10370 public List<IntentFilter> getAllIntentFilters(String packageName) { 10371 if (TextUtils.isEmpty(packageName)) { 10372 return Collections.<IntentFilter>emptyList(); 10373 } 10374 synchronized (mPackages) { 10375 PackageParser.Package pkg = mPackages.get(packageName); 10376 if (pkg == null || pkg.activities == null) { 10377 return Collections.<IntentFilter>emptyList(); 10378 } 10379 final int count = pkg.activities.size(); 10380 ArrayList<IntentFilter> result = new ArrayList<>(); 10381 for (int n=0; n<count; n++) { 10382 PackageParser.Activity activity = pkg.activities.get(n); 10383 if (activity.intents != null || activity.intents.size() > 0) { 10384 result.addAll(activity.intents); 10385 } 10386 } 10387 return result; 10388 } 10389 } 10390 10391 @Override 10392 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10393 mContext.enforceCallingOrSelfPermission( 10394 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10395 10396 synchronized (mPackages) { 10397 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10398 if (packageName != null) { 10399 result |= updateIntentVerificationStatus(packageName, 10400 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10401 userId); 10402 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10403 packageName, userId); 10404 } 10405 return result; 10406 } 10407 } 10408 10409 @Override 10410 public String getDefaultBrowserPackageName(int userId) { 10411 synchronized (mPackages) { 10412 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10413 } 10414 } 10415 10416 /** 10417 * Get the "allow unknown sources" setting. 10418 * 10419 * @return the current "allow unknown sources" setting 10420 */ 10421 private int getUnknownSourcesSettings() { 10422 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10423 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10424 -1); 10425 } 10426 10427 @Override 10428 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10429 final int uid = Binder.getCallingUid(); 10430 // writer 10431 synchronized (mPackages) { 10432 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10433 if (targetPackageSetting == null) { 10434 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10435 } 10436 10437 PackageSetting installerPackageSetting; 10438 if (installerPackageName != null) { 10439 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10440 if (installerPackageSetting == null) { 10441 throw new IllegalArgumentException("Unknown installer package: " 10442 + installerPackageName); 10443 } 10444 } else { 10445 installerPackageSetting = null; 10446 } 10447 10448 Signature[] callerSignature; 10449 Object obj = mSettings.getUserIdLPr(uid); 10450 if (obj != null) { 10451 if (obj instanceof SharedUserSetting) { 10452 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10453 } else if (obj instanceof PackageSetting) { 10454 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10455 } else { 10456 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10457 } 10458 } else { 10459 throw new SecurityException("Unknown calling uid " + uid); 10460 } 10461 10462 // Verify: can't set installerPackageName to a package that is 10463 // not signed with the same cert as the caller. 10464 if (installerPackageSetting != null) { 10465 if (compareSignatures(callerSignature, 10466 installerPackageSetting.signatures.mSignatures) 10467 != PackageManager.SIGNATURE_MATCH) { 10468 throw new SecurityException( 10469 "Caller does not have same cert as new installer package " 10470 + installerPackageName); 10471 } 10472 } 10473 10474 // Verify: if target already has an installer package, it must 10475 // be signed with the same cert as the caller. 10476 if (targetPackageSetting.installerPackageName != null) { 10477 PackageSetting setting = mSettings.mPackages.get( 10478 targetPackageSetting.installerPackageName); 10479 // If the currently set package isn't valid, then it's always 10480 // okay to change it. 10481 if (setting != null) { 10482 if (compareSignatures(callerSignature, 10483 setting.signatures.mSignatures) 10484 != PackageManager.SIGNATURE_MATCH) { 10485 throw new SecurityException( 10486 "Caller does not have same cert as old installer package " 10487 + targetPackageSetting.installerPackageName); 10488 } 10489 } 10490 } 10491 10492 // Okay! 10493 targetPackageSetting.installerPackageName = installerPackageName; 10494 scheduleWriteSettingsLocked(); 10495 } 10496 } 10497 10498 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10499 // Queue up an async operation since the package installation may take a little while. 10500 mHandler.post(new Runnable() { 10501 public void run() { 10502 mHandler.removeCallbacks(this); 10503 // Result object to be returned 10504 PackageInstalledInfo res = new PackageInstalledInfo(); 10505 res.returnCode = currentStatus; 10506 res.uid = -1; 10507 res.pkg = null; 10508 res.removedInfo = new PackageRemovedInfo(); 10509 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10510 args.doPreInstall(res.returnCode); 10511 synchronized (mInstallLock) { 10512 installPackageTracedLI(args, res); 10513 } 10514 args.doPostInstall(res.returnCode, res.uid); 10515 } 10516 10517 // A restore should be performed at this point if (a) the install 10518 // succeeded, (b) the operation is not an update, and (c) the new 10519 // package has not opted out of backup participation. 10520 final boolean update = res.removedInfo.removedPackage != null; 10521 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10522 boolean doRestore = !update 10523 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10524 10525 // Set up the post-install work request bookkeeping. This will be used 10526 // and cleaned up by the post-install event handling regardless of whether 10527 // there's a restore pass performed. Token values are >= 1. 10528 int token; 10529 if (mNextInstallToken < 0) mNextInstallToken = 1; 10530 token = mNextInstallToken++; 10531 10532 PostInstallData data = new PostInstallData(args, res); 10533 mRunningInstalls.put(token, data); 10534 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10535 10536 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10537 // Pass responsibility to the Backup Manager. It will perform a 10538 // restore if appropriate, then pass responsibility back to the 10539 // Package Manager to run the post-install observer callbacks 10540 // and broadcasts. 10541 IBackupManager bm = IBackupManager.Stub.asInterface( 10542 ServiceManager.getService(Context.BACKUP_SERVICE)); 10543 if (bm != null) { 10544 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10545 + " to BM for possible restore"); 10546 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10547 try { 10548 // TODO: http://b/22388012 10549 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10550 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10551 } else { 10552 doRestore = false; 10553 } 10554 } catch (RemoteException e) { 10555 // can't happen; the backup manager is local 10556 } catch (Exception e) { 10557 Slog.e(TAG, "Exception trying to enqueue restore", e); 10558 doRestore = false; 10559 } 10560 } else { 10561 Slog.e(TAG, "Backup Manager not found!"); 10562 doRestore = false; 10563 } 10564 } 10565 10566 if (!doRestore) { 10567 // No restore possible, or the Backup Manager was mysteriously not 10568 // available -- just fire the post-install work request directly. 10569 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10570 10571 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10572 10573 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10574 mHandler.sendMessage(msg); 10575 } 10576 } 10577 }); 10578 } 10579 10580 private abstract class HandlerParams { 10581 private static final int MAX_RETRIES = 4; 10582 10583 /** 10584 * Number of times startCopy() has been attempted and had a non-fatal 10585 * error. 10586 */ 10587 private int mRetries = 0; 10588 10589 /** User handle for the user requesting the information or installation. */ 10590 private final UserHandle mUser; 10591 String traceMethod; 10592 int traceCookie; 10593 10594 HandlerParams(UserHandle user) { 10595 mUser = user; 10596 } 10597 10598 UserHandle getUser() { 10599 return mUser; 10600 } 10601 10602 HandlerParams setTraceMethod(String traceMethod) { 10603 this.traceMethod = traceMethod; 10604 return this; 10605 } 10606 10607 HandlerParams setTraceCookie(int traceCookie) { 10608 this.traceCookie = traceCookie; 10609 return this; 10610 } 10611 10612 final boolean startCopy() { 10613 boolean res; 10614 try { 10615 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10616 10617 if (++mRetries > MAX_RETRIES) { 10618 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10619 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10620 handleServiceError(); 10621 return false; 10622 } else { 10623 handleStartCopy(); 10624 res = true; 10625 } 10626 } catch (RemoteException e) { 10627 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10628 mHandler.sendEmptyMessage(MCS_RECONNECT); 10629 res = false; 10630 } 10631 handleReturnCode(); 10632 return res; 10633 } 10634 10635 final void serviceError() { 10636 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10637 handleServiceError(); 10638 handleReturnCode(); 10639 } 10640 10641 abstract void handleStartCopy() throws RemoteException; 10642 abstract void handleServiceError(); 10643 abstract void handleReturnCode(); 10644 } 10645 10646 class MeasureParams extends HandlerParams { 10647 private final PackageStats mStats; 10648 private boolean mSuccess; 10649 10650 private final IPackageStatsObserver mObserver; 10651 10652 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10653 super(new UserHandle(stats.userHandle)); 10654 mObserver = observer; 10655 mStats = stats; 10656 } 10657 10658 @Override 10659 public String toString() { 10660 return "MeasureParams{" 10661 + Integer.toHexString(System.identityHashCode(this)) 10662 + " " + mStats.packageName + "}"; 10663 } 10664 10665 @Override 10666 void handleStartCopy() throws RemoteException { 10667 synchronized (mInstallLock) { 10668 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10669 } 10670 10671 if (mSuccess) { 10672 final boolean mounted; 10673 if (Environment.isExternalStorageEmulated()) { 10674 mounted = true; 10675 } else { 10676 final String status = Environment.getExternalStorageState(); 10677 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10678 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10679 } 10680 10681 if (mounted) { 10682 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10683 10684 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10685 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10686 10687 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10688 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10689 10690 // Always subtract cache size, since it's a subdirectory 10691 mStats.externalDataSize -= mStats.externalCacheSize; 10692 10693 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10694 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10695 10696 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10697 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10698 } 10699 } 10700 } 10701 10702 @Override 10703 void handleReturnCode() { 10704 if (mObserver != null) { 10705 try { 10706 mObserver.onGetStatsCompleted(mStats, mSuccess); 10707 } catch (RemoteException e) { 10708 Slog.i(TAG, "Observer no longer exists."); 10709 } 10710 } 10711 } 10712 10713 @Override 10714 void handleServiceError() { 10715 Slog.e(TAG, "Could not measure application " + mStats.packageName 10716 + " external storage"); 10717 } 10718 } 10719 10720 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10721 throws RemoteException { 10722 long result = 0; 10723 for (File path : paths) { 10724 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10725 } 10726 return result; 10727 } 10728 10729 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10730 for (File path : paths) { 10731 try { 10732 mcs.clearDirectory(path.getAbsolutePath()); 10733 } catch (RemoteException e) { 10734 } 10735 } 10736 } 10737 10738 static class OriginInfo { 10739 /** 10740 * Location where install is coming from, before it has been 10741 * copied/renamed into place. This could be a single monolithic APK 10742 * file, or a cluster directory. This location may be untrusted. 10743 */ 10744 final File file; 10745 final String cid; 10746 10747 /** 10748 * Flag indicating that {@link #file} or {@link #cid} has already been 10749 * staged, meaning downstream users don't need to defensively copy the 10750 * contents. 10751 */ 10752 final boolean staged; 10753 10754 /** 10755 * Flag indicating that {@link #file} or {@link #cid} is an already 10756 * installed app that is being moved. 10757 */ 10758 final boolean existing; 10759 10760 final String resolvedPath; 10761 final File resolvedFile; 10762 10763 static OriginInfo fromNothing() { 10764 return new OriginInfo(null, null, false, false); 10765 } 10766 10767 static OriginInfo fromUntrustedFile(File file) { 10768 return new OriginInfo(file, null, false, false); 10769 } 10770 10771 static OriginInfo fromExistingFile(File file) { 10772 return new OriginInfo(file, null, false, true); 10773 } 10774 10775 static OriginInfo fromStagedFile(File file) { 10776 return new OriginInfo(file, null, true, false); 10777 } 10778 10779 static OriginInfo fromStagedContainer(String cid) { 10780 return new OriginInfo(null, cid, true, false); 10781 } 10782 10783 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10784 this.file = file; 10785 this.cid = cid; 10786 this.staged = staged; 10787 this.existing = existing; 10788 10789 if (cid != null) { 10790 resolvedPath = PackageHelper.getSdDir(cid); 10791 resolvedFile = new File(resolvedPath); 10792 } else if (file != null) { 10793 resolvedPath = file.getAbsolutePath(); 10794 resolvedFile = file; 10795 } else { 10796 resolvedPath = null; 10797 resolvedFile = null; 10798 } 10799 } 10800 } 10801 10802 class MoveInfo { 10803 final int moveId; 10804 final String fromUuid; 10805 final String toUuid; 10806 final String packageName; 10807 final String dataAppName; 10808 final int appId; 10809 final String seinfo; 10810 10811 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10812 String dataAppName, int appId, String seinfo) { 10813 this.moveId = moveId; 10814 this.fromUuid = fromUuid; 10815 this.toUuid = toUuid; 10816 this.packageName = packageName; 10817 this.dataAppName = dataAppName; 10818 this.appId = appId; 10819 this.seinfo = seinfo; 10820 } 10821 } 10822 10823 class InstallParams extends HandlerParams { 10824 final OriginInfo origin; 10825 final MoveInfo move; 10826 final IPackageInstallObserver2 observer; 10827 int installFlags; 10828 final String installerPackageName; 10829 final String volumeUuid; 10830 final VerificationParams verificationParams; 10831 private InstallArgs mArgs; 10832 private int mRet; 10833 final String packageAbiOverride; 10834 final String[] grantedRuntimePermissions; 10835 10836 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10837 int installFlags, String installerPackageName, String volumeUuid, 10838 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10839 String[] grantedPermissions) { 10840 super(user); 10841 this.origin = origin; 10842 this.move = move; 10843 this.observer = observer; 10844 this.installFlags = installFlags; 10845 this.installerPackageName = installerPackageName; 10846 this.volumeUuid = volumeUuid; 10847 this.verificationParams = verificationParams; 10848 this.packageAbiOverride = packageAbiOverride; 10849 this.grantedRuntimePermissions = grantedPermissions; 10850 } 10851 10852 @Override 10853 public String toString() { 10854 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10855 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10856 } 10857 10858 public ManifestDigest getManifestDigest() { 10859 if (verificationParams == null) { 10860 return null; 10861 } 10862 return verificationParams.getManifestDigest(); 10863 } 10864 10865 private int installLocationPolicy(PackageInfoLite pkgLite) { 10866 String packageName = pkgLite.packageName; 10867 int installLocation = pkgLite.installLocation; 10868 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10869 // reader 10870 synchronized (mPackages) { 10871 PackageParser.Package pkg = mPackages.get(packageName); 10872 if (pkg != null) { 10873 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10874 // Check for downgrading. 10875 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10876 try { 10877 checkDowngrade(pkg, pkgLite); 10878 } catch (PackageManagerException e) { 10879 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10880 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10881 } 10882 } 10883 // Check for updated system application. 10884 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10885 if (onSd) { 10886 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10887 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10888 } 10889 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10890 } else { 10891 if (onSd) { 10892 // Install flag overrides everything. 10893 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10894 } 10895 // If current upgrade specifies particular preference 10896 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10897 // Application explicitly specified internal. 10898 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10899 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10900 // App explictly prefers external. Let policy decide 10901 } else { 10902 // Prefer previous location 10903 if (isExternal(pkg)) { 10904 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10905 } 10906 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10907 } 10908 } 10909 } else { 10910 // Invalid install. Return error code 10911 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10912 } 10913 } 10914 } 10915 // All the special cases have been taken care of. 10916 // Return result based on recommended install location. 10917 if (onSd) { 10918 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10919 } 10920 return pkgLite.recommendedInstallLocation; 10921 } 10922 10923 /* 10924 * Invoke remote method to get package information and install 10925 * location values. Override install location based on default 10926 * policy if needed and then create install arguments based 10927 * on the install location. 10928 */ 10929 public void handleStartCopy() throws RemoteException { 10930 int ret = PackageManager.INSTALL_SUCCEEDED; 10931 10932 // If we're already staged, we've firmly committed to an install location 10933 if (origin.staged) { 10934 if (origin.file != null) { 10935 installFlags |= PackageManager.INSTALL_INTERNAL; 10936 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10937 } else if (origin.cid != null) { 10938 installFlags |= PackageManager.INSTALL_EXTERNAL; 10939 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10940 } else { 10941 throw new IllegalStateException("Invalid stage location"); 10942 } 10943 } 10944 10945 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10946 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10947 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 10948 PackageInfoLite pkgLite = null; 10949 10950 if (onInt && onSd) { 10951 // Check if both bits are set. 10952 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10953 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10954 } else if (onSd && ephemeral) { 10955 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 10956 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10957 } else { 10958 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10959 packageAbiOverride); 10960 10961 if (DEBUG_EPHEMERAL && ephemeral) { 10962 Slog.v(TAG, "pkgLite for install: " + pkgLite); 10963 } 10964 10965 /* 10966 * If we have too little free space, try to free cache 10967 * before giving up. 10968 */ 10969 if (!origin.staged && pkgLite.recommendedInstallLocation 10970 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10971 // TODO: focus freeing disk space on the target device 10972 final StorageManager storage = StorageManager.from(mContext); 10973 final long lowThreshold = storage.getStorageLowBytes( 10974 Environment.getDataDirectory()); 10975 10976 final long sizeBytes = mContainerService.calculateInstalledSize( 10977 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10978 10979 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10980 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10981 installFlags, packageAbiOverride); 10982 } 10983 10984 /* 10985 * The cache free must have deleted the file we 10986 * downloaded to install. 10987 * 10988 * TODO: fix the "freeCache" call to not delete 10989 * the file we care about. 10990 */ 10991 if (pkgLite.recommendedInstallLocation 10992 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10993 pkgLite.recommendedInstallLocation 10994 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10995 } 10996 } 10997 } 10998 10999 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11000 int loc = pkgLite.recommendedInstallLocation; 11001 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11002 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11003 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11004 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11005 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11006 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11007 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11008 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11009 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11010 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11011 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11012 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11013 } else { 11014 // Override with defaults if needed. 11015 loc = installLocationPolicy(pkgLite); 11016 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11017 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11018 } else if (!onSd && !onInt) { 11019 // Override install location with flags 11020 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11021 // Set the flag to install on external media. 11022 installFlags |= PackageManager.INSTALL_EXTERNAL; 11023 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11024 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11025 if (DEBUG_EPHEMERAL) { 11026 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11027 } 11028 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11029 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11030 |PackageManager.INSTALL_INTERNAL); 11031 } else { 11032 // Make sure the flag for installing on external 11033 // media is unset 11034 installFlags |= PackageManager.INSTALL_INTERNAL; 11035 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11036 } 11037 } 11038 } 11039 } 11040 11041 final InstallArgs args = createInstallArgs(this); 11042 mArgs = args; 11043 11044 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11045 // TODO: http://b/22976637 11046 // Apps installed for "all" users use the device owner to verify the app 11047 UserHandle verifierUser = getUser(); 11048 if (verifierUser == UserHandle.ALL) { 11049 verifierUser = UserHandle.SYSTEM; 11050 } 11051 11052 /* 11053 * Determine if we have any installed package verifiers. If we 11054 * do, then we'll defer to them to verify the packages. 11055 */ 11056 final int requiredUid = mRequiredVerifierPackage == null ? -1 11057 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11058 if (!origin.existing && requiredUid != -1 11059 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11060 final Intent verification = new Intent( 11061 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11062 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11063 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11064 PACKAGE_MIME_TYPE); 11065 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11066 11067 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11068 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11069 verifierUser.getIdentifier()); 11070 11071 if (DEBUG_VERIFY) { 11072 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11073 + verification.toString() + " with " + pkgLite.verifiers.length 11074 + " optional verifiers"); 11075 } 11076 11077 final int verificationId = mPendingVerificationToken++; 11078 11079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11080 11081 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11082 installerPackageName); 11083 11084 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11085 installFlags); 11086 11087 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11088 pkgLite.packageName); 11089 11090 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11091 pkgLite.versionCode); 11092 11093 if (verificationParams != null) { 11094 if (verificationParams.getVerificationURI() != null) { 11095 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11096 verificationParams.getVerificationURI()); 11097 } 11098 if (verificationParams.getOriginatingURI() != null) { 11099 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11100 verificationParams.getOriginatingURI()); 11101 } 11102 if (verificationParams.getReferrer() != null) { 11103 verification.putExtra(Intent.EXTRA_REFERRER, 11104 verificationParams.getReferrer()); 11105 } 11106 if (verificationParams.getOriginatingUid() >= 0) { 11107 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11108 verificationParams.getOriginatingUid()); 11109 } 11110 if (verificationParams.getInstallerUid() >= 0) { 11111 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11112 verificationParams.getInstallerUid()); 11113 } 11114 } 11115 11116 final PackageVerificationState verificationState = new PackageVerificationState( 11117 requiredUid, args); 11118 11119 mPendingVerification.append(verificationId, verificationState); 11120 11121 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11122 receivers, verificationState); 11123 11124 /* 11125 * If any sufficient verifiers were listed in the package 11126 * manifest, attempt to ask them. 11127 */ 11128 if (sufficientVerifiers != null) { 11129 final int N = sufficientVerifiers.size(); 11130 if (N == 0) { 11131 Slog.i(TAG, "Additional verifiers required, but none installed."); 11132 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11133 } else { 11134 for (int i = 0; i < N; i++) { 11135 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11136 11137 final Intent sufficientIntent = new Intent(verification); 11138 sufficientIntent.setComponent(verifierComponent); 11139 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11140 } 11141 } 11142 } 11143 11144 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11145 mRequiredVerifierPackage, receivers); 11146 if (ret == PackageManager.INSTALL_SUCCEEDED 11147 && mRequiredVerifierPackage != null) { 11148 Trace.asyncTraceBegin( 11149 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11150 /* 11151 * Send the intent to the required verification agent, 11152 * but only start the verification timeout after the 11153 * target BroadcastReceivers have run. 11154 */ 11155 verification.setComponent(requiredVerifierComponent); 11156 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11157 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11158 new BroadcastReceiver() { 11159 @Override 11160 public void onReceive(Context context, Intent intent) { 11161 final Message msg = mHandler 11162 .obtainMessage(CHECK_PENDING_VERIFICATION); 11163 msg.arg1 = verificationId; 11164 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11165 } 11166 }, null, 0, null, null); 11167 11168 /* 11169 * We don't want the copy to proceed until verification 11170 * succeeds, so null out this field. 11171 */ 11172 mArgs = null; 11173 } 11174 } else { 11175 /* 11176 * No package verification is enabled, so immediately start 11177 * the remote call to initiate copy using temporary file. 11178 */ 11179 ret = args.copyApk(mContainerService, true); 11180 } 11181 } 11182 11183 mRet = ret; 11184 } 11185 11186 @Override 11187 void handleReturnCode() { 11188 // If mArgs is null, then MCS couldn't be reached. When it 11189 // reconnects, it will try again to install. At that point, this 11190 // will succeed. 11191 if (mArgs != null) { 11192 processPendingInstall(mArgs, mRet); 11193 } 11194 } 11195 11196 @Override 11197 void handleServiceError() { 11198 mArgs = createInstallArgs(this); 11199 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11200 } 11201 11202 public boolean isForwardLocked() { 11203 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11204 } 11205 } 11206 11207 /** 11208 * Used during creation of InstallArgs 11209 * 11210 * @param installFlags package installation flags 11211 * @return true if should be installed on external storage 11212 */ 11213 private static boolean installOnExternalAsec(int installFlags) { 11214 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11215 return false; 11216 } 11217 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11218 return true; 11219 } 11220 return false; 11221 } 11222 11223 /** 11224 * Used during creation of InstallArgs 11225 * 11226 * @param installFlags package installation flags 11227 * @return true if should be installed as forward locked 11228 */ 11229 private static boolean installForwardLocked(int installFlags) { 11230 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11231 } 11232 11233 private InstallArgs createInstallArgs(InstallParams params) { 11234 if (params.move != null) { 11235 return new MoveInstallArgs(params); 11236 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11237 return new AsecInstallArgs(params); 11238 } else { 11239 return new FileInstallArgs(params); 11240 } 11241 } 11242 11243 /** 11244 * Create args that describe an existing installed package. Typically used 11245 * when cleaning up old installs, or used as a move source. 11246 */ 11247 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11248 String resourcePath, String[] instructionSets) { 11249 final boolean isInAsec; 11250 if (installOnExternalAsec(installFlags)) { 11251 /* Apps on SD card are always in ASEC containers. */ 11252 isInAsec = true; 11253 } else if (installForwardLocked(installFlags) 11254 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11255 /* 11256 * Forward-locked apps are only in ASEC containers if they're the 11257 * new style 11258 */ 11259 isInAsec = true; 11260 } else { 11261 isInAsec = false; 11262 } 11263 11264 if (isInAsec) { 11265 return new AsecInstallArgs(codePath, instructionSets, 11266 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11267 } else { 11268 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11269 } 11270 } 11271 11272 static abstract class InstallArgs { 11273 /** @see InstallParams#origin */ 11274 final OriginInfo origin; 11275 /** @see InstallParams#move */ 11276 final MoveInfo move; 11277 11278 final IPackageInstallObserver2 observer; 11279 // Always refers to PackageManager flags only 11280 final int installFlags; 11281 final String installerPackageName; 11282 final String volumeUuid; 11283 final ManifestDigest manifestDigest; 11284 final UserHandle user; 11285 final String abiOverride; 11286 final String[] installGrantPermissions; 11287 /** If non-null, drop an async trace when the install completes */ 11288 final String traceMethod; 11289 final int traceCookie; 11290 11291 // The list of instruction sets supported by this app. This is currently 11292 // only used during the rmdex() phase to clean up resources. We can get rid of this 11293 // if we move dex files under the common app path. 11294 /* nullable */ String[] instructionSets; 11295 11296 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11297 int installFlags, String installerPackageName, String volumeUuid, 11298 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11299 String abiOverride, String[] installGrantPermissions, 11300 String traceMethod, int traceCookie) { 11301 this.origin = origin; 11302 this.move = move; 11303 this.installFlags = installFlags; 11304 this.observer = observer; 11305 this.installerPackageName = installerPackageName; 11306 this.volumeUuid = volumeUuid; 11307 this.manifestDigest = manifestDigest; 11308 this.user = user; 11309 this.instructionSets = instructionSets; 11310 this.abiOverride = abiOverride; 11311 this.installGrantPermissions = installGrantPermissions; 11312 this.traceMethod = traceMethod; 11313 this.traceCookie = traceCookie; 11314 } 11315 11316 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11317 abstract int doPreInstall(int status); 11318 11319 /** 11320 * Rename package into final resting place. All paths on the given 11321 * scanned package should be updated to reflect the rename. 11322 */ 11323 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11324 abstract int doPostInstall(int status, int uid); 11325 11326 /** @see PackageSettingBase#codePathString */ 11327 abstract String getCodePath(); 11328 /** @see PackageSettingBase#resourcePathString */ 11329 abstract String getResourcePath(); 11330 11331 // Need installer lock especially for dex file removal. 11332 abstract void cleanUpResourcesLI(); 11333 abstract boolean doPostDeleteLI(boolean delete); 11334 11335 /** 11336 * Called before the source arguments are copied. This is used mostly 11337 * for MoveParams when it needs to read the source file to put it in the 11338 * destination. 11339 */ 11340 int doPreCopy() { 11341 return PackageManager.INSTALL_SUCCEEDED; 11342 } 11343 11344 /** 11345 * Called after the source arguments are copied. This is used mostly for 11346 * MoveParams when it needs to read the source file to put it in the 11347 * destination. 11348 * 11349 * @return 11350 */ 11351 int doPostCopy(int uid) { 11352 return PackageManager.INSTALL_SUCCEEDED; 11353 } 11354 11355 protected boolean isFwdLocked() { 11356 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11357 } 11358 11359 protected boolean isExternalAsec() { 11360 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11361 } 11362 11363 protected boolean isEphemeral() { 11364 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11365 } 11366 11367 UserHandle getUser() { 11368 return user; 11369 } 11370 } 11371 11372 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11373 if (!allCodePaths.isEmpty()) { 11374 if (instructionSets == null) { 11375 throw new IllegalStateException("instructionSet == null"); 11376 } 11377 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11378 for (String codePath : allCodePaths) { 11379 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11380 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11381 if (retCode < 0) { 11382 Slog.w(TAG, "Couldn't remove dex file for package: " 11383 + " at location " + codePath + ", retcode=" + retCode); 11384 // we don't consider this to be a failure of the core package deletion 11385 } 11386 } 11387 } 11388 } 11389 } 11390 11391 /** 11392 * Logic to handle installation of non-ASEC applications, including copying 11393 * and renaming logic. 11394 */ 11395 class FileInstallArgs extends InstallArgs { 11396 private File codeFile; 11397 private File resourceFile; 11398 11399 // Example topology: 11400 // /data/app/com.example/base.apk 11401 // /data/app/com.example/split_foo.apk 11402 // /data/app/com.example/lib/arm/libfoo.so 11403 // /data/app/com.example/lib/arm64/libfoo.so 11404 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11405 11406 /** New install */ 11407 FileInstallArgs(InstallParams params) { 11408 super(params.origin, params.move, params.observer, params.installFlags, 11409 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11410 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11411 params.grantedRuntimePermissions, 11412 params.traceMethod, params.traceCookie); 11413 if (isFwdLocked()) { 11414 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11415 } 11416 } 11417 11418 /** Existing install */ 11419 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11420 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11421 null, null, null, 0); 11422 this.codeFile = (codePath != null) ? new File(codePath) : null; 11423 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11424 } 11425 11426 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11428 try { 11429 return doCopyApk(imcs, temp); 11430 } finally { 11431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11432 } 11433 } 11434 11435 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11436 if (origin.staged) { 11437 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11438 codeFile = origin.file; 11439 resourceFile = origin.file; 11440 return PackageManager.INSTALL_SUCCEEDED; 11441 } 11442 11443 try { 11444 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11445 final File tempDir = 11446 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11447 codeFile = tempDir; 11448 resourceFile = tempDir; 11449 } catch (IOException e) { 11450 Slog.w(TAG, "Failed to create copy file: " + e); 11451 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11452 } 11453 11454 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11455 @Override 11456 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11457 if (!FileUtils.isValidExtFilename(name)) { 11458 throw new IllegalArgumentException("Invalid filename: " + name); 11459 } 11460 try { 11461 final File file = new File(codeFile, name); 11462 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11463 O_RDWR | O_CREAT, 0644); 11464 Os.chmod(file.getAbsolutePath(), 0644); 11465 return new ParcelFileDescriptor(fd); 11466 } catch (ErrnoException e) { 11467 throw new RemoteException("Failed to open: " + e.getMessage()); 11468 } 11469 } 11470 }; 11471 11472 int ret = PackageManager.INSTALL_SUCCEEDED; 11473 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11474 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11475 Slog.e(TAG, "Failed to copy package"); 11476 return ret; 11477 } 11478 11479 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11480 NativeLibraryHelper.Handle handle = null; 11481 try { 11482 handle = NativeLibraryHelper.Handle.create(codeFile); 11483 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11484 abiOverride); 11485 } catch (IOException e) { 11486 Slog.e(TAG, "Copying native libraries failed", e); 11487 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11488 } finally { 11489 IoUtils.closeQuietly(handle); 11490 } 11491 11492 return ret; 11493 } 11494 11495 int doPreInstall(int status) { 11496 if (status != PackageManager.INSTALL_SUCCEEDED) { 11497 cleanUp(); 11498 } 11499 return status; 11500 } 11501 11502 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11503 if (status != PackageManager.INSTALL_SUCCEEDED) { 11504 cleanUp(); 11505 return false; 11506 } 11507 11508 final File targetDir = codeFile.getParentFile(); 11509 final File beforeCodeFile = codeFile; 11510 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11511 11512 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11513 try { 11514 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11515 } catch (ErrnoException e) { 11516 Slog.w(TAG, "Failed to rename", e); 11517 return false; 11518 } 11519 11520 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11521 Slog.w(TAG, "Failed to restorecon"); 11522 return false; 11523 } 11524 11525 // Reflect the rename internally 11526 codeFile = afterCodeFile; 11527 resourceFile = afterCodeFile; 11528 11529 // Reflect the rename in scanned details 11530 pkg.codePath = afterCodeFile.getAbsolutePath(); 11531 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11532 pkg.baseCodePath); 11533 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11534 pkg.splitCodePaths); 11535 11536 // Reflect the rename in app info 11537 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11538 pkg.applicationInfo.setCodePath(pkg.codePath); 11539 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11540 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11541 pkg.applicationInfo.setResourcePath(pkg.codePath); 11542 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11543 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11544 11545 return true; 11546 } 11547 11548 int doPostInstall(int status, int uid) { 11549 if (status != PackageManager.INSTALL_SUCCEEDED) { 11550 cleanUp(); 11551 } 11552 return status; 11553 } 11554 11555 @Override 11556 String getCodePath() { 11557 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11558 } 11559 11560 @Override 11561 String getResourcePath() { 11562 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11563 } 11564 11565 private boolean cleanUp() { 11566 if (codeFile == null || !codeFile.exists()) { 11567 return false; 11568 } 11569 11570 if (codeFile.isDirectory()) { 11571 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11572 } else { 11573 codeFile.delete(); 11574 } 11575 11576 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11577 resourceFile.delete(); 11578 } 11579 11580 return true; 11581 } 11582 11583 void cleanUpResourcesLI() { 11584 // Try enumerating all code paths before deleting 11585 List<String> allCodePaths = Collections.EMPTY_LIST; 11586 if (codeFile != null && codeFile.exists()) { 11587 try { 11588 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11589 allCodePaths = pkg.getAllCodePaths(); 11590 } catch (PackageParserException e) { 11591 // Ignored; we tried our best 11592 } 11593 } 11594 11595 cleanUp(); 11596 removeDexFiles(allCodePaths, instructionSets); 11597 } 11598 11599 boolean doPostDeleteLI(boolean delete) { 11600 // XXX err, shouldn't we respect the delete flag? 11601 cleanUpResourcesLI(); 11602 return true; 11603 } 11604 } 11605 11606 private boolean isAsecExternal(String cid) { 11607 final String asecPath = PackageHelper.getSdFilesystem(cid); 11608 return !asecPath.startsWith(mAsecInternalPath); 11609 } 11610 11611 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11612 PackageManagerException { 11613 if (copyRet < 0) { 11614 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11615 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11616 throw new PackageManagerException(copyRet, message); 11617 } 11618 } 11619 } 11620 11621 /** 11622 * Extract the MountService "container ID" from the full code path of an 11623 * .apk. 11624 */ 11625 static String cidFromCodePath(String fullCodePath) { 11626 int eidx = fullCodePath.lastIndexOf("/"); 11627 String subStr1 = fullCodePath.substring(0, eidx); 11628 int sidx = subStr1.lastIndexOf("/"); 11629 return subStr1.substring(sidx+1, eidx); 11630 } 11631 11632 /** 11633 * Logic to handle installation of ASEC applications, including copying and 11634 * renaming logic. 11635 */ 11636 class AsecInstallArgs extends InstallArgs { 11637 static final String RES_FILE_NAME = "pkg.apk"; 11638 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11639 11640 String cid; 11641 String packagePath; 11642 String resourcePath; 11643 11644 /** New install */ 11645 AsecInstallArgs(InstallParams params) { 11646 super(params.origin, params.move, params.observer, params.installFlags, 11647 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11648 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11649 params.grantedRuntimePermissions, 11650 params.traceMethod, params.traceCookie); 11651 } 11652 11653 /** Existing install */ 11654 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11655 boolean isExternal, boolean isForwardLocked) { 11656 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11657 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11658 instructionSets, null, null, null, 0); 11659 // Hackily pretend we're still looking at a full code path 11660 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11661 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11662 } 11663 11664 // Extract cid from fullCodePath 11665 int eidx = fullCodePath.lastIndexOf("/"); 11666 String subStr1 = fullCodePath.substring(0, eidx); 11667 int sidx = subStr1.lastIndexOf("/"); 11668 cid = subStr1.substring(sidx+1, eidx); 11669 setMountPath(subStr1); 11670 } 11671 11672 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11673 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11674 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11675 instructionSets, null, null, null, 0); 11676 this.cid = cid; 11677 setMountPath(PackageHelper.getSdDir(cid)); 11678 } 11679 11680 void createCopyFile() { 11681 cid = mInstallerService.allocateExternalStageCidLegacy(); 11682 } 11683 11684 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11685 if (origin.staged && origin.cid != null) { 11686 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11687 cid = origin.cid; 11688 setMountPath(PackageHelper.getSdDir(cid)); 11689 return PackageManager.INSTALL_SUCCEEDED; 11690 } 11691 11692 if (temp) { 11693 createCopyFile(); 11694 } else { 11695 /* 11696 * Pre-emptively destroy the container since it's destroyed if 11697 * copying fails due to it existing anyway. 11698 */ 11699 PackageHelper.destroySdDir(cid); 11700 } 11701 11702 final String newMountPath = imcs.copyPackageToContainer( 11703 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11704 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11705 11706 if (newMountPath != null) { 11707 setMountPath(newMountPath); 11708 return PackageManager.INSTALL_SUCCEEDED; 11709 } else { 11710 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11711 } 11712 } 11713 11714 @Override 11715 String getCodePath() { 11716 return packagePath; 11717 } 11718 11719 @Override 11720 String getResourcePath() { 11721 return resourcePath; 11722 } 11723 11724 int doPreInstall(int status) { 11725 if (status != PackageManager.INSTALL_SUCCEEDED) { 11726 // Destroy container 11727 PackageHelper.destroySdDir(cid); 11728 } else { 11729 boolean mounted = PackageHelper.isContainerMounted(cid); 11730 if (!mounted) { 11731 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11732 Process.SYSTEM_UID); 11733 if (newMountPath != null) { 11734 setMountPath(newMountPath); 11735 } else { 11736 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11737 } 11738 } 11739 } 11740 return status; 11741 } 11742 11743 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11744 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11745 String newMountPath = null; 11746 if (PackageHelper.isContainerMounted(cid)) { 11747 // Unmount the container 11748 if (!PackageHelper.unMountSdDir(cid)) { 11749 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11750 return false; 11751 } 11752 } 11753 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11754 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11755 " which might be stale. Will try to clean up."); 11756 // Clean up the stale container and proceed to recreate. 11757 if (!PackageHelper.destroySdDir(newCacheId)) { 11758 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11759 return false; 11760 } 11761 // Successfully cleaned up stale container. Try to rename again. 11762 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11763 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11764 + " inspite of cleaning it up."); 11765 return false; 11766 } 11767 } 11768 if (!PackageHelper.isContainerMounted(newCacheId)) { 11769 Slog.w(TAG, "Mounting container " + newCacheId); 11770 newMountPath = PackageHelper.mountSdDir(newCacheId, 11771 getEncryptKey(), Process.SYSTEM_UID); 11772 } else { 11773 newMountPath = PackageHelper.getSdDir(newCacheId); 11774 } 11775 if (newMountPath == null) { 11776 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11777 return false; 11778 } 11779 Log.i(TAG, "Succesfully renamed " + cid + 11780 " to " + newCacheId + 11781 " at new path: " + newMountPath); 11782 cid = newCacheId; 11783 11784 final File beforeCodeFile = new File(packagePath); 11785 setMountPath(newMountPath); 11786 final File afterCodeFile = new File(packagePath); 11787 11788 // Reflect the rename in scanned details 11789 pkg.codePath = afterCodeFile.getAbsolutePath(); 11790 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11791 pkg.baseCodePath); 11792 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11793 pkg.splitCodePaths); 11794 11795 // Reflect the rename in app info 11796 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11797 pkg.applicationInfo.setCodePath(pkg.codePath); 11798 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11799 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11800 pkg.applicationInfo.setResourcePath(pkg.codePath); 11801 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11802 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11803 11804 return true; 11805 } 11806 11807 private void setMountPath(String mountPath) { 11808 final File mountFile = new File(mountPath); 11809 11810 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11811 if (monolithicFile.exists()) { 11812 packagePath = monolithicFile.getAbsolutePath(); 11813 if (isFwdLocked()) { 11814 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11815 } else { 11816 resourcePath = packagePath; 11817 } 11818 } else { 11819 packagePath = mountFile.getAbsolutePath(); 11820 resourcePath = packagePath; 11821 } 11822 } 11823 11824 int doPostInstall(int status, int uid) { 11825 if (status != PackageManager.INSTALL_SUCCEEDED) { 11826 cleanUp(); 11827 } else { 11828 final int groupOwner; 11829 final String protectedFile; 11830 if (isFwdLocked()) { 11831 groupOwner = UserHandle.getSharedAppGid(uid); 11832 protectedFile = RES_FILE_NAME; 11833 } else { 11834 groupOwner = -1; 11835 protectedFile = null; 11836 } 11837 11838 if (uid < Process.FIRST_APPLICATION_UID 11839 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11840 Slog.e(TAG, "Failed to finalize " + cid); 11841 PackageHelper.destroySdDir(cid); 11842 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11843 } 11844 11845 boolean mounted = PackageHelper.isContainerMounted(cid); 11846 if (!mounted) { 11847 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11848 } 11849 } 11850 return status; 11851 } 11852 11853 private void cleanUp() { 11854 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11855 11856 // Destroy secure container 11857 PackageHelper.destroySdDir(cid); 11858 } 11859 11860 private List<String> getAllCodePaths() { 11861 final File codeFile = new File(getCodePath()); 11862 if (codeFile != null && codeFile.exists()) { 11863 try { 11864 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11865 return pkg.getAllCodePaths(); 11866 } catch (PackageParserException e) { 11867 // Ignored; we tried our best 11868 } 11869 } 11870 return Collections.EMPTY_LIST; 11871 } 11872 11873 void cleanUpResourcesLI() { 11874 // Enumerate all code paths before deleting 11875 cleanUpResourcesLI(getAllCodePaths()); 11876 } 11877 11878 private void cleanUpResourcesLI(List<String> allCodePaths) { 11879 cleanUp(); 11880 removeDexFiles(allCodePaths, instructionSets); 11881 } 11882 11883 String getPackageName() { 11884 return getAsecPackageName(cid); 11885 } 11886 11887 boolean doPostDeleteLI(boolean delete) { 11888 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11889 final List<String> allCodePaths = getAllCodePaths(); 11890 boolean mounted = PackageHelper.isContainerMounted(cid); 11891 if (mounted) { 11892 // Unmount first 11893 if (PackageHelper.unMountSdDir(cid)) { 11894 mounted = false; 11895 } 11896 } 11897 if (!mounted && delete) { 11898 cleanUpResourcesLI(allCodePaths); 11899 } 11900 return !mounted; 11901 } 11902 11903 @Override 11904 int doPreCopy() { 11905 if (isFwdLocked()) { 11906 if (!PackageHelper.fixSdPermissions(cid, 11907 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11908 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11909 } 11910 } 11911 11912 return PackageManager.INSTALL_SUCCEEDED; 11913 } 11914 11915 @Override 11916 int doPostCopy(int uid) { 11917 if (isFwdLocked()) { 11918 if (uid < Process.FIRST_APPLICATION_UID 11919 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11920 RES_FILE_NAME)) { 11921 Slog.e(TAG, "Failed to finalize " + cid); 11922 PackageHelper.destroySdDir(cid); 11923 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11924 } 11925 } 11926 11927 return PackageManager.INSTALL_SUCCEEDED; 11928 } 11929 } 11930 11931 /** 11932 * Logic to handle movement of existing installed applications. 11933 */ 11934 class MoveInstallArgs extends InstallArgs { 11935 private File codeFile; 11936 private File resourceFile; 11937 11938 /** New install */ 11939 MoveInstallArgs(InstallParams params) { 11940 super(params.origin, params.move, params.observer, params.installFlags, 11941 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11942 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11943 params.grantedRuntimePermissions, 11944 params.traceMethod, params.traceCookie); 11945 } 11946 11947 int copyApk(IMediaContainerService imcs, boolean temp) { 11948 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11949 + move.fromUuid + " to " + move.toUuid); 11950 synchronized (mInstaller) { 11951 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11952 move.dataAppName, move.appId, move.seinfo) != 0) { 11953 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11954 } 11955 } 11956 11957 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11958 resourceFile = codeFile; 11959 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11960 11961 return PackageManager.INSTALL_SUCCEEDED; 11962 } 11963 11964 int doPreInstall(int status) { 11965 if (status != PackageManager.INSTALL_SUCCEEDED) { 11966 cleanUp(move.toUuid); 11967 } 11968 return status; 11969 } 11970 11971 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11972 if (status != PackageManager.INSTALL_SUCCEEDED) { 11973 cleanUp(move.toUuid); 11974 return false; 11975 } 11976 11977 // Reflect the move in app info 11978 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11979 pkg.applicationInfo.setCodePath(pkg.codePath); 11980 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11981 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11982 pkg.applicationInfo.setResourcePath(pkg.codePath); 11983 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11984 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11985 11986 return true; 11987 } 11988 11989 int doPostInstall(int status, int uid) { 11990 if (status == PackageManager.INSTALL_SUCCEEDED) { 11991 cleanUp(move.fromUuid); 11992 } else { 11993 cleanUp(move.toUuid); 11994 } 11995 return status; 11996 } 11997 11998 @Override 11999 String getCodePath() { 12000 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12001 } 12002 12003 @Override 12004 String getResourcePath() { 12005 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12006 } 12007 12008 private boolean cleanUp(String volumeUuid) { 12009 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12010 move.dataAppName); 12011 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12012 synchronized (mInstallLock) { 12013 // Clean up both app data and code 12014 removeDataDirsLI(volumeUuid, move.packageName); 12015 if (codeFile.isDirectory()) { 12016 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12017 } else { 12018 codeFile.delete(); 12019 } 12020 } 12021 return true; 12022 } 12023 12024 void cleanUpResourcesLI() { 12025 throw new UnsupportedOperationException(); 12026 } 12027 12028 boolean doPostDeleteLI(boolean delete) { 12029 throw new UnsupportedOperationException(); 12030 } 12031 } 12032 12033 static String getAsecPackageName(String packageCid) { 12034 int idx = packageCid.lastIndexOf("-"); 12035 if (idx == -1) { 12036 return packageCid; 12037 } 12038 return packageCid.substring(0, idx); 12039 } 12040 12041 // Utility method used to create code paths based on package name and available index. 12042 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12043 String idxStr = ""; 12044 int idx = 1; 12045 // Fall back to default value of idx=1 if prefix is not 12046 // part of oldCodePath 12047 if (oldCodePath != null) { 12048 String subStr = oldCodePath; 12049 // Drop the suffix right away 12050 if (suffix != null && subStr.endsWith(suffix)) { 12051 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12052 } 12053 // If oldCodePath already contains prefix find out the 12054 // ending index to either increment or decrement. 12055 int sidx = subStr.lastIndexOf(prefix); 12056 if (sidx != -1) { 12057 subStr = subStr.substring(sidx + prefix.length()); 12058 if (subStr != null) { 12059 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12060 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12061 } 12062 try { 12063 idx = Integer.parseInt(subStr); 12064 if (idx <= 1) { 12065 idx++; 12066 } else { 12067 idx--; 12068 } 12069 } catch(NumberFormatException e) { 12070 } 12071 } 12072 } 12073 } 12074 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12075 return prefix + idxStr; 12076 } 12077 12078 private File getNextCodePath(File targetDir, String packageName) { 12079 int suffix = 1; 12080 File result; 12081 do { 12082 result = new File(targetDir, packageName + "-" + suffix); 12083 suffix++; 12084 } while (result.exists()); 12085 return result; 12086 } 12087 12088 // Utility method that returns the relative package path with respect 12089 // to the installation directory. Like say for /data/data/com.test-1.apk 12090 // string com.test-1 is returned. 12091 static String deriveCodePathName(String codePath) { 12092 if (codePath == null) { 12093 return null; 12094 } 12095 final File codeFile = new File(codePath); 12096 final String name = codeFile.getName(); 12097 if (codeFile.isDirectory()) { 12098 return name; 12099 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12100 final int lastDot = name.lastIndexOf('.'); 12101 return name.substring(0, lastDot); 12102 } else { 12103 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12104 return null; 12105 } 12106 } 12107 12108 class PackageInstalledInfo { 12109 String name; 12110 int uid; 12111 // The set of users that originally had this package installed. 12112 int[] origUsers; 12113 // The set of users that now have this package installed. 12114 int[] newUsers; 12115 PackageParser.Package pkg; 12116 int returnCode; 12117 String returnMsg; 12118 PackageRemovedInfo removedInfo; 12119 12120 public void setError(int code, String msg) { 12121 returnCode = code; 12122 returnMsg = msg; 12123 Slog.w(TAG, msg); 12124 } 12125 12126 public void setError(String msg, PackageParserException e) { 12127 returnCode = e.error; 12128 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12129 Slog.w(TAG, msg, e); 12130 } 12131 12132 public void setError(String msg, PackageManagerException e) { 12133 returnCode = e.error; 12134 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12135 Slog.w(TAG, msg, e); 12136 } 12137 12138 // In some error cases we want to convey more info back to the observer 12139 String origPackage; 12140 String origPermission; 12141 } 12142 12143 /* 12144 * Install a non-existing package. 12145 */ 12146 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12147 UserHandle user, String installerPackageName, String volumeUuid, 12148 PackageInstalledInfo res) { 12149 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12150 12151 // Remember this for later, in case we need to rollback this install 12152 String pkgName = pkg.packageName; 12153 12154 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12155 // TODO: b/23350563 12156 final boolean dataDirExists = Environment 12157 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12158 12159 synchronized(mPackages) { 12160 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12161 // A package with the same name is already installed, though 12162 // it has been renamed to an older name. The package we 12163 // are trying to install should be installed as an update to 12164 // the existing one, but that has not been requested, so bail. 12165 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12166 + " without first uninstalling package running as " 12167 + mSettings.mRenamedPackages.get(pkgName)); 12168 return; 12169 } 12170 if (mPackages.containsKey(pkgName)) { 12171 // Don't allow installation over an existing package with the same name. 12172 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12173 + " without first uninstalling."); 12174 return; 12175 } 12176 } 12177 12178 try { 12179 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12180 System.currentTimeMillis(), user); 12181 12182 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12183 // delete the partially installed application. the data directory will have to be 12184 // restored if it was already existing 12185 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12186 // remove package from internal structures. Note that we want deletePackageX to 12187 // delete the package data and cache directories that it created in 12188 // scanPackageLocked, unless those directories existed before we even tried to 12189 // install. 12190 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12191 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12192 res.removedInfo, true); 12193 } 12194 12195 } catch (PackageManagerException e) { 12196 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12197 } 12198 12199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12200 } 12201 12202 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12203 // Can't rotate keys during boot or if sharedUser. 12204 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12205 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12206 return false; 12207 } 12208 // app is using upgradeKeySets; make sure all are valid 12209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12210 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12211 for (int i = 0; i < upgradeKeySets.length; i++) { 12212 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12213 Slog.wtf(TAG, "Package " 12214 + (oldPs.name != null ? oldPs.name : "<null>") 12215 + " contains upgrade-key-set reference to unknown key-set: " 12216 + upgradeKeySets[i] 12217 + " reverting to signatures check."); 12218 return false; 12219 } 12220 } 12221 return true; 12222 } 12223 12224 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12225 // Upgrade keysets are being used. Determine if new package has a superset of the 12226 // required keys. 12227 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12228 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12229 for (int i = 0; i < upgradeKeySets.length; i++) { 12230 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12231 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12232 return true; 12233 } 12234 } 12235 return false; 12236 } 12237 12238 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12239 UserHandle user, String installerPackageName, String volumeUuid, 12240 PackageInstalledInfo res) { 12241 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12242 12243 final PackageParser.Package oldPackage; 12244 final String pkgName = pkg.packageName; 12245 final int[] allUsers; 12246 final boolean[] perUserInstalled; 12247 12248 // First find the old package info and check signatures 12249 synchronized(mPackages) { 12250 oldPackage = mPackages.get(pkgName); 12251 final boolean oldIsEphemeral 12252 = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0); 12253 if (isEphemeral && !oldIsEphemeral) { 12254 // can't downgrade from full to ephemeral 12255 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12256 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12257 return; 12258 } 12259 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12260 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12261 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12262 if(!checkUpgradeKeySetLP(ps, pkg)) { 12263 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12264 "New package not signed by keys specified by upgrade-keysets: " 12265 + pkgName); 12266 return; 12267 } 12268 } else { 12269 // default to original signature matching 12270 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12271 != PackageManager.SIGNATURE_MATCH) { 12272 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12273 "New package has a different signature: " + pkgName); 12274 return; 12275 } 12276 } 12277 12278 // In case of rollback, remember per-user/profile install state 12279 allUsers = sUserManager.getUserIds(); 12280 perUserInstalled = new boolean[allUsers.length]; 12281 for (int i = 0; i < allUsers.length; i++) { 12282 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12283 } 12284 } 12285 12286 boolean sysPkg = (isSystemApp(oldPackage)); 12287 if (sysPkg) { 12288 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12289 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12290 } else { 12291 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12292 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12293 } 12294 } 12295 12296 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12297 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12298 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12299 String volumeUuid, PackageInstalledInfo res) { 12300 String pkgName = deletedPackage.packageName; 12301 boolean deletedPkg = true; 12302 boolean updatedSettings = false; 12303 12304 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12305 + deletedPackage); 12306 long origUpdateTime; 12307 if (pkg.mExtras != null) { 12308 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12309 } else { 12310 origUpdateTime = 0; 12311 } 12312 12313 // First delete the existing package while retaining the data directory 12314 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12315 res.removedInfo, true)) { 12316 // If the existing package wasn't successfully deleted 12317 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12318 deletedPkg = false; 12319 } else { 12320 // Successfully deleted the old package; proceed with replace. 12321 12322 // If deleted package lived in a container, give users a chance to 12323 // relinquish resources before killing. 12324 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12325 if (DEBUG_INSTALL) { 12326 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12327 } 12328 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12329 final ArrayList<String> pkgList = new ArrayList<String>(1); 12330 pkgList.add(deletedPackage.applicationInfo.packageName); 12331 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12332 } 12333 12334 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12335 try { 12336 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12337 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12338 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12339 perUserInstalled, res, user); 12340 updatedSettings = true; 12341 } catch (PackageManagerException e) { 12342 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12343 } 12344 } 12345 12346 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12347 // remove package from internal structures. Note that we want deletePackageX to 12348 // delete the package data and cache directories that it created in 12349 // scanPackageLocked, unless those directories existed before we even tried to 12350 // install. 12351 if(updatedSettings) { 12352 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12353 deletePackageLI( 12354 pkgName, null, true, allUsers, perUserInstalled, 12355 PackageManager.DELETE_KEEP_DATA, 12356 res.removedInfo, true); 12357 } 12358 // Since we failed to install the new package we need to restore the old 12359 // package that we deleted. 12360 if (deletedPkg) { 12361 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12362 File restoreFile = new File(deletedPackage.codePath); 12363 // Parse old package 12364 boolean oldExternal = isExternal(deletedPackage); 12365 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12366 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12367 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12368 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12369 try { 12370 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12371 null); 12372 } catch (PackageManagerException e) { 12373 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12374 + e.getMessage()); 12375 return; 12376 } 12377 // Restore of old package succeeded. Update permissions. 12378 // writer 12379 synchronized (mPackages) { 12380 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12381 UPDATE_PERMISSIONS_ALL); 12382 // can downgrade to reader 12383 mSettings.writeLPr(); 12384 } 12385 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12386 } 12387 } 12388 } 12389 12390 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12391 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12392 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12393 String volumeUuid, PackageInstalledInfo res) { 12394 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12395 + ", old=" + deletedPackage); 12396 boolean disabledSystem = false; 12397 boolean updatedSettings = false; 12398 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12399 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12400 != 0) { 12401 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12402 } 12403 String packageName = deletedPackage.packageName; 12404 if (packageName == null) { 12405 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12406 "Attempt to delete null packageName."); 12407 return; 12408 } 12409 PackageParser.Package oldPkg; 12410 PackageSetting oldPkgSetting; 12411 // reader 12412 synchronized (mPackages) { 12413 oldPkg = mPackages.get(packageName); 12414 oldPkgSetting = mSettings.mPackages.get(packageName); 12415 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12416 (oldPkgSetting == null)) { 12417 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12418 "Couldn't find package:" + packageName + " information"); 12419 return; 12420 } 12421 } 12422 12423 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12424 12425 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12426 res.removedInfo.removedPackage = packageName; 12427 // Remove existing system package 12428 removePackageLI(oldPkgSetting, true); 12429 // writer 12430 synchronized (mPackages) { 12431 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12432 if (!disabledSystem && deletedPackage != null) { 12433 // We didn't need to disable the .apk as a current system package, 12434 // which means we are replacing another update that is already 12435 // installed. We need to make sure to delete the older one's .apk. 12436 res.removedInfo.args = createInstallArgsForExisting(0, 12437 deletedPackage.applicationInfo.getCodePath(), 12438 deletedPackage.applicationInfo.getResourcePath(), 12439 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12440 } else { 12441 res.removedInfo.args = null; 12442 } 12443 } 12444 12445 // Successfully disabled the old package. Now proceed with re-installation 12446 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12447 12448 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12449 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12450 12451 PackageParser.Package newPackage = null; 12452 try { 12453 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12454 if (newPackage.mExtras != null) { 12455 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12456 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12457 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12458 12459 // is the update attempting to change shared user? that isn't going to work... 12460 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12461 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12462 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12463 + " to " + newPkgSetting.sharedUser); 12464 updatedSettings = true; 12465 } 12466 } 12467 12468 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12469 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12470 perUserInstalled, res, user); 12471 updatedSettings = true; 12472 } 12473 12474 } catch (PackageManagerException e) { 12475 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12476 } 12477 12478 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12479 // Re installation failed. Restore old information 12480 // Remove new pkg information 12481 if (newPackage != null) { 12482 removeInstalledPackageLI(newPackage, true); 12483 } 12484 // Add back the old system package 12485 try { 12486 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12487 } catch (PackageManagerException e) { 12488 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12489 } 12490 // Restore the old system information in Settings 12491 synchronized (mPackages) { 12492 if (disabledSystem) { 12493 mSettings.enableSystemPackageLPw(packageName); 12494 } 12495 if (updatedSettings) { 12496 mSettings.setInstallerPackageName(packageName, 12497 oldPkgSetting.installerPackageName); 12498 } 12499 mSettings.writeLPr(); 12500 } 12501 } 12502 } 12503 12504 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12505 // Collect all used permissions in the UID 12506 ArraySet<String> usedPermissions = new ArraySet<>(); 12507 final int packageCount = su.packages.size(); 12508 for (int i = 0; i < packageCount; i++) { 12509 PackageSetting ps = su.packages.valueAt(i); 12510 if (ps.pkg == null) { 12511 continue; 12512 } 12513 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12514 for (int j = 0; j < requestedPermCount; j++) { 12515 String permission = ps.pkg.requestedPermissions.get(j); 12516 BasePermission bp = mSettings.mPermissions.get(permission); 12517 if (bp != null) { 12518 usedPermissions.add(permission); 12519 } 12520 } 12521 } 12522 12523 PermissionsState permissionsState = su.getPermissionsState(); 12524 // Prune install permissions 12525 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12526 final int installPermCount = installPermStates.size(); 12527 for (int i = installPermCount - 1; i >= 0; i--) { 12528 PermissionState permissionState = installPermStates.get(i); 12529 if (!usedPermissions.contains(permissionState.getName())) { 12530 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12531 if (bp != null) { 12532 permissionsState.revokeInstallPermission(bp); 12533 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12534 PackageManager.MASK_PERMISSION_FLAGS, 0); 12535 } 12536 } 12537 } 12538 12539 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12540 12541 // Prune runtime permissions 12542 for (int userId : allUserIds) { 12543 List<PermissionState> runtimePermStates = permissionsState 12544 .getRuntimePermissionStates(userId); 12545 final int runtimePermCount = runtimePermStates.size(); 12546 for (int i = runtimePermCount - 1; i >= 0; i--) { 12547 PermissionState permissionState = runtimePermStates.get(i); 12548 if (!usedPermissions.contains(permissionState.getName())) { 12549 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12550 if (bp != null) { 12551 permissionsState.revokeRuntimePermission(bp, userId); 12552 permissionsState.updatePermissionFlags(bp, userId, 12553 PackageManager.MASK_PERMISSION_FLAGS, 0); 12554 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12555 runtimePermissionChangedUserIds, userId); 12556 } 12557 } 12558 } 12559 } 12560 12561 return runtimePermissionChangedUserIds; 12562 } 12563 12564 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12565 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12566 UserHandle user) { 12567 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12568 12569 String pkgName = newPackage.packageName; 12570 synchronized (mPackages) { 12571 //write settings. the installStatus will be incomplete at this stage. 12572 //note that the new package setting would have already been 12573 //added to mPackages. It hasn't been persisted yet. 12574 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12575 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12576 mSettings.writeLPr(); 12577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12578 } 12579 12580 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12581 synchronized (mPackages) { 12582 updatePermissionsLPw(newPackage.packageName, newPackage, 12583 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12584 ? UPDATE_PERMISSIONS_ALL : 0)); 12585 // For system-bundled packages, we assume that installing an upgraded version 12586 // of the package implies that the user actually wants to run that new code, 12587 // so we enable the package. 12588 PackageSetting ps = mSettings.mPackages.get(pkgName); 12589 if (ps != null) { 12590 if (isSystemApp(newPackage)) { 12591 // NB: implicit assumption that system package upgrades apply to all users 12592 if (DEBUG_INSTALL) { 12593 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12594 } 12595 if (res.origUsers != null) { 12596 for (int userHandle : res.origUsers) { 12597 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12598 userHandle, installerPackageName); 12599 } 12600 } 12601 // Also convey the prior install/uninstall state 12602 if (allUsers != null && perUserInstalled != null) { 12603 for (int i = 0; i < allUsers.length; i++) { 12604 if (DEBUG_INSTALL) { 12605 Slog.d(TAG, " user " + allUsers[i] 12606 + " => " + perUserInstalled[i]); 12607 } 12608 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12609 } 12610 // these install state changes will be persisted in the 12611 // upcoming call to mSettings.writeLPr(). 12612 } 12613 } 12614 // It's implied that when a user requests installation, they want the app to be 12615 // installed and enabled. 12616 int userId = user.getIdentifier(); 12617 if (userId != UserHandle.USER_ALL) { 12618 ps.setInstalled(true, userId); 12619 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12620 } 12621 } 12622 res.name = pkgName; 12623 res.uid = newPackage.applicationInfo.uid; 12624 res.pkg = newPackage; 12625 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12626 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12627 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12628 //to update install status 12629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12630 mSettings.writeLPr(); 12631 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12632 } 12633 12634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12635 } 12636 12637 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12638 try { 12639 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12640 installPackageLI(args, res); 12641 } finally { 12642 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12643 } 12644 } 12645 12646 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12647 final int installFlags = args.installFlags; 12648 final String installerPackageName = args.installerPackageName; 12649 final String volumeUuid = args.volumeUuid; 12650 final File tmpPackageFile = new File(args.getCodePath()); 12651 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12652 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12653 || (args.volumeUuid != null)); 12654 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12655 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12656 boolean replace = false; 12657 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12658 if (args.move != null) { 12659 // moving a complete application; perfom an initial scan on the new install location 12660 scanFlags |= SCAN_INITIAL; 12661 } 12662 // Result object to be returned 12663 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12664 12665 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12666 12667 // Sanity check 12668 if (ephemeral && (forwardLocked || onExternal)) { 12669 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12670 + " external=" + onExternal); 12671 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12672 return; 12673 } 12674 12675 // Retrieve PackageSettings and parse package 12676 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12677 | PackageParser.PARSE_ENFORCE_CODE 12678 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12679 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12680 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0) 12681 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12682 PackageParser pp = new PackageParser(); 12683 pp.setSeparateProcesses(mSeparateProcesses); 12684 pp.setDisplayMetrics(mMetrics); 12685 12686 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12687 final PackageParser.Package pkg; 12688 try { 12689 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12690 } catch (PackageParserException e) { 12691 res.setError("Failed parse during installPackageLI", e); 12692 return; 12693 } finally { 12694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12695 } 12696 12697 // Mark that we have an install time CPU ABI override. 12698 pkg.cpuAbiOverride = args.abiOverride; 12699 12700 String pkgName = res.name = pkg.packageName; 12701 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12702 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12703 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12704 return; 12705 } 12706 } 12707 12708 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12709 try { 12710 pp.collectCertificates(pkg, parseFlags); 12711 } catch (PackageParserException e) { 12712 res.setError("Failed collect during installPackageLI", e); 12713 return; 12714 } finally { 12715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12716 } 12717 12718 /* If the installer passed in a manifest digest, compare it now. */ 12719 if (args.manifestDigest != null) { 12720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12721 try { 12722 pp.collectManifestDigest(pkg); 12723 } catch (PackageParserException e) { 12724 res.setError("Failed collect during installPackageLI", e); 12725 return; 12726 } finally { 12727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12728 } 12729 12730 if (DEBUG_INSTALL) { 12731 final String parsedManifest = pkg.manifestDigest == null ? "null" 12732 : pkg.manifestDigest.toString(); 12733 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12734 + parsedManifest); 12735 } 12736 12737 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12738 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12739 return; 12740 } 12741 } else if (DEBUG_INSTALL) { 12742 final String parsedManifest = pkg.manifestDigest == null 12743 ? "null" : pkg.manifestDigest.toString(); 12744 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12745 } 12746 12747 // Get rid of all references to package scan path via parser. 12748 pp = null; 12749 String oldCodePath = null; 12750 boolean systemApp = false; 12751 synchronized (mPackages) { 12752 // Check if installing already existing package 12753 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12754 String oldName = mSettings.mRenamedPackages.get(pkgName); 12755 if (pkg.mOriginalPackages != null 12756 && pkg.mOriginalPackages.contains(oldName) 12757 && mPackages.containsKey(oldName)) { 12758 // This package is derived from an original package, 12759 // and this device has been updating from that original 12760 // name. We must continue using the original name, so 12761 // rename the new package here. 12762 pkg.setPackageName(oldName); 12763 pkgName = pkg.packageName; 12764 replace = true; 12765 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12766 + oldName + " pkgName=" + pkgName); 12767 } else if (mPackages.containsKey(pkgName)) { 12768 // This package, under its official name, already exists 12769 // on the device; we should replace it. 12770 replace = true; 12771 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12772 } 12773 12774 // Prevent apps opting out from runtime permissions 12775 if (replace) { 12776 PackageParser.Package oldPackage = mPackages.get(pkgName); 12777 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12778 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12779 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12780 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12781 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12782 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12783 + " doesn't support runtime permissions but the old" 12784 + " target SDK " + oldTargetSdk + " does."); 12785 return; 12786 } 12787 } 12788 } 12789 12790 PackageSetting ps = mSettings.mPackages.get(pkgName); 12791 if (ps != null) { 12792 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12793 12794 // Quick sanity check that we're signed correctly if updating; 12795 // we'll check this again later when scanning, but we want to 12796 // bail early here before tripping over redefined permissions. 12797 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12798 if (!checkUpgradeKeySetLP(ps, pkg)) { 12799 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12800 + pkg.packageName + " upgrade keys do not match the " 12801 + "previously installed version"); 12802 return; 12803 } 12804 } else { 12805 try { 12806 verifySignaturesLP(ps, pkg); 12807 } catch (PackageManagerException e) { 12808 res.setError(e.error, e.getMessage()); 12809 return; 12810 } 12811 } 12812 12813 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12814 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12815 systemApp = (ps.pkg.applicationInfo.flags & 12816 ApplicationInfo.FLAG_SYSTEM) != 0; 12817 } 12818 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12819 } 12820 12821 // Check whether the newly-scanned package wants to define an already-defined perm 12822 int N = pkg.permissions.size(); 12823 for (int i = N-1; i >= 0; i--) { 12824 PackageParser.Permission perm = pkg.permissions.get(i); 12825 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12826 if (bp != null) { 12827 // If the defining package is signed with our cert, it's okay. This 12828 // also includes the "updating the same package" case, of course. 12829 // "updating same package" could also involve key-rotation. 12830 final boolean sigsOk; 12831 if (bp.sourcePackage.equals(pkg.packageName) 12832 && (bp.packageSetting instanceof PackageSetting) 12833 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12834 scanFlags))) { 12835 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12836 } else { 12837 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12838 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12839 } 12840 if (!sigsOk) { 12841 // If the owning package is the system itself, we log but allow 12842 // install to proceed; we fail the install on all other permission 12843 // redefinitions. 12844 if (!bp.sourcePackage.equals("android")) { 12845 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12846 + pkg.packageName + " attempting to redeclare permission " 12847 + perm.info.name + " already owned by " + bp.sourcePackage); 12848 res.origPermission = perm.info.name; 12849 res.origPackage = bp.sourcePackage; 12850 return; 12851 } else { 12852 Slog.w(TAG, "Package " + pkg.packageName 12853 + " attempting to redeclare system permission " 12854 + perm.info.name + "; ignoring new declaration"); 12855 pkg.permissions.remove(i); 12856 } 12857 } 12858 } 12859 } 12860 12861 } 12862 12863 if (systemApp) { 12864 if (onExternal) { 12865 // Abort update; system app can't be replaced with app on sdcard 12866 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12867 "Cannot install updates to system apps on sdcard"); 12868 return; 12869 } else if (ephemeral) { 12870 // Abort update; system app can't be replaced with an ephemeral app 12871 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12872 "Cannot update a system app with an ephemeral app"); 12873 return; 12874 } 12875 } 12876 12877 if (args.move != null) { 12878 // We did an in-place move, so dex is ready to roll 12879 scanFlags |= SCAN_NO_DEX; 12880 scanFlags |= SCAN_MOVE; 12881 12882 synchronized (mPackages) { 12883 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12884 if (ps == null) { 12885 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12886 "Missing settings for moved package " + pkgName); 12887 } 12888 12889 // We moved the entire application as-is, so bring over the 12890 // previously derived ABI information. 12891 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12892 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12893 } 12894 12895 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12896 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12897 scanFlags |= SCAN_NO_DEX; 12898 12899 try { 12900 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12901 true /* extract libs */); 12902 } catch (PackageManagerException pme) { 12903 Slog.e(TAG, "Error deriving application ABI", pme); 12904 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12905 return; 12906 } 12907 } 12908 12909 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12910 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12911 return; 12912 } 12913 12914 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12915 12916 if (replace) { 12917 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12918 installerPackageName, volumeUuid, res); 12919 } else { 12920 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12921 args.user, installerPackageName, volumeUuid, res); 12922 } 12923 synchronized (mPackages) { 12924 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12925 if (ps != null) { 12926 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12927 } 12928 } 12929 } 12930 12931 private void startIntentFilterVerifications(int userId, boolean replacing, 12932 PackageParser.Package pkg) { 12933 if (mIntentFilterVerifierComponent == null) { 12934 Slog.w(TAG, "No IntentFilter verification will not be done as " 12935 + "there is no IntentFilterVerifier available!"); 12936 return; 12937 } 12938 12939 final int verifierUid = getPackageUid( 12940 mIntentFilterVerifierComponent.getPackageName(), 12941 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12942 12943 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12944 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12945 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12946 mHandler.sendMessage(msg); 12947 } 12948 12949 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12950 PackageParser.Package pkg) { 12951 int size = pkg.activities.size(); 12952 if (size == 0) { 12953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12954 "No activity, so no need to verify any IntentFilter!"); 12955 return; 12956 } 12957 12958 final boolean hasDomainURLs = hasDomainURLs(pkg); 12959 if (!hasDomainURLs) { 12960 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12961 "No domain URLs, so no need to verify any IntentFilter!"); 12962 return; 12963 } 12964 12965 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12966 + " if any IntentFilter from the " + size 12967 + " Activities needs verification ..."); 12968 12969 int count = 0; 12970 final String packageName = pkg.packageName; 12971 12972 synchronized (mPackages) { 12973 // If this is a new install and we see that we've already run verification for this 12974 // package, we have nothing to do: it means the state was restored from backup. 12975 if (!replacing) { 12976 IntentFilterVerificationInfo ivi = 12977 mSettings.getIntentFilterVerificationLPr(packageName); 12978 if (ivi != null) { 12979 if (DEBUG_DOMAIN_VERIFICATION) { 12980 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12981 + ivi.getStatusString()); 12982 } 12983 return; 12984 } 12985 } 12986 12987 // If any filters need to be verified, then all need to be. 12988 boolean needToVerify = false; 12989 for (PackageParser.Activity a : pkg.activities) { 12990 for (ActivityIntentInfo filter : a.intents) { 12991 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12992 if (DEBUG_DOMAIN_VERIFICATION) { 12993 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12994 } 12995 needToVerify = true; 12996 break; 12997 } 12998 } 12999 } 13000 13001 if (needToVerify) { 13002 final int verificationId = mIntentFilterVerificationToken++; 13003 for (PackageParser.Activity a : pkg.activities) { 13004 for (ActivityIntentInfo filter : a.intents) { 13005 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13006 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13007 "Verification needed for IntentFilter:" + filter.toString()); 13008 mIntentFilterVerifier.addOneIntentFilterVerification( 13009 verifierUid, userId, verificationId, filter, packageName); 13010 count++; 13011 } 13012 } 13013 } 13014 } 13015 } 13016 13017 if (count > 0) { 13018 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13019 + " IntentFilter verification" + (count > 1 ? "s" : "") 13020 + " for userId:" + userId); 13021 mIntentFilterVerifier.startVerifications(userId); 13022 } else { 13023 if (DEBUG_DOMAIN_VERIFICATION) { 13024 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13025 } 13026 } 13027 } 13028 13029 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13030 final ComponentName cn = filter.activity.getComponentName(); 13031 final String packageName = cn.getPackageName(); 13032 13033 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13034 packageName); 13035 if (ivi == null) { 13036 return true; 13037 } 13038 int status = ivi.getStatus(); 13039 switch (status) { 13040 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13041 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13042 return true; 13043 13044 default: 13045 // Nothing to do 13046 return false; 13047 } 13048 } 13049 13050 private static boolean isMultiArch(PackageSetting ps) { 13051 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13052 } 13053 13054 private static boolean isMultiArch(ApplicationInfo info) { 13055 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13056 } 13057 13058 private static boolean isExternal(PackageParser.Package pkg) { 13059 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13060 } 13061 13062 private static boolean isExternal(PackageSetting ps) { 13063 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13064 } 13065 13066 private static boolean isExternal(ApplicationInfo info) { 13067 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13068 } 13069 13070 private static boolean isEphemeral(PackageParser.Package pkg) { 13071 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13072 } 13073 13074 private static boolean isEphemeral(PackageSetting ps) { 13075 return (ps.pkgFlags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13076 } 13077 13078 private static boolean isSystemApp(PackageParser.Package pkg) { 13079 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13080 } 13081 13082 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13083 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13084 } 13085 13086 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13087 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13088 } 13089 13090 private static boolean isSystemApp(PackageSetting ps) { 13091 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13092 } 13093 13094 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13095 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13096 } 13097 13098 private int packageFlagsToInstallFlags(PackageSetting ps) { 13099 int installFlags = 0; 13100 if (isEphemeral(ps)) { 13101 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13102 } 13103 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13104 // This existing package was an external ASEC install when we have 13105 // the external flag without a UUID 13106 installFlags |= PackageManager.INSTALL_EXTERNAL; 13107 } 13108 if (ps.isForwardLocked()) { 13109 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13110 } 13111 return installFlags; 13112 } 13113 13114 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13115 if (isExternal(pkg)) { 13116 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13117 return StorageManager.UUID_PRIMARY_PHYSICAL; 13118 } else { 13119 return pkg.volumeUuid; 13120 } 13121 } else { 13122 return StorageManager.UUID_PRIVATE_INTERNAL; 13123 } 13124 } 13125 13126 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13127 if (isExternal(pkg)) { 13128 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13129 return mSettings.getExternalVersion(); 13130 } else { 13131 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13132 } 13133 } else { 13134 return mSettings.getInternalVersion(); 13135 } 13136 } 13137 13138 private void deleteTempPackageFiles() { 13139 final FilenameFilter filter = new FilenameFilter() { 13140 public boolean accept(File dir, String name) { 13141 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13142 } 13143 }; 13144 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13145 file.delete(); 13146 } 13147 } 13148 13149 @Override 13150 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13151 int flags) { 13152 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13153 flags); 13154 } 13155 13156 @Override 13157 public void deletePackage(final String packageName, 13158 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13159 mContext.enforceCallingOrSelfPermission( 13160 android.Manifest.permission.DELETE_PACKAGES, null); 13161 Preconditions.checkNotNull(packageName); 13162 Preconditions.checkNotNull(observer); 13163 final int uid = Binder.getCallingUid(); 13164 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13165 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13166 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13167 mContext.enforceCallingOrSelfPermission( 13168 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13169 "deletePackage for user " + userId); 13170 } 13171 13172 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13173 try { 13174 observer.onPackageDeleted(packageName, 13175 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13176 } catch (RemoteException re) { 13177 } 13178 return; 13179 } 13180 13181 for (int currentUserId : users) { 13182 if (getBlockUninstallForUser(packageName, currentUserId)) { 13183 try { 13184 observer.onPackageDeleted(packageName, 13185 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13186 } catch (RemoteException re) { 13187 } 13188 return; 13189 } 13190 } 13191 13192 if (DEBUG_REMOVE) { 13193 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13194 } 13195 // Queue up an async operation since the package deletion may take a little while. 13196 mHandler.post(new Runnable() { 13197 public void run() { 13198 mHandler.removeCallbacks(this); 13199 final int returnCode = deletePackageX(packageName, userId, flags); 13200 try { 13201 observer.onPackageDeleted(packageName, returnCode, null); 13202 } catch (RemoteException e) { 13203 Log.i(TAG, "Observer no longer exists."); 13204 } //end catch 13205 } //end run 13206 }); 13207 } 13208 13209 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13210 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13211 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13212 try { 13213 if (dpm != null) { 13214 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13215 /* callingUserOnly =*/ false); 13216 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13217 : deviceOwnerComponentName.getPackageName(); 13218 // Does the package contains the device owner? 13219 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13220 // this check is probably not needed, since DO should be registered as a device 13221 // admin on some user too. (Original bug for this: b/17657954) 13222 if (packageName.equals(deviceOwnerPackageName)) { 13223 return true; 13224 } 13225 // Does it contain a device admin for any user? 13226 int[] users; 13227 if (userId == UserHandle.USER_ALL) { 13228 users = sUserManager.getUserIds(); 13229 } else { 13230 users = new int[]{userId}; 13231 } 13232 for (int i = 0; i < users.length; ++i) { 13233 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13234 return true; 13235 } 13236 } 13237 } 13238 } catch (RemoteException e) { 13239 } 13240 return false; 13241 } 13242 13243 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13244 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13245 } 13246 13247 /** 13248 * This method is an internal method that could be get invoked either 13249 * to delete an installed package or to clean up a failed installation. 13250 * After deleting an installed package, a broadcast is sent to notify any 13251 * listeners that the package has been installed. For cleaning up a failed 13252 * installation, the broadcast is not necessary since the package's 13253 * installation wouldn't have sent the initial broadcast either 13254 * The key steps in deleting a package are 13255 * deleting the package information in internal structures like mPackages, 13256 * deleting the packages base directories through installd 13257 * updating mSettings to reflect current status 13258 * persisting settings for later use 13259 * sending a broadcast if necessary 13260 */ 13261 private int deletePackageX(String packageName, int userId, int flags) { 13262 final PackageRemovedInfo info = new PackageRemovedInfo(); 13263 final boolean res; 13264 13265 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13266 ? UserHandle.ALL : new UserHandle(userId); 13267 13268 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13269 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13270 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13271 } 13272 13273 boolean removedForAllUsers = false; 13274 boolean systemUpdate = false; 13275 13276 // for the uninstall-updates case and restricted profiles, remember the per- 13277 // userhandle installed state 13278 int[] allUsers; 13279 boolean[] perUserInstalled; 13280 synchronized (mPackages) { 13281 PackageSetting ps = mSettings.mPackages.get(packageName); 13282 allUsers = sUserManager.getUserIds(); 13283 perUserInstalled = new boolean[allUsers.length]; 13284 for (int i = 0; i < allUsers.length; i++) { 13285 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13286 } 13287 } 13288 13289 synchronized (mInstallLock) { 13290 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13291 res = deletePackageLI(packageName, removeForUser, 13292 true, allUsers, perUserInstalled, 13293 flags | REMOVE_CHATTY, info, true); 13294 systemUpdate = info.isRemovedPackageSystemUpdate; 13295 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13296 removedForAllUsers = true; 13297 } 13298 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13299 + " removedForAllUsers=" + removedForAllUsers); 13300 } 13301 13302 if (res) { 13303 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13304 13305 // If the removed package was a system update, the old system package 13306 // was re-enabled; we need to broadcast this information 13307 if (systemUpdate) { 13308 Bundle extras = new Bundle(1); 13309 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13310 ? info.removedAppId : info.uid); 13311 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13312 13313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13314 extras, 0, null, null, null); 13315 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13316 extras, 0, null, null, null); 13317 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13318 null, 0, packageName, null, null); 13319 } 13320 } 13321 // Force a gc here. 13322 Runtime.getRuntime().gc(); 13323 // Delete the resources here after sending the broadcast to let 13324 // other processes clean up before deleting resources. 13325 if (info.args != null) { 13326 synchronized (mInstallLock) { 13327 info.args.doPostDeleteLI(true); 13328 } 13329 } 13330 13331 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13332 } 13333 13334 class PackageRemovedInfo { 13335 String removedPackage; 13336 int uid = -1; 13337 int removedAppId = -1; 13338 int[] removedUsers = null; 13339 boolean isRemovedPackageSystemUpdate = false; 13340 // Clean up resources deleted packages. 13341 InstallArgs args = null; 13342 13343 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13344 Bundle extras = new Bundle(1); 13345 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13346 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13347 if (replacing) { 13348 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13349 } 13350 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13351 if (removedPackage != null) { 13352 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13353 extras, 0, null, null, removedUsers); 13354 if (fullRemove && !replacing) { 13355 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13356 extras, 0, null, null, removedUsers); 13357 } 13358 } 13359 if (removedAppId >= 0) { 13360 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13361 removedUsers); 13362 } 13363 } 13364 } 13365 13366 /* 13367 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13368 * flag is not set, the data directory is removed as well. 13369 * make sure this flag is set for partially installed apps. If not its meaningless to 13370 * delete a partially installed application. 13371 */ 13372 private void removePackageDataLI(PackageSetting ps, 13373 int[] allUserHandles, boolean[] perUserInstalled, 13374 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13375 String packageName = ps.name; 13376 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13377 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13378 // Retrieve object to delete permissions for shared user later on 13379 final PackageSetting deletedPs; 13380 // reader 13381 synchronized (mPackages) { 13382 deletedPs = mSettings.mPackages.get(packageName); 13383 if (outInfo != null) { 13384 outInfo.removedPackage = packageName; 13385 outInfo.removedUsers = deletedPs != null 13386 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13387 : null; 13388 } 13389 } 13390 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13391 removeDataDirsLI(ps.volumeUuid, packageName); 13392 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13393 } 13394 // writer 13395 synchronized (mPackages) { 13396 if (deletedPs != null) { 13397 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13398 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13399 clearDefaultBrowserIfNeeded(packageName); 13400 if (outInfo != null) { 13401 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13402 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13403 } 13404 updatePermissionsLPw(deletedPs.name, null, 0); 13405 if (deletedPs.sharedUser != null) { 13406 // Remove permissions associated with package. Since runtime 13407 // permissions are per user we have to kill the removed package 13408 // or packages running under the shared user of the removed 13409 // package if revoking the permissions requested only by the removed 13410 // package is successful and this causes a change in gids. 13411 for (int userId : UserManagerService.getInstance().getUserIds()) { 13412 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13413 userId); 13414 if (userIdToKill == UserHandle.USER_ALL 13415 || userIdToKill >= UserHandle.USER_SYSTEM) { 13416 // If gids changed for this user, kill all affected packages. 13417 mHandler.post(new Runnable() { 13418 @Override 13419 public void run() { 13420 // This has to happen with no lock held. 13421 killApplication(deletedPs.name, deletedPs.appId, 13422 KILL_APP_REASON_GIDS_CHANGED); 13423 } 13424 }); 13425 break; 13426 } 13427 } 13428 } 13429 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13430 } 13431 // make sure to preserve per-user disabled state if this removal was just 13432 // a downgrade of a system app to the factory package 13433 if (allUserHandles != null && perUserInstalled != null) { 13434 if (DEBUG_REMOVE) { 13435 Slog.d(TAG, "Propagating install state across downgrade"); 13436 } 13437 for (int i = 0; i < allUserHandles.length; i++) { 13438 if (DEBUG_REMOVE) { 13439 Slog.d(TAG, " user " + allUserHandles[i] 13440 + " => " + perUserInstalled[i]); 13441 } 13442 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13443 } 13444 } 13445 } 13446 // can downgrade to reader 13447 if (writeSettings) { 13448 // Save settings now 13449 mSettings.writeLPr(); 13450 } 13451 } 13452 if (outInfo != null) { 13453 // A user ID was deleted here. Go through all users and remove it 13454 // from KeyStore. 13455 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13456 } 13457 } 13458 13459 static boolean locationIsPrivileged(File path) { 13460 try { 13461 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13462 .getCanonicalPath(); 13463 return path.getCanonicalPath().startsWith(privilegedAppDir); 13464 } catch (IOException e) { 13465 Slog.e(TAG, "Unable to access code path " + path); 13466 } 13467 return false; 13468 } 13469 13470 /* 13471 * Tries to delete system package. 13472 */ 13473 private boolean deleteSystemPackageLI(PackageSetting newPs, 13474 int[] allUserHandles, boolean[] perUserInstalled, 13475 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13476 final boolean applyUserRestrictions 13477 = (allUserHandles != null) && (perUserInstalled != null); 13478 PackageSetting disabledPs = null; 13479 // Confirm if the system package has been updated 13480 // An updated system app can be deleted. This will also have to restore 13481 // the system pkg from system partition 13482 // reader 13483 synchronized (mPackages) { 13484 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13485 } 13486 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13487 + " disabledPs=" + disabledPs); 13488 if (disabledPs == null) { 13489 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13490 return false; 13491 } else if (DEBUG_REMOVE) { 13492 Slog.d(TAG, "Deleting system pkg from data partition"); 13493 } 13494 if (DEBUG_REMOVE) { 13495 if (applyUserRestrictions) { 13496 Slog.d(TAG, "Remembering install states:"); 13497 for (int i = 0; i < allUserHandles.length; i++) { 13498 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13499 } 13500 } 13501 } 13502 // Delete the updated package 13503 outInfo.isRemovedPackageSystemUpdate = true; 13504 if (disabledPs.versionCode < newPs.versionCode) { 13505 // Delete data for downgrades 13506 flags &= ~PackageManager.DELETE_KEEP_DATA; 13507 } else { 13508 // Preserve data by setting flag 13509 flags |= PackageManager.DELETE_KEEP_DATA; 13510 } 13511 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13512 allUserHandles, perUserInstalled, outInfo, writeSettings); 13513 if (!ret) { 13514 return false; 13515 } 13516 // writer 13517 synchronized (mPackages) { 13518 // Reinstate the old system package 13519 mSettings.enableSystemPackageLPw(newPs.name); 13520 // Remove any native libraries from the upgraded package. 13521 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13522 } 13523 // Install the system package 13524 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13525 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13526 if (locationIsPrivileged(disabledPs.codePath)) { 13527 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13528 } 13529 13530 final PackageParser.Package newPkg; 13531 try { 13532 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13533 } catch (PackageManagerException e) { 13534 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13535 return false; 13536 } 13537 13538 // writer 13539 synchronized (mPackages) { 13540 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13541 13542 // Propagate the permissions state as we do not want to drop on the floor 13543 // runtime permissions. The update permissions method below will take 13544 // care of removing obsolete permissions and grant install permissions. 13545 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13546 updatePermissionsLPw(newPkg.packageName, newPkg, 13547 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13548 13549 if (applyUserRestrictions) { 13550 if (DEBUG_REMOVE) { 13551 Slog.d(TAG, "Propagating install state across reinstall"); 13552 } 13553 for (int i = 0; i < allUserHandles.length; i++) { 13554 if (DEBUG_REMOVE) { 13555 Slog.d(TAG, " user " + allUserHandles[i] 13556 + " => " + perUserInstalled[i]); 13557 } 13558 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13559 13560 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13561 } 13562 // Regardless of writeSettings we need to ensure that this restriction 13563 // state propagation is persisted 13564 mSettings.writeAllUsersPackageRestrictionsLPr(); 13565 } 13566 // can downgrade to reader here 13567 if (writeSettings) { 13568 mSettings.writeLPr(); 13569 } 13570 } 13571 return true; 13572 } 13573 13574 private boolean deleteInstalledPackageLI(PackageSetting ps, 13575 boolean deleteCodeAndResources, int flags, 13576 int[] allUserHandles, boolean[] perUserInstalled, 13577 PackageRemovedInfo outInfo, boolean writeSettings) { 13578 if (outInfo != null) { 13579 outInfo.uid = ps.appId; 13580 } 13581 13582 // Delete package data from internal structures and also remove data if flag is set 13583 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13584 13585 // Delete application code and resources 13586 if (deleteCodeAndResources && (outInfo != null)) { 13587 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13588 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13589 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13590 } 13591 return true; 13592 } 13593 13594 @Override 13595 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13596 int userId) { 13597 mContext.enforceCallingOrSelfPermission( 13598 android.Manifest.permission.DELETE_PACKAGES, null); 13599 synchronized (mPackages) { 13600 PackageSetting ps = mSettings.mPackages.get(packageName); 13601 if (ps == null) { 13602 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13603 return false; 13604 } 13605 if (!ps.getInstalled(userId)) { 13606 // Can't block uninstall for an app that is not installed or enabled. 13607 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13608 return false; 13609 } 13610 ps.setBlockUninstall(blockUninstall, userId); 13611 mSettings.writePackageRestrictionsLPr(userId); 13612 } 13613 return true; 13614 } 13615 13616 @Override 13617 public boolean getBlockUninstallForUser(String packageName, int userId) { 13618 synchronized (mPackages) { 13619 PackageSetting ps = mSettings.mPackages.get(packageName); 13620 if (ps == null) { 13621 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13622 return false; 13623 } 13624 return ps.getBlockUninstall(userId); 13625 } 13626 } 13627 13628 /* 13629 * This method handles package deletion in general 13630 */ 13631 private boolean deletePackageLI(String packageName, UserHandle user, 13632 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13633 int flags, PackageRemovedInfo outInfo, 13634 boolean writeSettings) { 13635 if (packageName == null) { 13636 Slog.w(TAG, "Attempt to delete null packageName."); 13637 return false; 13638 } 13639 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13640 PackageSetting ps; 13641 boolean dataOnly = false; 13642 int removeUser = -1; 13643 int appId = -1; 13644 synchronized (mPackages) { 13645 ps = mSettings.mPackages.get(packageName); 13646 if (ps == null) { 13647 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13648 return false; 13649 } 13650 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13651 && user.getIdentifier() != UserHandle.USER_ALL) { 13652 // The caller is asking that the package only be deleted for a single 13653 // user. To do this, we just mark its uninstalled state and delete 13654 // its data. If this is a system app, we only allow this to happen if 13655 // they have set the special DELETE_SYSTEM_APP which requests different 13656 // semantics than normal for uninstalling system apps. 13657 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13658 final int userId = user.getIdentifier(); 13659 ps.setUserState(userId, 13660 COMPONENT_ENABLED_STATE_DEFAULT, 13661 false, //installed 13662 true, //stopped 13663 true, //notLaunched 13664 false, //hidden 13665 null, null, null, 13666 false, // blockUninstall 13667 ps.readUserState(userId).domainVerificationStatus, 0); 13668 if (!isSystemApp(ps)) { 13669 // Do not uninstall the APK if an app should be cached 13670 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13671 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13672 // Other user still have this package installed, so all 13673 // we need to do is clear this user's data and save that 13674 // it is uninstalled. 13675 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13676 removeUser = user.getIdentifier(); 13677 appId = ps.appId; 13678 scheduleWritePackageRestrictionsLocked(removeUser); 13679 } else { 13680 // We need to set it back to 'installed' so the uninstall 13681 // broadcasts will be sent correctly. 13682 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13683 ps.setInstalled(true, user.getIdentifier()); 13684 } 13685 } else { 13686 // This is a system app, so we assume that the 13687 // other users still have this package installed, so all 13688 // we need to do is clear this user's data and save that 13689 // it is uninstalled. 13690 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13691 removeUser = user.getIdentifier(); 13692 appId = ps.appId; 13693 scheduleWritePackageRestrictionsLocked(removeUser); 13694 } 13695 } 13696 } 13697 13698 if (removeUser >= 0) { 13699 // From above, we determined that we are deleting this only 13700 // for a single user. Continue the work here. 13701 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13702 if (outInfo != null) { 13703 outInfo.removedPackage = packageName; 13704 outInfo.removedAppId = appId; 13705 outInfo.removedUsers = new int[] {removeUser}; 13706 } 13707 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13708 removeKeystoreDataIfNeeded(removeUser, appId); 13709 schedulePackageCleaning(packageName, removeUser, false); 13710 synchronized (mPackages) { 13711 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13712 scheduleWritePackageRestrictionsLocked(removeUser); 13713 } 13714 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13715 } 13716 return true; 13717 } 13718 13719 if (dataOnly) { 13720 // Delete application data first 13721 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13722 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13723 return true; 13724 } 13725 13726 boolean ret = false; 13727 if (isSystemApp(ps)) { 13728 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13729 // When an updated system application is deleted we delete the existing resources as well and 13730 // fall back to existing code in system partition 13731 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13732 flags, outInfo, writeSettings); 13733 } else { 13734 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13735 // Kill application pre-emptively especially for apps on sd. 13736 killApplication(packageName, ps.appId, "uninstall pkg"); 13737 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13738 allUserHandles, perUserInstalled, 13739 outInfo, writeSettings); 13740 } 13741 13742 return ret; 13743 } 13744 13745 private final class ClearStorageConnection implements ServiceConnection { 13746 IMediaContainerService mContainerService; 13747 13748 @Override 13749 public void onServiceConnected(ComponentName name, IBinder service) { 13750 synchronized (this) { 13751 mContainerService = IMediaContainerService.Stub.asInterface(service); 13752 notifyAll(); 13753 } 13754 } 13755 13756 @Override 13757 public void onServiceDisconnected(ComponentName name) { 13758 } 13759 } 13760 13761 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13762 final boolean mounted; 13763 if (Environment.isExternalStorageEmulated()) { 13764 mounted = true; 13765 } else { 13766 final String status = Environment.getExternalStorageState(); 13767 13768 mounted = status.equals(Environment.MEDIA_MOUNTED) 13769 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13770 } 13771 13772 if (!mounted) { 13773 return; 13774 } 13775 13776 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13777 int[] users; 13778 if (userId == UserHandle.USER_ALL) { 13779 users = sUserManager.getUserIds(); 13780 } else { 13781 users = new int[] { userId }; 13782 } 13783 final ClearStorageConnection conn = new ClearStorageConnection(); 13784 if (mContext.bindServiceAsUser( 13785 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13786 try { 13787 for (int curUser : users) { 13788 long timeout = SystemClock.uptimeMillis() + 5000; 13789 synchronized (conn) { 13790 long now = SystemClock.uptimeMillis(); 13791 while (conn.mContainerService == null && now < timeout) { 13792 try { 13793 conn.wait(timeout - now); 13794 } catch (InterruptedException e) { 13795 } 13796 } 13797 } 13798 if (conn.mContainerService == null) { 13799 return; 13800 } 13801 13802 final UserEnvironment userEnv = new UserEnvironment(curUser); 13803 clearDirectory(conn.mContainerService, 13804 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13805 if (allData) { 13806 clearDirectory(conn.mContainerService, 13807 userEnv.buildExternalStorageAppDataDirs(packageName)); 13808 clearDirectory(conn.mContainerService, 13809 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13810 } 13811 } 13812 } finally { 13813 mContext.unbindService(conn); 13814 } 13815 } 13816 } 13817 13818 @Override 13819 public void clearApplicationUserData(final String packageName, 13820 final IPackageDataObserver observer, final int userId) { 13821 mContext.enforceCallingOrSelfPermission( 13822 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13823 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13824 // Queue up an async operation since the package deletion may take a little while. 13825 mHandler.post(new Runnable() { 13826 public void run() { 13827 mHandler.removeCallbacks(this); 13828 final boolean succeeded; 13829 synchronized (mInstallLock) { 13830 succeeded = clearApplicationUserDataLI(packageName, userId); 13831 } 13832 clearExternalStorageDataSync(packageName, userId, true); 13833 if (succeeded) { 13834 // invoke DeviceStorageMonitor's update method to clear any notifications 13835 DeviceStorageMonitorInternal 13836 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13837 if (dsm != null) { 13838 dsm.checkMemory(); 13839 } 13840 } 13841 if(observer != null) { 13842 try { 13843 observer.onRemoveCompleted(packageName, succeeded); 13844 } catch (RemoteException e) { 13845 Log.i(TAG, "Observer no longer exists."); 13846 } 13847 } //end if observer 13848 } //end run 13849 }); 13850 } 13851 13852 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13853 if (packageName == null) { 13854 Slog.w(TAG, "Attempt to delete null packageName."); 13855 return false; 13856 } 13857 13858 // Try finding details about the requested package 13859 PackageParser.Package pkg; 13860 synchronized (mPackages) { 13861 pkg = mPackages.get(packageName); 13862 if (pkg == null) { 13863 final PackageSetting ps = mSettings.mPackages.get(packageName); 13864 if (ps != null) { 13865 pkg = ps.pkg; 13866 } 13867 } 13868 13869 if (pkg == null) { 13870 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13871 return false; 13872 } 13873 13874 PackageSetting ps = (PackageSetting) pkg.mExtras; 13875 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13876 } 13877 13878 // Always delete data directories for package, even if we found no other 13879 // record of app. This helps users recover from UID mismatches without 13880 // resorting to a full data wipe. 13881 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13882 if (retCode < 0) { 13883 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13884 return false; 13885 } 13886 13887 final int appId = pkg.applicationInfo.uid; 13888 removeKeystoreDataIfNeeded(userId, appId); 13889 13890 // Create a native library symlink only if we have native libraries 13891 // and if the native libraries are 32 bit libraries. We do not provide 13892 // this symlink for 64 bit libraries. 13893 if (pkg.applicationInfo.primaryCpuAbi != null && 13894 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13895 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13896 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13897 nativeLibPath, userId) < 0) { 13898 Slog.w(TAG, "Failed linking native library dir"); 13899 return false; 13900 } 13901 } 13902 13903 return true; 13904 } 13905 13906 /** 13907 * Reverts user permission state changes (permissions and flags) in 13908 * all packages for a given user. 13909 * 13910 * @param userId The device user for which to do a reset. 13911 */ 13912 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13913 final int packageCount = mPackages.size(); 13914 for (int i = 0; i < packageCount; i++) { 13915 PackageParser.Package pkg = mPackages.valueAt(i); 13916 PackageSetting ps = (PackageSetting) pkg.mExtras; 13917 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13918 } 13919 } 13920 13921 /** 13922 * Reverts user permission state changes (permissions and flags). 13923 * 13924 * @param ps The package for which to reset. 13925 * @param userId The device user for which to do a reset. 13926 */ 13927 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13928 final PackageSetting ps, final int userId) { 13929 if (ps.pkg == null) { 13930 return; 13931 } 13932 13933 // These are flags that can change base on user actions. 13934 final int userSettableMask = FLAG_PERMISSION_USER_SET 13935 | FLAG_PERMISSION_USER_FIXED 13936 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 13937 | FLAG_PERMISSION_REVIEW_REQUIRED; 13938 13939 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13940 | FLAG_PERMISSION_POLICY_FIXED; 13941 13942 boolean writeInstallPermissions = false; 13943 boolean writeRuntimePermissions = false; 13944 13945 final int permissionCount = ps.pkg.requestedPermissions.size(); 13946 for (int i = 0; i < permissionCount; i++) { 13947 String permission = ps.pkg.requestedPermissions.get(i); 13948 13949 BasePermission bp = mSettings.mPermissions.get(permission); 13950 if (bp == null) { 13951 continue; 13952 } 13953 13954 // If shared user we just reset the state to which only this app contributed. 13955 if (ps.sharedUser != null) { 13956 boolean used = false; 13957 final int packageCount = ps.sharedUser.packages.size(); 13958 for (int j = 0; j < packageCount; j++) { 13959 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13960 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13961 && pkg.pkg.requestedPermissions.contains(permission)) { 13962 used = true; 13963 break; 13964 } 13965 } 13966 if (used) { 13967 continue; 13968 } 13969 } 13970 13971 PermissionsState permissionsState = ps.getPermissionsState(); 13972 13973 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13974 13975 // Always clear the user settable flags. 13976 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13977 bp.name) != null; 13978 // If permission review is enabled and this is a legacy app, mark the 13979 // permission as requiring a review as this is the initial state. 13980 int flags = 0; 13981 if (Build.PERMISSIONS_REVIEW_REQUIRED 13982 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 13983 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 13984 } 13985 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 13986 if (hasInstallState) { 13987 writeInstallPermissions = true; 13988 } else { 13989 writeRuntimePermissions = true; 13990 } 13991 } 13992 13993 // Below is only runtime permission handling. 13994 if (!bp.isRuntime()) { 13995 continue; 13996 } 13997 13998 // Never clobber system or policy. 13999 if ((oldFlags & policyOrSystemFlags) != 0) { 14000 continue; 14001 } 14002 14003 // If this permission was granted by default, make sure it is. 14004 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14005 if (permissionsState.grantRuntimePermission(bp, userId) 14006 != PERMISSION_OPERATION_FAILURE) { 14007 writeRuntimePermissions = true; 14008 } 14009 // If permission review is enabled the permissions for a legacy apps 14010 // are represented as constantly granted runtime ones, so don't revoke. 14011 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14012 // Otherwise, reset the permission. 14013 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14014 switch (revokeResult) { 14015 case PERMISSION_OPERATION_SUCCESS: { 14016 writeRuntimePermissions = true; 14017 } break; 14018 14019 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14020 writeRuntimePermissions = true; 14021 final int appId = ps.appId; 14022 mHandler.post(new Runnable() { 14023 @Override 14024 public void run() { 14025 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14026 } 14027 }); 14028 } break; 14029 } 14030 } 14031 } 14032 14033 // Synchronously write as we are taking permissions away. 14034 if (writeRuntimePermissions) { 14035 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14036 } 14037 14038 // Synchronously write as we are taking permissions away. 14039 if (writeInstallPermissions) { 14040 mSettings.writeLPr(); 14041 } 14042 } 14043 14044 /** 14045 * Remove entries from the keystore daemon. Will only remove it if the 14046 * {@code appId} is valid. 14047 */ 14048 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14049 if (appId < 0) { 14050 return; 14051 } 14052 14053 final KeyStore keyStore = KeyStore.getInstance(); 14054 if (keyStore != null) { 14055 if (userId == UserHandle.USER_ALL) { 14056 for (final int individual : sUserManager.getUserIds()) { 14057 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14058 } 14059 } else { 14060 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14061 } 14062 } else { 14063 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14064 } 14065 } 14066 14067 @Override 14068 public void deleteApplicationCacheFiles(final String packageName, 14069 final IPackageDataObserver observer) { 14070 mContext.enforceCallingOrSelfPermission( 14071 android.Manifest.permission.DELETE_CACHE_FILES, null); 14072 // Queue up an async operation since the package deletion may take a little while. 14073 final int userId = UserHandle.getCallingUserId(); 14074 mHandler.post(new Runnable() { 14075 public void run() { 14076 mHandler.removeCallbacks(this); 14077 final boolean succeded; 14078 synchronized (mInstallLock) { 14079 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14080 } 14081 clearExternalStorageDataSync(packageName, userId, false); 14082 if (observer != null) { 14083 try { 14084 observer.onRemoveCompleted(packageName, succeded); 14085 } catch (RemoteException e) { 14086 Log.i(TAG, "Observer no longer exists."); 14087 } 14088 } //end if observer 14089 } //end run 14090 }); 14091 } 14092 14093 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14094 if (packageName == null) { 14095 Slog.w(TAG, "Attempt to delete null packageName."); 14096 return false; 14097 } 14098 PackageParser.Package p; 14099 synchronized (mPackages) { 14100 p = mPackages.get(packageName); 14101 } 14102 if (p == null) { 14103 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14104 return false; 14105 } 14106 final ApplicationInfo applicationInfo = p.applicationInfo; 14107 if (applicationInfo == null) { 14108 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14109 return false; 14110 } 14111 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14112 if (retCode < 0) { 14113 Slog.w(TAG, "Couldn't remove cache files for package: " 14114 + packageName + " u" + userId); 14115 return false; 14116 } 14117 return true; 14118 } 14119 14120 @Override 14121 public void getPackageSizeInfo(final String packageName, int userHandle, 14122 final IPackageStatsObserver observer) { 14123 mContext.enforceCallingOrSelfPermission( 14124 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14125 if (packageName == null) { 14126 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14127 } 14128 14129 PackageStats stats = new PackageStats(packageName, userHandle); 14130 14131 /* 14132 * Queue up an async operation since the package measurement may take a 14133 * little while. 14134 */ 14135 Message msg = mHandler.obtainMessage(INIT_COPY); 14136 msg.obj = new MeasureParams(stats, observer); 14137 mHandler.sendMessage(msg); 14138 } 14139 14140 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14141 PackageStats pStats) { 14142 if (packageName == null) { 14143 Slog.w(TAG, "Attempt to get size of null packageName."); 14144 return false; 14145 } 14146 PackageParser.Package p; 14147 boolean dataOnly = false; 14148 String libDirRoot = null; 14149 String asecPath = null; 14150 PackageSetting ps = null; 14151 synchronized (mPackages) { 14152 p = mPackages.get(packageName); 14153 ps = mSettings.mPackages.get(packageName); 14154 if(p == null) { 14155 dataOnly = true; 14156 if((ps == null) || (ps.pkg == null)) { 14157 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14158 return false; 14159 } 14160 p = ps.pkg; 14161 } 14162 if (ps != null) { 14163 libDirRoot = ps.legacyNativeLibraryPathString; 14164 } 14165 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14166 final long token = Binder.clearCallingIdentity(); 14167 try { 14168 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14169 if (secureContainerId != null) { 14170 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14171 } 14172 } finally { 14173 Binder.restoreCallingIdentity(token); 14174 } 14175 } 14176 } 14177 String publicSrcDir = null; 14178 if(!dataOnly) { 14179 final ApplicationInfo applicationInfo = p.applicationInfo; 14180 if (applicationInfo == null) { 14181 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14182 return false; 14183 } 14184 if (p.isForwardLocked()) { 14185 publicSrcDir = applicationInfo.getBaseResourcePath(); 14186 } 14187 } 14188 // TODO: extend to measure size of split APKs 14189 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14190 // not just the first level. 14191 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14192 // just the primary. 14193 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14194 14195 String apkPath; 14196 File packageDir = new File(p.codePath); 14197 14198 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14199 apkPath = packageDir.getAbsolutePath(); 14200 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14201 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14202 libDirRoot = null; 14203 } 14204 } else { 14205 apkPath = p.baseCodePath; 14206 } 14207 14208 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14209 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14210 if (res < 0) { 14211 return false; 14212 } 14213 14214 // Fix-up for forward-locked applications in ASEC containers. 14215 if (!isExternal(p)) { 14216 pStats.codeSize += pStats.externalCodeSize; 14217 pStats.externalCodeSize = 0L; 14218 } 14219 14220 return true; 14221 } 14222 14223 14224 @Override 14225 public void addPackageToPreferred(String packageName) { 14226 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14227 } 14228 14229 @Override 14230 public void removePackageFromPreferred(String packageName) { 14231 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14232 } 14233 14234 @Override 14235 public List<PackageInfo> getPreferredPackages(int flags) { 14236 return new ArrayList<PackageInfo>(); 14237 } 14238 14239 private int getUidTargetSdkVersionLockedLPr(int uid) { 14240 Object obj = mSettings.getUserIdLPr(uid); 14241 if (obj instanceof SharedUserSetting) { 14242 final SharedUserSetting sus = (SharedUserSetting) obj; 14243 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14244 final Iterator<PackageSetting> it = sus.packages.iterator(); 14245 while (it.hasNext()) { 14246 final PackageSetting ps = it.next(); 14247 if (ps.pkg != null) { 14248 int v = ps.pkg.applicationInfo.targetSdkVersion; 14249 if (v < vers) vers = v; 14250 } 14251 } 14252 return vers; 14253 } else if (obj instanceof PackageSetting) { 14254 final PackageSetting ps = (PackageSetting) obj; 14255 if (ps.pkg != null) { 14256 return ps.pkg.applicationInfo.targetSdkVersion; 14257 } 14258 } 14259 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14260 } 14261 14262 @Override 14263 public void addPreferredActivity(IntentFilter filter, int match, 14264 ComponentName[] set, ComponentName activity, int userId) { 14265 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14266 "Adding preferred"); 14267 } 14268 14269 private void addPreferredActivityInternal(IntentFilter filter, int match, 14270 ComponentName[] set, ComponentName activity, boolean always, int userId, 14271 String opname) { 14272 // writer 14273 int callingUid = Binder.getCallingUid(); 14274 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14275 if (filter.countActions() == 0) { 14276 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14277 return; 14278 } 14279 synchronized (mPackages) { 14280 if (mContext.checkCallingOrSelfPermission( 14281 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14282 != PackageManager.PERMISSION_GRANTED) { 14283 if (getUidTargetSdkVersionLockedLPr(callingUid) 14284 < Build.VERSION_CODES.FROYO) { 14285 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14286 + callingUid); 14287 return; 14288 } 14289 mContext.enforceCallingOrSelfPermission( 14290 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14291 } 14292 14293 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14294 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14295 + userId + ":"); 14296 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14297 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14298 scheduleWritePackageRestrictionsLocked(userId); 14299 } 14300 } 14301 14302 @Override 14303 public void replacePreferredActivity(IntentFilter filter, int match, 14304 ComponentName[] set, ComponentName activity, int userId) { 14305 if (filter.countActions() != 1) { 14306 throw new IllegalArgumentException( 14307 "replacePreferredActivity expects filter to have only 1 action."); 14308 } 14309 if (filter.countDataAuthorities() != 0 14310 || filter.countDataPaths() != 0 14311 || filter.countDataSchemes() > 1 14312 || filter.countDataTypes() != 0) { 14313 throw new IllegalArgumentException( 14314 "replacePreferredActivity expects filter to have no data authorities, " + 14315 "paths, or types; and at most one scheme."); 14316 } 14317 14318 final int callingUid = Binder.getCallingUid(); 14319 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14320 synchronized (mPackages) { 14321 if (mContext.checkCallingOrSelfPermission( 14322 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14323 != PackageManager.PERMISSION_GRANTED) { 14324 if (getUidTargetSdkVersionLockedLPr(callingUid) 14325 < Build.VERSION_CODES.FROYO) { 14326 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14327 + Binder.getCallingUid()); 14328 return; 14329 } 14330 mContext.enforceCallingOrSelfPermission( 14331 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14332 } 14333 14334 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14335 if (pir != null) { 14336 // Get all of the existing entries that exactly match this filter. 14337 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14338 if (existing != null && existing.size() == 1) { 14339 PreferredActivity cur = existing.get(0); 14340 if (DEBUG_PREFERRED) { 14341 Slog.i(TAG, "Checking replace of preferred:"); 14342 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14343 if (!cur.mPref.mAlways) { 14344 Slog.i(TAG, " -- CUR; not mAlways!"); 14345 } else { 14346 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14347 Slog.i(TAG, " -- CUR: mSet=" 14348 + Arrays.toString(cur.mPref.mSetComponents)); 14349 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14350 Slog.i(TAG, " -- NEW: mMatch=" 14351 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14352 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14353 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14354 } 14355 } 14356 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14357 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14358 && cur.mPref.sameSet(set)) { 14359 // Setting the preferred activity to what it happens to be already 14360 if (DEBUG_PREFERRED) { 14361 Slog.i(TAG, "Replacing with same preferred activity " 14362 + cur.mPref.mShortComponent + " for user " 14363 + userId + ":"); 14364 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14365 } 14366 return; 14367 } 14368 } 14369 14370 if (existing != null) { 14371 if (DEBUG_PREFERRED) { 14372 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14373 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14374 } 14375 for (int i = 0; i < existing.size(); i++) { 14376 PreferredActivity pa = existing.get(i); 14377 if (DEBUG_PREFERRED) { 14378 Slog.i(TAG, "Removing existing preferred activity " 14379 + pa.mPref.mComponent + ":"); 14380 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14381 } 14382 pir.removeFilter(pa); 14383 } 14384 } 14385 } 14386 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14387 "Replacing preferred"); 14388 } 14389 } 14390 14391 @Override 14392 public void clearPackagePreferredActivities(String packageName) { 14393 final int uid = Binder.getCallingUid(); 14394 // writer 14395 synchronized (mPackages) { 14396 PackageParser.Package pkg = mPackages.get(packageName); 14397 if (pkg == null || pkg.applicationInfo.uid != uid) { 14398 if (mContext.checkCallingOrSelfPermission( 14399 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14400 != PackageManager.PERMISSION_GRANTED) { 14401 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14402 < Build.VERSION_CODES.FROYO) { 14403 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14404 + Binder.getCallingUid()); 14405 return; 14406 } 14407 mContext.enforceCallingOrSelfPermission( 14408 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14409 } 14410 } 14411 14412 int user = UserHandle.getCallingUserId(); 14413 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14414 scheduleWritePackageRestrictionsLocked(user); 14415 } 14416 } 14417 } 14418 14419 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14420 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14421 ArrayList<PreferredActivity> removed = null; 14422 boolean changed = false; 14423 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14424 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14425 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14426 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14427 continue; 14428 } 14429 Iterator<PreferredActivity> it = pir.filterIterator(); 14430 while (it.hasNext()) { 14431 PreferredActivity pa = it.next(); 14432 // Mark entry for removal only if it matches the package name 14433 // and the entry is of type "always". 14434 if (packageName == null || 14435 (pa.mPref.mComponent.getPackageName().equals(packageName) 14436 && pa.mPref.mAlways)) { 14437 if (removed == null) { 14438 removed = new ArrayList<PreferredActivity>(); 14439 } 14440 removed.add(pa); 14441 } 14442 } 14443 if (removed != null) { 14444 for (int j=0; j<removed.size(); j++) { 14445 PreferredActivity pa = removed.get(j); 14446 pir.removeFilter(pa); 14447 } 14448 changed = true; 14449 } 14450 } 14451 return changed; 14452 } 14453 14454 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14455 private void clearIntentFilterVerificationsLPw(int userId) { 14456 final int packageCount = mPackages.size(); 14457 for (int i = 0; i < packageCount; i++) { 14458 PackageParser.Package pkg = mPackages.valueAt(i); 14459 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14460 } 14461 } 14462 14463 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14464 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14465 if (userId == UserHandle.USER_ALL) { 14466 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14467 sUserManager.getUserIds())) { 14468 for (int oneUserId : sUserManager.getUserIds()) { 14469 scheduleWritePackageRestrictionsLocked(oneUserId); 14470 } 14471 } 14472 } else { 14473 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14474 scheduleWritePackageRestrictionsLocked(userId); 14475 } 14476 } 14477 } 14478 14479 void clearDefaultBrowserIfNeeded(String packageName) { 14480 for (int oneUserId : sUserManager.getUserIds()) { 14481 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14482 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14483 if (packageName.equals(defaultBrowserPackageName)) { 14484 setDefaultBrowserPackageName(null, oneUserId); 14485 } 14486 } 14487 } 14488 14489 @Override 14490 public void resetApplicationPreferences(int userId) { 14491 mContext.enforceCallingOrSelfPermission( 14492 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14493 // writer 14494 synchronized (mPackages) { 14495 final long identity = Binder.clearCallingIdentity(); 14496 try { 14497 clearPackagePreferredActivitiesLPw(null, userId); 14498 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14499 // TODO: We have to reset the default SMS and Phone. This requires 14500 // significant refactoring to keep all default apps in the package 14501 // manager (cleaner but more work) or have the services provide 14502 // callbacks to the package manager to request a default app reset. 14503 applyFactoryDefaultBrowserLPw(userId); 14504 clearIntentFilterVerificationsLPw(userId); 14505 primeDomainVerificationsLPw(userId); 14506 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14507 scheduleWritePackageRestrictionsLocked(userId); 14508 } finally { 14509 Binder.restoreCallingIdentity(identity); 14510 } 14511 } 14512 } 14513 14514 @Override 14515 public int getPreferredActivities(List<IntentFilter> outFilters, 14516 List<ComponentName> outActivities, String packageName) { 14517 14518 int num = 0; 14519 final int userId = UserHandle.getCallingUserId(); 14520 // reader 14521 synchronized (mPackages) { 14522 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14523 if (pir != null) { 14524 final Iterator<PreferredActivity> it = pir.filterIterator(); 14525 while (it.hasNext()) { 14526 final PreferredActivity pa = it.next(); 14527 if (packageName == null 14528 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14529 && pa.mPref.mAlways)) { 14530 if (outFilters != null) { 14531 outFilters.add(new IntentFilter(pa)); 14532 } 14533 if (outActivities != null) { 14534 outActivities.add(pa.mPref.mComponent); 14535 } 14536 } 14537 } 14538 } 14539 } 14540 14541 return num; 14542 } 14543 14544 @Override 14545 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14546 int userId) { 14547 int callingUid = Binder.getCallingUid(); 14548 if (callingUid != Process.SYSTEM_UID) { 14549 throw new SecurityException( 14550 "addPersistentPreferredActivity can only be run by the system"); 14551 } 14552 if (filter.countActions() == 0) { 14553 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14554 return; 14555 } 14556 synchronized (mPackages) { 14557 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14558 " :"); 14559 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14560 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14561 new PersistentPreferredActivity(filter, activity)); 14562 scheduleWritePackageRestrictionsLocked(userId); 14563 } 14564 } 14565 14566 @Override 14567 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14568 int callingUid = Binder.getCallingUid(); 14569 if (callingUid != Process.SYSTEM_UID) { 14570 throw new SecurityException( 14571 "clearPackagePersistentPreferredActivities can only be run by the system"); 14572 } 14573 ArrayList<PersistentPreferredActivity> removed = null; 14574 boolean changed = false; 14575 synchronized (mPackages) { 14576 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14577 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14578 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14579 .valueAt(i); 14580 if (userId != thisUserId) { 14581 continue; 14582 } 14583 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14584 while (it.hasNext()) { 14585 PersistentPreferredActivity ppa = it.next(); 14586 // Mark entry for removal only if it matches the package name. 14587 if (ppa.mComponent.getPackageName().equals(packageName)) { 14588 if (removed == null) { 14589 removed = new ArrayList<PersistentPreferredActivity>(); 14590 } 14591 removed.add(ppa); 14592 } 14593 } 14594 if (removed != null) { 14595 for (int j=0; j<removed.size(); j++) { 14596 PersistentPreferredActivity ppa = removed.get(j); 14597 ppir.removeFilter(ppa); 14598 } 14599 changed = true; 14600 } 14601 } 14602 14603 if (changed) { 14604 scheduleWritePackageRestrictionsLocked(userId); 14605 } 14606 } 14607 } 14608 14609 /** 14610 * Common machinery for picking apart a restored XML blob and passing 14611 * it to a caller-supplied functor to be applied to the running system. 14612 */ 14613 private void restoreFromXml(XmlPullParser parser, int userId, 14614 String expectedStartTag, BlobXmlRestorer functor) 14615 throws IOException, XmlPullParserException { 14616 int type; 14617 while ((type = parser.next()) != XmlPullParser.START_TAG 14618 && type != XmlPullParser.END_DOCUMENT) { 14619 } 14620 if (type != XmlPullParser.START_TAG) { 14621 // oops didn't find a start tag?! 14622 if (DEBUG_BACKUP) { 14623 Slog.e(TAG, "Didn't find start tag during restore"); 14624 } 14625 return; 14626 } 14627 14628 // this is supposed to be TAG_PREFERRED_BACKUP 14629 if (!expectedStartTag.equals(parser.getName())) { 14630 if (DEBUG_BACKUP) { 14631 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14632 } 14633 return; 14634 } 14635 14636 // skip interfering stuff, then we're aligned with the backing implementation 14637 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14638 functor.apply(parser, userId); 14639 } 14640 14641 private interface BlobXmlRestorer { 14642 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14643 } 14644 14645 /** 14646 * Non-Binder method, support for the backup/restore mechanism: write the 14647 * full set of preferred activities in its canonical XML format. Returns the 14648 * XML output as a byte array, or null if there is none. 14649 */ 14650 @Override 14651 public byte[] getPreferredActivityBackup(int userId) { 14652 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14653 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14654 } 14655 14656 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14657 try { 14658 final XmlSerializer serializer = new FastXmlSerializer(); 14659 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14660 serializer.startDocument(null, true); 14661 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14662 14663 synchronized (mPackages) { 14664 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14665 } 14666 14667 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14668 serializer.endDocument(); 14669 serializer.flush(); 14670 } catch (Exception e) { 14671 if (DEBUG_BACKUP) { 14672 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14673 } 14674 return null; 14675 } 14676 14677 return dataStream.toByteArray(); 14678 } 14679 14680 @Override 14681 public void restorePreferredActivities(byte[] backup, int userId) { 14682 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14683 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14684 } 14685 14686 try { 14687 final XmlPullParser parser = Xml.newPullParser(); 14688 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14689 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14690 new BlobXmlRestorer() { 14691 @Override 14692 public void apply(XmlPullParser parser, int userId) 14693 throws XmlPullParserException, IOException { 14694 synchronized (mPackages) { 14695 mSettings.readPreferredActivitiesLPw(parser, userId); 14696 } 14697 } 14698 } ); 14699 } catch (Exception e) { 14700 if (DEBUG_BACKUP) { 14701 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14702 } 14703 } 14704 } 14705 14706 /** 14707 * Non-Binder method, support for the backup/restore mechanism: write the 14708 * default browser (etc) settings in its canonical XML format. Returns the default 14709 * browser XML representation as a byte array, or null if there is none. 14710 */ 14711 @Override 14712 public byte[] getDefaultAppsBackup(int userId) { 14713 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14714 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14715 } 14716 14717 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14718 try { 14719 final XmlSerializer serializer = new FastXmlSerializer(); 14720 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14721 serializer.startDocument(null, true); 14722 serializer.startTag(null, TAG_DEFAULT_APPS); 14723 14724 synchronized (mPackages) { 14725 mSettings.writeDefaultAppsLPr(serializer, userId); 14726 } 14727 14728 serializer.endTag(null, TAG_DEFAULT_APPS); 14729 serializer.endDocument(); 14730 serializer.flush(); 14731 } catch (Exception e) { 14732 if (DEBUG_BACKUP) { 14733 Slog.e(TAG, "Unable to write default apps for backup", e); 14734 } 14735 return null; 14736 } 14737 14738 return dataStream.toByteArray(); 14739 } 14740 14741 @Override 14742 public void restoreDefaultApps(byte[] backup, int userId) { 14743 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14744 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14745 } 14746 14747 try { 14748 final XmlPullParser parser = Xml.newPullParser(); 14749 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14750 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14751 new BlobXmlRestorer() { 14752 @Override 14753 public void apply(XmlPullParser parser, int userId) 14754 throws XmlPullParserException, IOException { 14755 synchronized (mPackages) { 14756 mSettings.readDefaultAppsLPw(parser, userId); 14757 } 14758 } 14759 } ); 14760 } catch (Exception e) { 14761 if (DEBUG_BACKUP) { 14762 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14763 } 14764 } 14765 } 14766 14767 @Override 14768 public byte[] getIntentFilterVerificationBackup(int userId) { 14769 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14770 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14771 } 14772 14773 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14774 try { 14775 final XmlSerializer serializer = new FastXmlSerializer(); 14776 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14777 serializer.startDocument(null, true); 14778 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14779 14780 synchronized (mPackages) { 14781 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14782 } 14783 14784 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14785 serializer.endDocument(); 14786 serializer.flush(); 14787 } catch (Exception e) { 14788 if (DEBUG_BACKUP) { 14789 Slog.e(TAG, "Unable to write default apps for backup", e); 14790 } 14791 return null; 14792 } 14793 14794 return dataStream.toByteArray(); 14795 } 14796 14797 @Override 14798 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14799 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14800 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14801 } 14802 14803 try { 14804 final XmlPullParser parser = Xml.newPullParser(); 14805 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14806 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14807 new BlobXmlRestorer() { 14808 @Override 14809 public void apply(XmlPullParser parser, int userId) 14810 throws XmlPullParserException, IOException { 14811 synchronized (mPackages) { 14812 mSettings.readAllDomainVerificationsLPr(parser, userId); 14813 mSettings.writeLPr(); 14814 } 14815 } 14816 } ); 14817 } catch (Exception e) { 14818 if (DEBUG_BACKUP) { 14819 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14820 } 14821 } 14822 } 14823 14824 @Override 14825 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14826 int sourceUserId, int targetUserId, int flags) { 14827 mContext.enforceCallingOrSelfPermission( 14828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14829 int callingUid = Binder.getCallingUid(); 14830 enforceOwnerRights(ownerPackage, callingUid); 14831 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14832 if (intentFilter.countActions() == 0) { 14833 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14834 return; 14835 } 14836 synchronized (mPackages) { 14837 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14838 ownerPackage, targetUserId, flags); 14839 CrossProfileIntentResolver resolver = 14840 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14841 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14842 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14843 if (existing != null) { 14844 int size = existing.size(); 14845 for (int i = 0; i < size; i++) { 14846 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14847 return; 14848 } 14849 } 14850 } 14851 resolver.addFilter(newFilter); 14852 scheduleWritePackageRestrictionsLocked(sourceUserId); 14853 } 14854 } 14855 14856 @Override 14857 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14858 mContext.enforceCallingOrSelfPermission( 14859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14860 int callingUid = Binder.getCallingUid(); 14861 enforceOwnerRights(ownerPackage, callingUid); 14862 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14863 synchronized (mPackages) { 14864 CrossProfileIntentResolver resolver = 14865 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14866 ArraySet<CrossProfileIntentFilter> set = 14867 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14868 for (CrossProfileIntentFilter filter : set) { 14869 if (filter.getOwnerPackage().equals(ownerPackage)) { 14870 resolver.removeFilter(filter); 14871 } 14872 } 14873 scheduleWritePackageRestrictionsLocked(sourceUserId); 14874 } 14875 } 14876 14877 // Enforcing that callingUid is owning pkg on userId 14878 private void enforceOwnerRights(String pkg, int callingUid) { 14879 // The system owns everything. 14880 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14881 return; 14882 } 14883 int callingUserId = UserHandle.getUserId(callingUid); 14884 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14885 if (pi == null) { 14886 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14887 + callingUserId); 14888 } 14889 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14890 throw new SecurityException("Calling uid " + callingUid 14891 + " does not own package " + pkg); 14892 } 14893 } 14894 14895 @Override 14896 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14897 Intent intent = new Intent(Intent.ACTION_MAIN); 14898 intent.addCategory(Intent.CATEGORY_HOME); 14899 14900 final int callingUserId = UserHandle.getCallingUserId(); 14901 List<ResolveInfo> list = queryIntentActivities(intent, null, 14902 PackageManager.GET_META_DATA, callingUserId); 14903 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14904 true, false, false, callingUserId); 14905 14906 allHomeCandidates.clear(); 14907 if (list != null) { 14908 for (ResolveInfo ri : list) { 14909 allHomeCandidates.add(ri); 14910 } 14911 } 14912 return (preferred == null || preferred.activityInfo == null) 14913 ? null 14914 : new ComponentName(preferred.activityInfo.packageName, 14915 preferred.activityInfo.name); 14916 } 14917 14918 @Override 14919 public void setApplicationEnabledSetting(String appPackageName, 14920 int newState, int flags, int userId, String callingPackage) { 14921 if (!sUserManager.exists(userId)) return; 14922 if (callingPackage == null) { 14923 callingPackage = Integer.toString(Binder.getCallingUid()); 14924 } 14925 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14926 } 14927 14928 @Override 14929 public void setComponentEnabledSetting(ComponentName componentName, 14930 int newState, int flags, int userId) { 14931 if (!sUserManager.exists(userId)) return; 14932 setEnabledSetting(componentName.getPackageName(), 14933 componentName.getClassName(), newState, flags, userId, null); 14934 } 14935 14936 private void setEnabledSetting(final String packageName, String className, int newState, 14937 final int flags, int userId, String callingPackage) { 14938 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14939 || newState == COMPONENT_ENABLED_STATE_ENABLED 14940 || newState == COMPONENT_ENABLED_STATE_DISABLED 14941 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14942 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14943 throw new IllegalArgumentException("Invalid new component state: " 14944 + newState); 14945 } 14946 PackageSetting pkgSetting; 14947 final int uid = Binder.getCallingUid(); 14948 final int permission = mContext.checkCallingOrSelfPermission( 14949 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14950 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14951 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14952 boolean sendNow = false; 14953 boolean isApp = (className == null); 14954 String componentName = isApp ? packageName : className; 14955 int packageUid = -1; 14956 ArrayList<String> components; 14957 14958 // writer 14959 synchronized (mPackages) { 14960 pkgSetting = mSettings.mPackages.get(packageName); 14961 if (pkgSetting == null) { 14962 if (className == null) { 14963 throw new IllegalArgumentException( 14964 "Unknown package: " + packageName); 14965 } 14966 throw new IllegalArgumentException( 14967 "Unknown component: " + packageName 14968 + "/" + className); 14969 } 14970 // Allow root and verify that userId is not being specified by a different user 14971 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14972 throw new SecurityException( 14973 "Permission Denial: attempt to change component state from pid=" 14974 + Binder.getCallingPid() 14975 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14976 } 14977 if (className == null) { 14978 // We're dealing with an application/package level state change 14979 if (pkgSetting.getEnabled(userId) == newState) { 14980 // Nothing to do 14981 return; 14982 } 14983 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14984 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14985 // Don't care about who enables an app. 14986 callingPackage = null; 14987 } 14988 pkgSetting.setEnabled(newState, userId, callingPackage); 14989 // pkgSetting.pkg.mSetEnabled = newState; 14990 } else { 14991 // We're dealing with a component level state change 14992 // First, verify that this is a valid class name. 14993 PackageParser.Package pkg = pkgSetting.pkg; 14994 if (pkg == null || !pkg.hasComponentClassName(className)) { 14995 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14996 throw new IllegalArgumentException("Component class " + className 14997 + " does not exist in " + packageName); 14998 } else { 14999 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15000 + className + " does not exist in " + packageName); 15001 } 15002 } 15003 switch (newState) { 15004 case COMPONENT_ENABLED_STATE_ENABLED: 15005 if (!pkgSetting.enableComponentLPw(className, userId)) { 15006 return; 15007 } 15008 break; 15009 case COMPONENT_ENABLED_STATE_DISABLED: 15010 if (!pkgSetting.disableComponentLPw(className, userId)) { 15011 return; 15012 } 15013 break; 15014 case COMPONENT_ENABLED_STATE_DEFAULT: 15015 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15016 return; 15017 } 15018 break; 15019 default: 15020 Slog.e(TAG, "Invalid new component state: " + newState); 15021 return; 15022 } 15023 } 15024 scheduleWritePackageRestrictionsLocked(userId); 15025 components = mPendingBroadcasts.get(userId, packageName); 15026 final boolean newPackage = components == null; 15027 if (newPackage) { 15028 components = new ArrayList<String>(); 15029 } 15030 if (!components.contains(componentName)) { 15031 components.add(componentName); 15032 } 15033 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15034 sendNow = true; 15035 // Purge entry from pending broadcast list if another one exists already 15036 // since we are sending one right away. 15037 mPendingBroadcasts.remove(userId, packageName); 15038 } else { 15039 if (newPackage) { 15040 mPendingBroadcasts.put(userId, packageName, components); 15041 } 15042 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15043 // Schedule a message 15044 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15045 } 15046 } 15047 } 15048 15049 long callingId = Binder.clearCallingIdentity(); 15050 try { 15051 if (sendNow) { 15052 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15053 sendPackageChangedBroadcast(packageName, 15054 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15055 } 15056 } finally { 15057 Binder.restoreCallingIdentity(callingId); 15058 } 15059 } 15060 15061 private void sendPackageChangedBroadcast(String packageName, 15062 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15063 if (DEBUG_INSTALL) 15064 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15065 + componentNames); 15066 Bundle extras = new Bundle(4); 15067 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15068 String nameList[] = new String[componentNames.size()]; 15069 componentNames.toArray(nameList); 15070 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15071 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15072 extras.putInt(Intent.EXTRA_UID, packageUid); 15073 // If this is not reporting a change of the overall package, then only send it 15074 // to registered receivers. We don't want to launch a swath of apps for every 15075 // little component state change. 15076 final int flags = !componentNames.contains(packageName) 15077 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15078 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15079 new int[] {UserHandle.getUserId(packageUid)}); 15080 } 15081 15082 @Override 15083 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15084 if (!sUserManager.exists(userId)) return; 15085 final int uid = Binder.getCallingUid(); 15086 final int permission = mContext.checkCallingOrSelfPermission( 15087 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15088 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15089 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15090 // writer 15091 synchronized (mPackages) { 15092 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15093 allowedByPermission, uid, userId)) { 15094 scheduleWritePackageRestrictionsLocked(userId); 15095 } 15096 } 15097 } 15098 15099 @Override 15100 public String getInstallerPackageName(String packageName) { 15101 // reader 15102 synchronized (mPackages) { 15103 return mSettings.getInstallerPackageNameLPr(packageName); 15104 } 15105 } 15106 15107 @Override 15108 public int getApplicationEnabledSetting(String packageName, int userId) { 15109 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15110 int uid = Binder.getCallingUid(); 15111 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15112 // reader 15113 synchronized (mPackages) { 15114 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15115 } 15116 } 15117 15118 @Override 15119 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15120 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15121 int uid = Binder.getCallingUid(); 15122 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15123 // reader 15124 synchronized (mPackages) { 15125 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15126 } 15127 } 15128 15129 @Override 15130 public void enterSafeMode() { 15131 enforceSystemOrRoot("Only the system can request entering safe mode"); 15132 15133 if (!mSystemReady) { 15134 mSafeMode = true; 15135 } 15136 } 15137 15138 @Override 15139 public void systemReady() { 15140 mSystemReady = true; 15141 15142 // Read the compatibilty setting when the system is ready. 15143 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15144 mContext.getContentResolver(), 15145 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15146 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15147 if (DEBUG_SETTINGS) { 15148 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15149 } 15150 15151 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15152 15153 synchronized (mPackages) { 15154 // Verify that all of the preferred activity components actually 15155 // exist. It is possible for applications to be updated and at 15156 // that point remove a previously declared activity component that 15157 // had been set as a preferred activity. We try to clean this up 15158 // the next time we encounter that preferred activity, but it is 15159 // possible for the user flow to never be able to return to that 15160 // situation so here we do a sanity check to make sure we haven't 15161 // left any junk around. 15162 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15163 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15164 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15165 removed.clear(); 15166 for (PreferredActivity pa : pir.filterSet()) { 15167 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15168 removed.add(pa); 15169 } 15170 } 15171 if (removed.size() > 0) { 15172 for (int r=0; r<removed.size(); r++) { 15173 PreferredActivity pa = removed.get(r); 15174 Slog.w(TAG, "Removing dangling preferred activity: " 15175 + pa.mPref.mComponent); 15176 pir.removeFilter(pa); 15177 } 15178 mSettings.writePackageRestrictionsLPr( 15179 mSettings.mPreferredActivities.keyAt(i)); 15180 } 15181 } 15182 15183 for (int userId : UserManagerService.getInstance().getUserIds()) { 15184 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15185 grantPermissionsUserIds = ArrayUtils.appendInt( 15186 grantPermissionsUserIds, userId); 15187 } 15188 } 15189 } 15190 sUserManager.systemReady(); 15191 15192 // If we upgraded grant all default permissions before kicking off. 15193 for (int userId : grantPermissionsUserIds) { 15194 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15195 } 15196 15197 // Kick off any messages waiting for system ready 15198 if (mPostSystemReadyMessages != null) { 15199 for (Message msg : mPostSystemReadyMessages) { 15200 msg.sendToTarget(); 15201 } 15202 mPostSystemReadyMessages = null; 15203 } 15204 15205 // Watch for external volumes that come and go over time 15206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15207 storage.registerListener(mStorageListener); 15208 15209 mInstallerService.systemReady(); 15210 mPackageDexOptimizer.systemReady(); 15211 15212 MountServiceInternal mountServiceInternal = LocalServices.getService( 15213 MountServiceInternal.class); 15214 mountServiceInternal.addExternalStoragePolicy( 15215 new MountServiceInternal.ExternalStorageMountPolicy() { 15216 @Override 15217 public int getMountMode(int uid, String packageName) { 15218 if (Process.isIsolated(uid)) { 15219 return Zygote.MOUNT_EXTERNAL_NONE; 15220 } 15221 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15222 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15223 } 15224 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15225 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15226 } 15227 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15228 return Zygote.MOUNT_EXTERNAL_READ; 15229 } 15230 return Zygote.MOUNT_EXTERNAL_WRITE; 15231 } 15232 15233 @Override 15234 public boolean hasExternalStorage(int uid, String packageName) { 15235 return true; 15236 } 15237 }); 15238 } 15239 15240 @Override 15241 public boolean isSafeMode() { 15242 return mSafeMode; 15243 } 15244 15245 @Override 15246 public boolean hasSystemUidErrors() { 15247 return mHasSystemUidErrors; 15248 } 15249 15250 static String arrayToString(int[] array) { 15251 StringBuffer buf = new StringBuffer(128); 15252 buf.append('['); 15253 if (array != null) { 15254 for (int i=0; i<array.length; i++) { 15255 if (i > 0) buf.append(", "); 15256 buf.append(array[i]); 15257 } 15258 } 15259 buf.append(']'); 15260 return buf.toString(); 15261 } 15262 15263 static class DumpState { 15264 public static final int DUMP_LIBS = 1 << 0; 15265 public static final int DUMP_FEATURES = 1 << 1; 15266 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15267 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15268 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15269 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15270 public static final int DUMP_PERMISSIONS = 1 << 6; 15271 public static final int DUMP_PACKAGES = 1 << 7; 15272 public static final int DUMP_SHARED_USERS = 1 << 8; 15273 public static final int DUMP_MESSAGES = 1 << 9; 15274 public static final int DUMP_PROVIDERS = 1 << 10; 15275 public static final int DUMP_VERIFIERS = 1 << 11; 15276 public static final int DUMP_PREFERRED = 1 << 12; 15277 public static final int DUMP_PREFERRED_XML = 1 << 13; 15278 public static final int DUMP_KEYSETS = 1 << 14; 15279 public static final int DUMP_VERSION = 1 << 15; 15280 public static final int DUMP_INSTALLS = 1 << 16; 15281 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15282 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15283 15284 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15285 15286 private int mTypes; 15287 15288 private int mOptions; 15289 15290 private boolean mTitlePrinted; 15291 15292 private SharedUserSetting mSharedUser; 15293 15294 public boolean isDumping(int type) { 15295 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15296 return true; 15297 } 15298 15299 return (mTypes & type) != 0; 15300 } 15301 15302 public void setDump(int type) { 15303 mTypes |= type; 15304 } 15305 15306 public boolean isOptionEnabled(int option) { 15307 return (mOptions & option) != 0; 15308 } 15309 15310 public void setOptionEnabled(int option) { 15311 mOptions |= option; 15312 } 15313 15314 public boolean onTitlePrinted() { 15315 final boolean printed = mTitlePrinted; 15316 mTitlePrinted = true; 15317 return printed; 15318 } 15319 15320 public boolean getTitlePrinted() { 15321 return mTitlePrinted; 15322 } 15323 15324 public void setTitlePrinted(boolean enabled) { 15325 mTitlePrinted = enabled; 15326 } 15327 15328 public SharedUserSetting getSharedUser() { 15329 return mSharedUser; 15330 } 15331 15332 public void setSharedUser(SharedUserSetting user) { 15333 mSharedUser = user; 15334 } 15335 } 15336 15337 @Override 15338 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15339 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15340 (new PackageManagerShellCommand(this)).exec( 15341 this, in, out, err, args, resultReceiver); 15342 } 15343 15344 @Override 15345 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15346 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15347 != PackageManager.PERMISSION_GRANTED) { 15348 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15349 + Binder.getCallingPid() 15350 + ", uid=" + Binder.getCallingUid() 15351 + " without permission " 15352 + android.Manifest.permission.DUMP); 15353 return; 15354 } 15355 15356 DumpState dumpState = new DumpState(); 15357 boolean fullPreferred = false; 15358 boolean checkin = false; 15359 15360 String packageName = null; 15361 ArraySet<String> permissionNames = null; 15362 15363 int opti = 0; 15364 while (opti < args.length) { 15365 String opt = args[opti]; 15366 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15367 break; 15368 } 15369 opti++; 15370 15371 if ("-a".equals(opt)) { 15372 // Right now we only know how to print all. 15373 } else if ("-h".equals(opt)) { 15374 pw.println("Package manager dump options:"); 15375 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15376 pw.println(" --checkin: dump for a checkin"); 15377 pw.println(" -f: print details of intent filters"); 15378 pw.println(" -h: print this help"); 15379 pw.println(" cmd may be one of:"); 15380 pw.println(" l[ibraries]: list known shared libraries"); 15381 pw.println(" f[eatures]: list device features"); 15382 pw.println(" k[eysets]: print known keysets"); 15383 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15384 pw.println(" perm[issions]: dump permissions"); 15385 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15386 pw.println(" pref[erred]: print preferred package settings"); 15387 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15388 pw.println(" prov[iders]: dump content providers"); 15389 pw.println(" p[ackages]: dump installed packages"); 15390 pw.println(" s[hared-users]: dump shared user IDs"); 15391 pw.println(" m[essages]: print collected runtime messages"); 15392 pw.println(" v[erifiers]: print package verifier info"); 15393 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15394 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15395 pw.println(" version: print database version info"); 15396 pw.println(" write: write current settings now"); 15397 pw.println(" installs: details about install sessions"); 15398 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15399 pw.println(" <package.name>: info about given package"); 15400 return; 15401 } else if ("--checkin".equals(opt)) { 15402 checkin = true; 15403 } else if ("-f".equals(opt)) { 15404 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15405 } else { 15406 pw.println("Unknown argument: " + opt + "; use -h for help"); 15407 } 15408 } 15409 15410 // Is the caller requesting to dump a particular piece of data? 15411 if (opti < args.length) { 15412 String cmd = args[opti]; 15413 opti++; 15414 // Is this a package name? 15415 if ("android".equals(cmd) || cmd.contains(".")) { 15416 packageName = cmd; 15417 // When dumping a single package, we always dump all of its 15418 // filter information since the amount of data will be reasonable. 15419 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15420 } else if ("check-permission".equals(cmd)) { 15421 if (opti >= args.length) { 15422 pw.println("Error: check-permission missing permission argument"); 15423 return; 15424 } 15425 String perm = args[opti]; 15426 opti++; 15427 if (opti >= args.length) { 15428 pw.println("Error: check-permission missing package argument"); 15429 return; 15430 } 15431 String pkg = args[opti]; 15432 opti++; 15433 int user = UserHandle.getUserId(Binder.getCallingUid()); 15434 if (opti < args.length) { 15435 try { 15436 user = Integer.parseInt(args[opti]); 15437 } catch (NumberFormatException e) { 15438 pw.println("Error: check-permission user argument is not a number: " 15439 + args[opti]); 15440 return; 15441 } 15442 } 15443 pw.println(checkPermission(perm, pkg, user)); 15444 return; 15445 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15446 dumpState.setDump(DumpState.DUMP_LIBS); 15447 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15448 dumpState.setDump(DumpState.DUMP_FEATURES); 15449 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15450 if (opti >= args.length) { 15451 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15452 | DumpState.DUMP_SERVICE_RESOLVERS 15453 | DumpState.DUMP_RECEIVER_RESOLVERS 15454 | DumpState.DUMP_CONTENT_RESOLVERS); 15455 } else { 15456 while (opti < args.length) { 15457 String name = args[opti]; 15458 if ("a".equals(name) || "activity".equals(name)) { 15459 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15460 } else if ("s".equals(name) || "service".equals(name)) { 15461 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15462 } else if ("r".equals(name) || "receiver".equals(name)) { 15463 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15464 } else if ("c".equals(name) || "content".equals(name)) { 15465 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15466 } else { 15467 pw.println("Error: unknown resolver table type: " + name); 15468 return; 15469 } 15470 opti++; 15471 } 15472 } 15473 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15474 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15475 } else if ("permission".equals(cmd)) { 15476 if (opti >= args.length) { 15477 pw.println("Error: permission requires permission name"); 15478 return; 15479 } 15480 permissionNames = new ArraySet<>(); 15481 while (opti < args.length) { 15482 permissionNames.add(args[opti]); 15483 opti++; 15484 } 15485 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15486 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15487 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15488 dumpState.setDump(DumpState.DUMP_PREFERRED); 15489 } else if ("preferred-xml".equals(cmd)) { 15490 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15491 if (opti < args.length && "--full".equals(args[opti])) { 15492 fullPreferred = true; 15493 opti++; 15494 } 15495 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15496 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15497 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15498 dumpState.setDump(DumpState.DUMP_PACKAGES); 15499 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15500 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15501 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15502 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15503 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15504 dumpState.setDump(DumpState.DUMP_MESSAGES); 15505 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15506 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15507 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15508 || "intent-filter-verifiers".equals(cmd)) { 15509 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15510 } else if ("version".equals(cmd)) { 15511 dumpState.setDump(DumpState.DUMP_VERSION); 15512 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15513 dumpState.setDump(DumpState.DUMP_KEYSETS); 15514 } else if ("installs".equals(cmd)) { 15515 dumpState.setDump(DumpState.DUMP_INSTALLS); 15516 } else if ("write".equals(cmd)) { 15517 synchronized (mPackages) { 15518 mSettings.writeLPr(); 15519 pw.println("Settings written."); 15520 return; 15521 } 15522 } 15523 } 15524 15525 if (checkin) { 15526 pw.println("vers,1"); 15527 } 15528 15529 // reader 15530 synchronized (mPackages) { 15531 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15532 if (!checkin) { 15533 if (dumpState.onTitlePrinted()) 15534 pw.println(); 15535 pw.println("Database versions:"); 15536 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15537 } 15538 } 15539 15540 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15541 if (!checkin) { 15542 if (dumpState.onTitlePrinted()) 15543 pw.println(); 15544 pw.println("Verifiers:"); 15545 pw.print(" Required: "); 15546 pw.print(mRequiredVerifierPackage); 15547 pw.print(" (uid="); 15548 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15549 pw.println(")"); 15550 } else if (mRequiredVerifierPackage != null) { 15551 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15552 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15553 } 15554 } 15555 15556 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15557 packageName == null) { 15558 if (mIntentFilterVerifierComponent != null) { 15559 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15560 if (!checkin) { 15561 if (dumpState.onTitlePrinted()) 15562 pw.println(); 15563 pw.println("Intent Filter Verifier:"); 15564 pw.print(" Using: "); 15565 pw.print(verifierPackageName); 15566 pw.print(" (uid="); 15567 pw.print(getPackageUid(verifierPackageName, 0)); 15568 pw.println(")"); 15569 } else if (verifierPackageName != null) { 15570 pw.print("ifv,"); pw.print(verifierPackageName); 15571 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15572 } 15573 } else { 15574 pw.println(); 15575 pw.println("No Intent Filter Verifier available!"); 15576 } 15577 } 15578 15579 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15580 boolean printedHeader = false; 15581 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15582 while (it.hasNext()) { 15583 String name = it.next(); 15584 SharedLibraryEntry ent = mSharedLibraries.get(name); 15585 if (!checkin) { 15586 if (!printedHeader) { 15587 if (dumpState.onTitlePrinted()) 15588 pw.println(); 15589 pw.println("Libraries:"); 15590 printedHeader = true; 15591 } 15592 pw.print(" "); 15593 } else { 15594 pw.print("lib,"); 15595 } 15596 pw.print(name); 15597 if (!checkin) { 15598 pw.print(" -> "); 15599 } 15600 if (ent.path != null) { 15601 if (!checkin) { 15602 pw.print("(jar) "); 15603 pw.print(ent.path); 15604 } else { 15605 pw.print(",jar,"); 15606 pw.print(ent.path); 15607 } 15608 } else { 15609 if (!checkin) { 15610 pw.print("(apk) "); 15611 pw.print(ent.apk); 15612 } else { 15613 pw.print(",apk,"); 15614 pw.print(ent.apk); 15615 } 15616 } 15617 pw.println(); 15618 } 15619 } 15620 15621 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15622 if (dumpState.onTitlePrinted()) 15623 pw.println(); 15624 if (!checkin) { 15625 pw.println("Features:"); 15626 } 15627 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15628 while (it.hasNext()) { 15629 String name = it.next(); 15630 if (!checkin) { 15631 pw.print(" "); 15632 } else { 15633 pw.print("feat,"); 15634 } 15635 pw.println(name); 15636 } 15637 } 15638 15639 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15640 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15641 : "Activity Resolver Table:", " ", packageName, 15642 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15643 dumpState.setTitlePrinted(true); 15644 } 15645 } 15646 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15647 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15648 : "Receiver Resolver Table:", " ", packageName, 15649 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15650 dumpState.setTitlePrinted(true); 15651 } 15652 } 15653 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15654 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15655 : "Service Resolver Table:", " ", packageName, 15656 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15657 dumpState.setTitlePrinted(true); 15658 } 15659 } 15660 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15661 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15662 : "Provider Resolver Table:", " ", packageName, 15663 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15664 dumpState.setTitlePrinted(true); 15665 } 15666 } 15667 15668 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15669 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15670 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15671 int user = mSettings.mPreferredActivities.keyAt(i); 15672 if (pir.dump(pw, 15673 dumpState.getTitlePrinted() 15674 ? "\nPreferred Activities User " + user + ":" 15675 : "Preferred Activities User " + user + ":", " ", 15676 packageName, true, false)) { 15677 dumpState.setTitlePrinted(true); 15678 } 15679 } 15680 } 15681 15682 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15683 pw.flush(); 15684 FileOutputStream fout = new FileOutputStream(fd); 15685 BufferedOutputStream str = new BufferedOutputStream(fout); 15686 XmlSerializer serializer = new FastXmlSerializer(); 15687 try { 15688 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15689 serializer.startDocument(null, true); 15690 serializer.setFeature( 15691 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15692 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15693 serializer.endDocument(); 15694 serializer.flush(); 15695 } catch (IllegalArgumentException e) { 15696 pw.println("Failed writing: " + e); 15697 } catch (IllegalStateException e) { 15698 pw.println("Failed writing: " + e); 15699 } catch (IOException e) { 15700 pw.println("Failed writing: " + e); 15701 } 15702 } 15703 15704 if (!checkin 15705 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15706 && packageName == null) { 15707 pw.println(); 15708 int count = mSettings.mPackages.size(); 15709 if (count == 0) { 15710 pw.println("No applications!"); 15711 pw.println(); 15712 } else { 15713 final String prefix = " "; 15714 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15715 if (allPackageSettings.size() == 0) { 15716 pw.println("No domain preferred apps!"); 15717 pw.println(); 15718 } else { 15719 pw.println("App verification status:"); 15720 pw.println(); 15721 count = 0; 15722 for (PackageSetting ps : allPackageSettings) { 15723 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15724 if (ivi == null || ivi.getPackageName() == null) continue; 15725 pw.println(prefix + "Package: " + ivi.getPackageName()); 15726 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15727 pw.println(prefix + "Status: " + ivi.getStatusString()); 15728 pw.println(); 15729 count++; 15730 } 15731 if (count == 0) { 15732 pw.println(prefix + "No app verification established."); 15733 pw.println(); 15734 } 15735 for (int userId : sUserManager.getUserIds()) { 15736 pw.println("App linkages for user " + userId + ":"); 15737 pw.println(); 15738 count = 0; 15739 for (PackageSetting ps : allPackageSettings) { 15740 final long status = ps.getDomainVerificationStatusForUser(userId); 15741 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15742 continue; 15743 } 15744 pw.println(prefix + "Package: " + ps.name); 15745 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15746 String statusStr = IntentFilterVerificationInfo. 15747 getStatusStringFromValue(status); 15748 pw.println(prefix + "Status: " + statusStr); 15749 pw.println(); 15750 count++; 15751 } 15752 if (count == 0) { 15753 pw.println(prefix + "No configured app linkages."); 15754 pw.println(); 15755 } 15756 } 15757 } 15758 } 15759 } 15760 15761 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15762 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15763 if (packageName == null && permissionNames == null) { 15764 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15765 if (iperm == 0) { 15766 if (dumpState.onTitlePrinted()) 15767 pw.println(); 15768 pw.println("AppOp Permissions:"); 15769 } 15770 pw.print(" AppOp Permission "); 15771 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15772 pw.println(":"); 15773 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15774 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15775 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15776 } 15777 } 15778 } 15779 } 15780 15781 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15782 boolean printedSomething = false; 15783 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15784 if (packageName != null && !packageName.equals(p.info.packageName)) { 15785 continue; 15786 } 15787 if (!printedSomething) { 15788 if (dumpState.onTitlePrinted()) 15789 pw.println(); 15790 pw.println("Registered ContentProviders:"); 15791 printedSomething = true; 15792 } 15793 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15794 pw.print(" "); pw.println(p.toString()); 15795 } 15796 printedSomething = false; 15797 for (Map.Entry<String, PackageParser.Provider> entry : 15798 mProvidersByAuthority.entrySet()) { 15799 PackageParser.Provider p = entry.getValue(); 15800 if (packageName != null && !packageName.equals(p.info.packageName)) { 15801 continue; 15802 } 15803 if (!printedSomething) { 15804 if (dumpState.onTitlePrinted()) 15805 pw.println(); 15806 pw.println("ContentProvider Authorities:"); 15807 printedSomething = true; 15808 } 15809 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15810 pw.print(" "); pw.println(p.toString()); 15811 if (p.info != null && p.info.applicationInfo != null) { 15812 final String appInfo = p.info.applicationInfo.toString(); 15813 pw.print(" applicationInfo="); pw.println(appInfo); 15814 } 15815 } 15816 } 15817 15818 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15819 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15820 } 15821 15822 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15823 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15824 } 15825 15826 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15827 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15828 } 15829 15830 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15831 // XXX should handle packageName != null by dumping only install data that 15832 // the given package is involved with. 15833 if (dumpState.onTitlePrinted()) pw.println(); 15834 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15835 } 15836 15837 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15838 if (dumpState.onTitlePrinted()) pw.println(); 15839 mSettings.dumpReadMessagesLPr(pw, dumpState); 15840 15841 pw.println(); 15842 pw.println("Package warning messages:"); 15843 BufferedReader in = null; 15844 String line = null; 15845 try { 15846 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15847 while ((line = in.readLine()) != null) { 15848 if (line.contains("ignored: updated version")) continue; 15849 pw.println(line); 15850 } 15851 } catch (IOException ignored) { 15852 } finally { 15853 IoUtils.closeQuietly(in); 15854 } 15855 } 15856 15857 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15858 BufferedReader in = null; 15859 String line = null; 15860 try { 15861 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15862 while ((line = in.readLine()) != null) { 15863 if (line.contains("ignored: updated version")) continue; 15864 pw.print("msg,"); 15865 pw.println(line); 15866 } 15867 } catch (IOException ignored) { 15868 } finally { 15869 IoUtils.closeQuietly(in); 15870 } 15871 } 15872 } 15873 } 15874 15875 private String dumpDomainString(String packageName) { 15876 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15877 List<IntentFilter> filters = getAllIntentFilters(packageName); 15878 15879 ArraySet<String> result = new ArraySet<>(); 15880 if (iviList.size() > 0) { 15881 for (IntentFilterVerificationInfo ivi : iviList) { 15882 for (String host : ivi.getDomains()) { 15883 result.add(host); 15884 } 15885 } 15886 } 15887 if (filters != null && filters.size() > 0) { 15888 for (IntentFilter filter : filters) { 15889 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15890 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15891 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15892 result.addAll(filter.getHostsList()); 15893 } 15894 } 15895 } 15896 15897 StringBuilder sb = new StringBuilder(result.size() * 16); 15898 for (String domain : result) { 15899 if (sb.length() > 0) sb.append(" "); 15900 sb.append(domain); 15901 } 15902 return sb.toString(); 15903 } 15904 15905 // ------- apps on sdcard specific code ------- 15906 static final boolean DEBUG_SD_INSTALL = false; 15907 15908 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15909 15910 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15911 15912 private boolean mMediaMounted = false; 15913 15914 static String getEncryptKey() { 15915 try { 15916 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15917 SD_ENCRYPTION_KEYSTORE_NAME); 15918 if (sdEncKey == null) { 15919 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15920 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15921 if (sdEncKey == null) { 15922 Slog.e(TAG, "Failed to create encryption keys"); 15923 return null; 15924 } 15925 } 15926 return sdEncKey; 15927 } catch (NoSuchAlgorithmException nsae) { 15928 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15929 return null; 15930 } catch (IOException ioe) { 15931 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15932 return null; 15933 } 15934 } 15935 15936 /* 15937 * Update media status on PackageManager. 15938 */ 15939 @Override 15940 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15941 int callingUid = Binder.getCallingUid(); 15942 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15943 throw new SecurityException("Media status can only be updated by the system"); 15944 } 15945 // reader; this apparently protects mMediaMounted, but should probably 15946 // be a different lock in that case. 15947 synchronized (mPackages) { 15948 Log.i(TAG, "Updating external media status from " 15949 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15950 + (mediaStatus ? "mounted" : "unmounted")); 15951 if (DEBUG_SD_INSTALL) 15952 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15953 + ", mMediaMounted=" + mMediaMounted); 15954 if (mediaStatus == mMediaMounted) { 15955 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15956 : 0, -1); 15957 mHandler.sendMessage(msg); 15958 return; 15959 } 15960 mMediaMounted = mediaStatus; 15961 } 15962 // Queue up an async operation since the package installation may take a 15963 // little while. 15964 mHandler.post(new Runnable() { 15965 public void run() { 15966 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15967 } 15968 }); 15969 } 15970 15971 /** 15972 * Called by MountService when the initial ASECs to scan are available. 15973 * Should block until all the ASEC containers are finished being scanned. 15974 */ 15975 public void scanAvailableAsecs() { 15976 updateExternalMediaStatusInner(true, false, false); 15977 if (mShouldRestoreconData) { 15978 SELinuxMMAC.setRestoreconDone(); 15979 mShouldRestoreconData = false; 15980 } 15981 } 15982 15983 /* 15984 * Collect information of applications on external media, map them against 15985 * existing containers and update information based on current mount status. 15986 * Please note that we always have to report status if reportStatus has been 15987 * set to true especially when unloading packages. 15988 */ 15989 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15990 boolean externalStorage) { 15991 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15992 int[] uidArr = EmptyArray.INT; 15993 15994 final String[] list = PackageHelper.getSecureContainerList(); 15995 if (ArrayUtils.isEmpty(list)) { 15996 Log.i(TAG, "No secure containers found"); 15997 } else { 15998 // Process list of secure containers and categorize them 15999 // as active or stale based on their package internal state. 16000 16001 // reader 16002 synchronized (mPackages) { 16003 for (String cid : list) { 16004 // Leave stages untouched for now; installer service owns them 16005 if (PackageInstallerService.isStageName(cid)) continue; 16006 16007 if (DEBUG_SD_INSTALL) 16008 Log.i(TAG, "Processing container " + cid); 16009 String pkgName = getAsecPackageName(cid); 16010 if (pkgName == null) { 16011 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16012 continue; 16013 } 16014 if (DEBUG_SD_INSTALL) 16015 Log.i(TAG, "Looking for pkg : " + pkgName); 16016 16017 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16018 if (ps == null) { 16019 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16020 continue; 16021 } 16022 16023 /* 16024 * Skip packages that are not external if we're unmounting 16025 * external storage. 16026 */ 16027 if (externalStorage && !isMounted && !isExternal(ps)) { 16028 continue; 16029 } 16030 16031 final AsecInstallArgs args = new AsecInstallArgs(cid, 16032 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16033 // The package status is changed only if the code path 16034 // matches between settings and the container id. 16035 if (ps.codePathString != null 16036 && ps.codePathString.startsWith(args.getCodePath())) { 16037 if (DEBUG_SD_INSTALL) { 16038 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16039 + " at code path: " + ps.codePathString); 16040 } 16041 16042 // We do have a valid package installed on sdcard 16043 processCids.put(args, ps.codePathString); 16044 final int uid = ps.appId; 16045 if (uid != -1) { 16046 uidArr = ArrayUtils.appendInt(uidArr, uid); 16047 } 16048 } else { 16049 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16050 + ps.codePathString); 16051 } 16052 } 16053 } 16054 16055 Arrays.sort(uidArr); 16056 } 16057 16058 // Process packages with valid entries. 16059 if (isMounted) { 16060 if (DEBUG_SD_INSTALL) 16061 Log.i(TAG, "Loading packages"); 16062 loadMediaPackages(processCids, uidArr, externalStorage); 16063 startCleaningPackages(); 16064 mInstallerService.onSecureContainersAvailable(); 16065 } else { 16066 if (DEBUG_SD_INSTALL) 16067 Log.i(TAG, "Unloading packages"); 16068 unloadMediaPackages(processCids, uidArr, reportStatus); 16069 } 16070 } 16071 16072 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16073 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16074 final int size = infos.size(); 16075 final String[] packageNames = new String[size]; 16076 final int[] packageUids = new int[size]; 16077 for (int i = 0; i < size; i++) { 16078 final ApplicationInfo info = infos.get(i); 16079 packageNames[i] = info.packageName; 16080 packageUids[i] = info.uid; 16081 } 16082 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16083 finishedReceiver); 16084 } 16085 16086 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16087 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16088 sendResourcesChangedBroadcast(mediaStatus, replacing, 16089 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16090 } 16091 16092 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16093 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16094 int size = pkgList.length; 16095 if (size > 0) { 16096 // Send broadcasts here 16097 Bundle extras = new Bundle(); 16098 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16099 if (uidArr != null) { 16100 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16101 } 16102 if (replacing) { 16103 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16104 } 16105 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16106 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16107 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16108 } 16109 } 16110 16111 /* 16112 * Look at potentially valid container ids from processCids If package 16113 * information doesn't match the one on record or package scanning fails, 16114 * the cid is added to list of removeCids. We currently don't delete stale 16115 * containers. 16116 */ 16117 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16118 boolean externalStorage) { 16119 ArrayList<String> pkgList = new ArrayList<String>(); 16120 Set<AsecInstallArgs> keys = processCids.keySet(); 16121 16122 for (AsecInstallArgs args : keys) { 16123 String codePath = processCids.get(args); 16124 if (DEBUG_SD_INSTALL) 16125 Log.i(TAG, "Loading container : " + args.cid); 16126 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16127 try { 16128 // Make sure there are no container errors first. 16129 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16130 Slog.e(TAG, "Failed to mount cid : " + args.cid 16131 + " when installing from sdcard"); 16132 continue; 16133 } 16134 // Check code path here. 16135 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16136 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16137 + " does not match one in settings " + codePath); 16138 continue; 16139 } 16140 // Parse package 16141 int parseFlags = mDefParseFlags; 16142 if (args.isExternalAsec()) { 16143 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16144 } 16145 if (args.isFwdLocked()) { 16146 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16147 } 16148 16149 synchronized (mInstallLock) { 16150 PackageParser.Package pkg = null; 16151 try { 16152 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16153 } catch (PackageManagerException e) { 16154 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16155 } 16156 // Scan the package 16157 if (pkg != null) { 16158 /* 16159 * TODO why is the lock being held? doPostInstall is 16160 * called in other places without the lock. This needs 16161 * to be straightened out. 16162 */ 16163 // writer 16164 synchronized (mPackages) { 16165 retCode = PackageManager.INSTALL_SUCCEEDED; 16166 pkgList.add(pkg.packageName); 16167 // Post process args 16168 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16169 pkg.applicationInfo.uid); 16170 } 16171 } else { 16172 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16173 } 16174 } 16175 16176 } finally { 16177 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16178 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16179 } 16180 } 16181 } 16182 // writer 16183 synchronized (mPackages) { 16184 // If the platform SDK has changed since the last time we booted, 16185 // we need to re-grant app permission to catch any new ones that 16186 // appear. This is really a hack, and means that apps can in some 16187 // cases get permissions that the user didn't initially explicitly 16188 // allow... it would be nice to have some better way to handle 16189 // this situation. 16190 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16191 : mSettings.getInternalVersion(); 16192 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16193 : StorageManager.UUID_PRIVATE_INTERNAL; 16194 16195 int updateFlags = UPDATE_PERMISSIONS_ALL; 16196 if (ver.sdkVersion != mSdkVersion) { 16197 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16198 + mSdkVersion + "; regranting permissions for external"); 16199 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16200 } 16201 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16202 16203 // Yay, everything is now upgraded 16204 ver.forceCurrent(); 16205 16206 // can downgrade to reader 16207 // Persist settings 16208 mSettings.writeLPr(); 16209 } 16210 // Send a broadcast to let everyone know we are done processing 16211 if (pkgList.size() > 0) { 16212 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16213 } 16214 } 16215 16216 /* 16217 * Utility method to unload a list of specified containers 16218 */ 16219 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16220 // Just unmount all valid containers. 16221 for (AsecInstallArgs arg : cidArgs) { 16222 synchronized (mInstallLock) { 16223 arg.doPostDeleteLI(false); 16224 } 16225 } 16226 } 16227 16228 /* 16229 * Unload packages mounted on external media. This involves deleting package 16230 * data from internal structures, sending broadcasts about diabled packages, 16231 * gc'ing to free up references, unmounting all secure containers 16232 * corresponding to packages on external media, and posting a 16233 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16234 * that we always have to post this message if status has been requested no 16235 * matter what. 16236 */ 16237 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16238 final boolean reportStatus) { 16239 if (DEBUG_SD_INSTALL) 16240 Log.i(TAG, "unloading media packages"); 16241 ArrayList<String> pkgList = new ArrayList<String>(); 16242 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16243 final Set<AsecInstallArgs> keys = processCids.keySet(); 16244 for (AsecInstallArgs args : keys) { 16245 String pkgName = args.getPackageName(); 16246 if (DEBUG_SD_INSTALL) 16247 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16248 // Delete package internally 16249 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16250 synchronized (mInstallLock) { 16251 boolean res = deletePackageLI(pkgName, null, false, null, null, 16252 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16253 if (res) { 16254 pkgList.add(pkgName); 16255 } else { 16256 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16257 failedList.add(args); 16258 } 16259 } 16260 } 16261 16262 // reader 16263 synchronized (mPackages) { 16264 // We didn't update the settings after removing each package; 16265 // write them now for all packages. 16266 mSettings.writeLPr(); 16267 } 16268 16269 // We have to absolutely send UPDATED_MEDIA_STATUS only 16270 // after confirming that all the receivers processed the ordered 16271 // broadcast when packages get disabled, force a gc to clean things up. 16272 // and unload all the containers. 16273 if (pkgList.size() > 0) { 16274 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16275 new IIntentReceiver.Stub() { 16276 public void performReceive(Intent intent, int resultCode, String data, 16277 Bundle extras, boolean ordered, boolean sticky, 16278 int sendingUser) throws RemoteException { 16279 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16280 reportStatus ? 1 : 0, 1, keys); 16281 mHandler.sendMessage(msg); 16282 } 16283 }); 16284 } else { 16285 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16286 keys); 16287 mHandler.sendMessage(msg); 16288 } 16289 } 16290 16291 private void loadPrivatePackages(final VolumeInfo vol) { 16292 mHandler.post(new Runnable() { 16293 @Override 16294 public void run() { 16295 loadPrivatePackagesInner(vol); 16296 } 16297 }); 16298 } 16299 16300 private void loadPrivatePackagesInner(VolumeInfo vol) { 16301 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16302 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16303 16304 final VersionInfo ver; 16305 final List<PackageSetting> packages; 16306 synchronized (mPackages) { 16307 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16308 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16309 } 16310 16311 for (PackageSetting ps : packages) { 16312 synchronized (mInstallLock) { 16313 final PackageParser.Package pkg; 16314 try { 16315 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16316 loaded.add(pkg.applicationInfo); 16317 } catch (PackageManagerException e) { 16318 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16319 } 16320 16321 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16322 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16323 } 16324 } 16325 } 16326 16327 synchronized (mPackages) { 16328 int updateFlags = UPDATE_PERMISSIONS_ALL; 16329 if (ver.sdkVersion != mSdkVersion) { 16330 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16331 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16332 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16333 } 16334 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16335 16336 // Yay, everything is now upgraded 16337 ver.forceCurrent(); 16338 16339 mSettings.writeLPr(); 16340 } 16341 16342 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16343 sendResourcesChangedBroadcast(true, false, loaded, null); 16344 } 16345 16346 private void unloadPrivatePackages(final VolumeInfo vol) { 16347 mHandler.post(new Runnable() { 16348 @Override 16349 public void run() { 16350 unloadPrivatePackagesInner(vol); 16351 } 16352 }); 16353 } 16354 16355 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16356 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16357 synchronized (mInstallLock) { 16358 synchronized (mPackages) { 16359 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16360 for (PackageSetting ps : packages) { 16361 if (ps.pkg == null) continue; 16362 16363 final ApplicationInfo info = ps.pkg.applicationInfo; 16364 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16365 if (deletePackageLI(ps.name, null, false, null, null, 16366 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16367 unloaded.add(info); 16368 } else { 16369 Slog.w(TAG, "Failed to unload " + ps.codePath); 16370 } 16371 } 16372 16373 mSettings.writeLPr(); 16374 } 16375 } 16376 16377 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16378 sendResourcesChangedBroadcast(false, false, unloaded, null); 16379 } 16380 16381 /** 16382 * Examine all users present on given mounted volume, and destroy data 16383 * belonging to users that are no longer valid, or whose user ID has been 16384 * recycled. 16385 */ 16386 private void reconcileUsers(String volumeUuid) { 16387 final File[] files = FileUtils 16388 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16389 for (File file : files) { 16390 if (!file.isDirectory()) continue; 16391 16392 final int userId; 16393 final UserInfo info; 16394 try { 16395 userId = Integer.parseInt(file.getName()); 16396 info = sUserManager.getUserInfo(userId); 16397 } catch (NumberFormatException e) { 16398 Slog.w(TAG, "Invalid user directory " + file); 16399 continue; 16400 } 16401 16402 boolean destroyUser = false; 16403 if (info == null) { 16404 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16405 + " because no matching user was found"); 16406 destroyUser = true; 16407 } else { 16408 try { 16409 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16410 } catch (IOException e) { 16411 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16412 + " because we failed to enforce serial number: " + e); 16413 destroyUser = true; 16414 } 16415 } 16416 16417 if (destroyUser) { 16418 synchronized (mInstallLock) { 16419 mInstaller.removeUserDataDirs(volumeUuid, userId); 16420 } 16421 } 16422 } 16423 16424 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16425 final UserManager um = mContext.getSystemService(UserManager.class); 16426 for (UserInfo user : um.getUsers()) { 16427 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16428 if (userDir.exists()) continue; 16429 16430 try { 16431 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 16432 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16433 } catch (IOException e) { 16434 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16435 } 16436 } 16437 } 16438 16439 /** 16440 * Examine all apps present on given mounted volume, and destroy apps that 16441 * aren't expected, either due to uninstallation or reinstallation on 16442 * another volume. 16443 */ 16444 private void reconcileApps(String volumeUuid) { 16445 final File[] files = FileUtils 16446 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16447 for (File file : files) { 16448 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16449 && !PackageInstallerService.isStageName(file.getName()); 16450 if (!isPackage) { 16451 // Ignore entries which are not packages 16452 continue; 16453 } 16454 16455 boolean destroyApp = false; 16456 String packageName = null; 16457 try { 16458 final PackageLite pkg = PackageParser.parsePackageLite(file, 16459 PackageParser.PARSE_MUST_BE_APK); 16460 packageName = pkg.packageName; 16461 16462 synchronized (mPackages) { 16463 final PackageSetting ps = mSettings.mPackages.get(packageName); 16464 if (ps == null) { 16465 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16466 + volumeUuid + " because we found no install record"); 16467 destroyApp = true; 16468 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16469 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16470 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16471 destroyApp = true; 16472 } 16473 } 16474 16475 } catch (PackageParserException e) { 16476 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16477 destroyApp = true; 16478 } 16479 16480 if (destroyApp) { 16481 synchronized (mInstallLock) { 16482 if (packageName != null) { 16483 removeDataDirsLI(volumeUuid, packageName); 16484 } 16485 if (file.isDirectory()) { 16486 mInstaller.rmPackageDir(file.getAbsolutePath()); 16487 } else { 16488 file.delete(); 16489 } 16490 } 16491 } 16492 } 16493 } 16494 16495 private void unfreezePackage(String packageName) { 16496 synchronized (mPackages) { 16497 final PackageSetting ps = mSettings.mPackages.get(packageName); 16498 if (ps != null) { 16499 ps.frozen = false; 16500 } 16501 } 16502 } 16503 16504 @Override 16505 public int movePackage(final String packageName, final String volumeUuid) { 16506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16507 16508 final int moveId = mNextMoveId.getAndIncrement(); 16509 mHandler.post(new Runnable() { 16510 @Override 16511 public void run() { 16512 try { 16513 movePackageInternal(packageName, volumeUuid, moveId); 16514 } catch (PackageManagerException e) { 16515 Slog.w(TAG, "Failed to move " + packageName, e); 16516 mMoveCallbacks.notifyStatusChanged(moveId, 16517 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16518 } 16519 } 16520 }); 16521 return moveId; 16522 } 16523 16524 private void movePackageInternal(final String packageName, final String volumeUuid, 16525 final int moveId) throws PackageManagerException { 16526 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16527 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16528 final PackageManager pm = mContext.getPackageManager(); 16529 16530 final boolean currentAsec; 16531 final String currentVolumeUuid; 16532 final File codeFile; 16533 final String installerPackageName; 16534 final String packageAbiOverride; 16535 final int appId; 16536 final String seinfo; 16537 final String label; 16538 16539 // reader 16540 synchronized (mPackages) { 16541 final PackageParser.Package pkg = mPackages.get(packageName); 16542 final PackageSetting ps = mSettings.mPackages.get(packageName); 16543 if (pkg == null || ps == null) { 16544 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16545 } 16546 16547 if (pkg.applicationInfo.isSystemApp()) { 16548 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16549 "Cannot move system application"); 16550 } 16551 16552 if (pkg.applicationInfo.isExternalAsec()) { 16553 currentAsec = true; 16554 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16555 } else if (pkg.applicationInfo.isForwardLocked()) { 16556 currentAsec = true; 16557 currentVolumeUuid = "forward_locked"; 16558 } else { 16559 currentAsec = false; 16560 currentVolumeUuid = ps.volumeUuid; 16561 16562 final File probe = new File(pkg.codePath); 16563 final File probeOat = new File(probe, "oat"); 16564 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16565 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16566 "Move only supported for modern cluster style installs"); 16567 } 16568 } 16569 16570 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16571 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16572 "Package already moved to " + volumeUuid); 16573 } 16574 16575 if (ps.frozen) { 16576 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16577 "Failed to move already frozen package"); 16578 } 16579 ps.frozen = true; 16580 16581 codeFile = new File(pkg.codePath); 16582 installerPackageName = ps.installerPackageName; 16583 packageAbiOverride = ps.cpuAbiOverrideString; 16584 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16585 seinfo = pkg.applicationInfo.seinfo; 16586 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16587 } 16588 16589 // Now that we're guarded by frozen state, kill app during move 16590 final long token = Binder.clearCallingIdentity(); 16591 try { 16592 killApplication(packageName, appId, "move pkg"); 16593 } finally { 16594 Binder.restoreCallingIdentity(token); 16595 } 16596 16597 final Bundle extras = new Bundle(); 16598 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16599 extras.putString(Intent.EXTRA_TITLE, label); 16600 mMoveCallbacks.notifyCreated(moveId, extras); 16601 16602 int installFlags; 16603 final boolean moveCompleteApp; 16604 final File measurePath; 16605 16606 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16607 installFlags = INSTALL_INTERNAL; 16608 moveCompleteApp = !currentAsec; 16609 measurePath = Environment.getDataAppDirectory(volumeUuid); 16610 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16611 installFlags = INSTALL_EXTERNAL; 16612 moveCompleteApp = false; 16613 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16614 } else { 16615 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16616 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16617 || !volume.isMountedWritable()) { 16618 unfreezePackage(packageName); 16619 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16620 "Move location not mounted private volume"); 16621 } 16622 16623 Preconditions.checkState(!currentAsec); 16624 16625 installFlags = INSTALL_INTERNAL; 16626 moveCompleteApp = true; 16627 measurePath = Environment.getDataAppDirectory(volumeUuid); 16628 } 16629 16630 final PackageStats stats = new PackageStats(null, -1); 16631 synchronized (mInstaller) { 16632 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16633 unfreezePackage(packageName); 16634 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16635 "Failed to measure package size"); 16636 } 16637 } 16638 16639 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16640 + stats.dataSize); 16641 16642 final long startFreeBytes = measurePath.getFreeSpace(); 16643 final long sizeBytes; 16644 if (moveCompleteApp) { 16645 sizeBytes = stats.codeSize + stats.dataSize; 16646 } else { 16647 sizeBytes = stats.codeSize; 16648 } 16649 16650 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16651 unfreezePackage(packageName); 16652 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16653 "Not enough free space to move"); 16654 } 16655 16656 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16657 16658 final CountDownLatch installedLatch = new CountDownLatch(1); 16659 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16660 @Override 16661 public void onUserActionRequired(Intent intent) throws RemoteException { 16662 throw new IllegalStateException(); 16663 } 16664 16665 @Override 16666 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16667 Bundle extras) throws RemoteException { 16668 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16669 + PackageManager.installStatusToString(returnCode, msg)); 16670 16671 installedLatch.countDown(); 16672 16673 // Regardless of success or failure of the move operation, 16674 // always unfreeze the package 16675 unfreezePackage(packageName); 16676 16677 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16678 switch (status) { 16679 case PackageInstaller.STATUS_SUCCESS: 16680 mMoveCallbacks.notifyStatusChanged(moveId, 16681 PackageManager.MOVE_SUCCEEDED); 16682 break; 16683 case PackageInstaller.STATUS_FAILURE_STORAGE: 16684 mMoveCallbacks.notifyStatusChanged(moveId, 16685 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16686 break; 16687 default: 16688 mMoveCallbacks.notifyStatusChanged(moveId, 16689 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16690 break; 16691 } 16692 } 16693 }; 16694 16695 final MoveInfo move; 16696 if (moveCompleteApp) { 16697 // Kick off a thread to report progress estimates 16698 new Thread() { 16699 @Override 16700 public void run() { 16701 while (true) { 16702 try { 16703 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16704 break; 16705 } 16706 } catch (InterruptedException ignored) { 16707 } 16708 16709 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16710 final int progress = 10 + (int) MathUtils.constrain( 16711 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16712 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16713 } 16714 } 16715 }.start(); 16716 16717 final String dataAppName = codeFile.getName(); 16718 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16719 dataAppName, appId, seinfo); 16720 } else { 16721 move = null; 16722 } 16723 16724 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16725 16726 final Message msg = mHandler.obtainMessage(INIT_COPY); 16727 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16728 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16729 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16730 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16731 msg.obj = params; 16732 16733 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16734 System.identityHashCode(msg.obj)); 16735 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16736 System.identityHashCode(msg.obj)); 16737 16738 mHandler.sendMessage(msg); 16739 } 16740 16741 @Override 16742 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16743 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16744 16745 final int realMoveId = mNextMoveId.getAndIncrement(); 16746 final Bundle extras = new Bundle(); 16747 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16748 mMoveCallbacks.notifyCreated(realMoveId, extras); 16749 16750 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16751 @Override 16752 public void onCreated(int moveId, Bundle extras) { 16753 // Ignored 16754 } 16755 16756 @Override 16757 public void onStatusChanged(int moveId, int status, long estMillis) { 16758 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16759 } 16760 }; 16761 16762 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16763 storage.setPrimaryStorageUuid(volumeUuid, callback); 16764 return realMoveId; 16765 } 16766 16767 @Override 16768 public int getMoveStatus(int moveId) { 16769 mContext.enforceCallingOrSelfPermission( 16770 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16771 return mMoveCallbacks.mLastStatus.get(moveId); 16772 } 16773 16774 @Override 16775 public void registerMoveCallback(IPackageMoveObserver callback) { 16776 mContext.enforceCallingOrSelfPermission( 16777 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16778 mMoveCallbacks.register(callback); 16779 } 16780 16781 @Override 16782 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16783 mContext.enforceCallingOrSelfPermission( 16784 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16785 mMoveCallbacks.unregister(callback); 16786 } 16787 16788 @Override 16789 public boolean setInstallLocation(int loc) { 16790 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16791 null); 16792 if (getInstallLocation() == loc) { 16793 return true; 16794 } 16795 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16796 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16797 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16798 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16799 return true; 16800 } 16801 return false; 16802 } 16803 16804 @Override 16805 public int getInstallLocation() { 16806 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16807 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16808 PackageHelper.APP_INSTALL_AUTO); 16809 } 16810 16811 /** Called by UserManagerService */ 16812 void cleanUpUser(UserManagerService userManager, int userHandle) { 16813 synchronized (mPackages) { 16814 mDirtyUsers.remove(userHandle); 16815 mUserNeedsBadging.delete(userHandle); 16816 mSettings.removeUserLPw(userHandle); 16817 mPendingBroadcasts.remove(userHandle); 16818 } 16819 synchronized (mInstallLock) { 16820 if (mInstaller != null) { 16821 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16822 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16823 final String volumeUuid = vol.getFsUuid(); 16824 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16825 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16826 } 16827 } 16828 synchronized (mPackages) { 16829 removeUnusedPackagesLILPw(userManager, userHandle); 16830 } 16831 } 16832 } 16833 16834 /** 16835 * We're removing userHandle and would like to remove any downloaded packages 16836 * that are no longer in use by any other user. 16837 * @param userHandle the user being removed 16838 */ 16839 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16840 final boolean DEBUG_CLEAN_APKS = false; 16841 int [] users = userManager.getUserIds(); 16842 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16843 while (psit.hasNext()) { 16844 PackageSetting ps = psit.next(); 16845 if (ps.pkg == null) { 16846 continue; 16847 } 16848 final String packageName = ps.pkg.packageName; 16849 // Skip over if system app 16850 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16851 continue; 16852 } 16853 if (DEBUG_CLEAN_APKS) { 16854 Slog.i(TAG, "Checking package " + packageName); 16855 } 16856 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16857 if (keep) { 16858 if (DEBUG_CLEAN_APKS) { 16859 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16860 } 16861 } else { 16862 for (int i = 0; i < users.length; i++) { 16863 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16864 keep = true; 16865 if (DEBUG_CLEAN_APKS) { 16866 Slog.i(TAG, " Keeping package " + packageName + " for user " 16867 + users[i]); 16868 } 16869 break; 16870 } 16871 } 16872 } 16873 if (!keep) { 16874 if (DEBUG_CLEAN_APKS) { 16875 Slog.i(TAG, " Removing package " + packageName); 16876 } 16877 mHandler.post(new Runnable() { 16878 public void run() { 16879 deletePackageX(packageName, userHandle, 0); 16880 } //end run 16881 }); 16882 } 16883 } 16884 } 16885 16886 /** Called by UserManagerService */ 16887 void createNewUser(int userHandle) { 16888 if (mInstaller != null) { 16889 synchronized (mInstallLock) { 16890 synchronized (mPackages) { 16891 mInstaller.createUserConfig(userHandle); 16892 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16893 } 16894 } 16895 synchronized (mPackages) { 16896 applyFactoryDefaultBrowserLPw(userHandle); 16897 primeDomainVerificationsLPw(userHandle); 16898 } 16899 } 16900 } 16901 16902 void newUserCreated(final int userHandle) { 16903 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16904 // If permission review for legacy apps is required, we represent 16905 // dagerous permissions for such apps as always granted runtime 16906 // permissions to keep per user flag state whether review is needed. 16907 // Hence, if a new user is added we have to propagate dangerous 16908 // permission grants for these legacy apps. 16909 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 16910 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 16911 | UPDATE_PERMISSIONS_REPLACE_ALL); 16912 } 16913 } 16914 16915 @Override 16916 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16917 mContext.enforceCallingOrSelfPermission( 16918 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16919 "Only package verification agents can read the verifier device identity"); 16920 16921 synchronized (mPackages) { 16922 return mSettings.getVerifierDeviceIdentityLPw(); 16923 } 16924 } 16925 16926 @Override 16927 public void setPermissionEnforced(String permission, boolean enforced) { 16928 // TODO: Now that we no longer change GID for storage, this should to away. 16929 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16930 "setPermissionEnforced"); 16931 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16932 synchronized (mPackages) { 16933 if (mSettings.mReadExternalStorageEnforced == null 16934 || mSettings.mReadExternalStorageEnforced != enforced) { 16935 mSettings.mReadExternalStorageEnforced = enforced; 16936 mSettings.writeLPr(); 16937 } 16938 } 16939 // kill any non-foreground processes so we restart them and 16940 // grant/revoke the GID. 16941 final IActivityManager am = ActivityManagerNative.getDefault(); 16942 if (am != null) { 16943 final long token = Binder.clearCallingIdentity(); 16944 try { 16945 am.killProcessesBelowForeground("setPermissionEnforcement"); 16946 } catch (RemoteException e) { 16947 } finally { 16948 Binder.restoreCallingIdentity(token); 16949 } 16950 } 16951 } else { 16952 throw new IllegalArgumentException("No selective enforcement for " + permission); 16953 } 16954 } 16955 16956 @Override 16957 @Deprecated 16958 public boolean isPermissionEnforced(String permission) { 16959 return true; 16960 } 16961 16962 @Override 16963 public boolean isStorageLow() { 16964 final long token = Binder.clearCallingIdentity(); 16965 try { 16966 final DeviceStorageMonitorInternal 16967 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16968 if (dsm != null) { 16969 return dsm.isMemoryLow(); 16970 } else { 16971 return false; 16972 } 16973 } finally { 16974 Binder.restoreCallingIdentity(token); 16975 } 16976 } 16977 16978 @Override 16979 public IPackageInstaller getPackageInstaller() { 16980 return mInstallerService; 16981 } 16982 16983 private boolean userNeedsBadging(int userId) { 16984 int index = mUserNeedsBadging.indexOfKey(userId); 16985 if (index < 0) { 16986 final UserInfo userInfo; 16987 final long token = Binder.clearCallingIdentity(); 16988 try { 16989 userInfo = sUserManager.getUserInfo(userId); 16990 } finally { 16991 Binder.restoreCallingIdentity(token); 16992 } 16993 final boolean b; 16994 if (userInfo != null && userInfo.isManagedProfile()) { 16995 b = true; 16996 } else { 16997 b = false; 16998 } 16999 mUserNeedsBadging.put(userId, b); 17000 return b; 17001 } 17002 return mUserNeedsBadging.valueAt(index); 17003 } 17004 17005 @Override 17006 public KeySet getKeySetByAlias(String packageName, String alias) { 17007 if (packageName == null || alias == null) { 17008 return null; 17009 } 17010 synchronized(mPackages) { 17011 final PackageParser.Package pkg = mPackages.get(packageName); 17012 if (pkg == null) { 17013 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17014 throw new IllegalArgumentException("Unknown package: " + packageName); 17015 } 17016 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17017 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17018 } 17019 } 17020 17021 @Override 17022 public KeySet getSigningKeySet(String packageName) { 17023 if (packageName == null) { 17024 return null; 17025 } 17026 synchronized(mPackages) { 17027 final PackageParser.Package pkg = mPackages.get(packageName); 17028 if (pkg == null) { 17029 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17030 throw new IllegalArgumentException("Unknown package: " + packageName); 17031 } 17032 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17033 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17034 throw new SecurityException("May not access signing KeySet of other apps."); 17035 } 17036 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17037 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17038 } 17039 } 17040 17041 @Override 17042 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17043 if (packageName == null || ks == null) { 17044 return false; 17045 } 17046 synchronized(mPackages) { 17047 final PackageParser.Package pkg = mPackages.get(packageName); 17048 if (pkg == null) { 17049 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17050 throw new IllegalArgumentException("Unknown package: " + packageName); 17051 } 17052 IBinder ksh = ks.getToken(); 17053 if (ksh instanceof KeySetHandle) { 17054 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17055 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17056 } 17057 return false; 17058 } 17059 } 17060 17061 @Override 17062 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17063 if (packageName == null || ks == null) { 17064 return false; 17065 } 17066 synchronized(mPackages) { 17067 final PackageParser.Package pkg = mPackages.get(packageName); 17068 if (pkg == null) { 17069 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17070 throw new IllegalArgumentException("Unknown package: " + packageName); 17071 } 17072 IBinder ksh = ks.getToken(); 17073 if (ksh instanceof KeySetHandle) { 17074 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17075 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17076 } 17077 return false; 17078 } 17079 } 17080 17081 private void deletePackageIfUnusedLPr(final String packageName) { 17082 PackageSetting ps = mSettings.mPackages.get(packageName); 17083 if (ps == null) { 17084 return; 17085 } 17086 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17087 // TODO Implement atomic delete if package is unused 17088 // It is currently possible that the package will be deleted even if it is installed 17089 // after this method returns. 17090 mHandler.post(new Runnable() { 17091 public void run() { 17092 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17093 } 17094 }); 17095 } 17096 } 17097 17098 /** 17099 * Check and throw if the given before/after packages would be considered a 17100 * downgrade. 17101 */ 17102 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17103 throws PackageManagerException { 17104 if (after.versionCode < before.mVersionCode) { 17105 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17106 "Update version code " + after.versionCode + " is older than current " 17107 + before.mVersionCode); 17108 } else if (after.versionCode == before.mVersionCode) { 17109 if (after.baseRevisionCode < before.baseRevisionCode) { 17110 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17111 "Update base revision code " + after.baseRevisionCode 17112 + " is older than current " + before.baseRevisionCode); 17113 } 17114 17115 if (!ArrayUtils.isEmpty(after.splitNames)) { 17116 for (int i = 0; i < after.splitNames.length; i++) { 17117 final String splitName = after.splitNames[i]; 17118 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17119 if (j != -1) { 17120 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17121 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17122 "Update split " + splitName + " revision code " 17123 + after.splitRevisionCodes[i] + " is older than current " 17124 + before.splitRevisionCodes[j]); 17125 } 17126 } 17127 } 17128 } 17129 } 17130 } 17131 17132 private static class MoveCallbacks extends Handler { 17133 private static final int MSG_CREATED = 1; 17134 private static final int MSG_STATUS_CHANGED = 2; 17135 17136 private final RemoteCallbackList<IPackageMoveObserver> 17137 mCallbacks = new RemoteCallbackList<>(); 17138 17139 private final SparseIntArray mLastStatus = new SparseIntArray(); 17140 17141 public MoveCallbacks(Looper looper) { 17142 super(looper); 17143 } 17144 17145 public void register(IPackageMoveObserver callback) { 17146 mCallbacks.register(callback); 17147 } 17148 17149 public void unregister(IPackageMoveObserver callback) { 17150 mCallbacks.unregister(callback); 17151 } 17152 17153 @Override 17154 public void handleMessage(Message msg) { 17155 final SomeArgs args = (SomeArgs) msg.obj; 17156 final int n = mCallbacks.beginBroadcast(); 17157 for (int i = 0; i < n; i++) { 17158 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17159 try { 17160 invokeCallback(callback, msg.what, args); 17161 } catch (RemoteException ignored) { 17162 } 17163 } 17164 mCallbacks.finishBroadcast(); 17165 args.recycle(); 17166 } 17167 17168 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17169 throws RemoteException { 17170 switch (what) { 17171 case MSG_CREATED: { 17172 callback.onCreated(args.argi1, (Bundle) args.arg2); 17173 break; 17174 } 17175 case MSG_STATUS_CHANGED: { 17176 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17177 break; 17178 } 17179 } 17180 } 17181 17182 private void notifyCreated(int moveId, Bundle extras) { 17183 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17184 17185 final SomeArgs args = SomeArgs.obtain(); 17186 args.argi1 = moveId; 17187 args.arg2 = extras; 17188 obtainMessage(MSG_CREATED, args).sendToTarget(); 17189 } 17190 17191 private void notifyStatusChanged(int moveId, int status) { 17192 notifyStatusChanged(moveId, status, -1); 17193 } 17194 17195 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17196 Slog.v(TAG, "Move " + moveId + " status " + status); 17197 17198 final SomeArgs args = SomeArgs.obtain(); 17199 args.argi1 = moveId; 17200 args.argi2 = status; 17201 args.arg3 = estMillis; 17202 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17203 17204 synchronized (mLastStatus) { 17205 mLastStatus.put(moveId, status); 17206 } 17207 } 17208 } 17209 17210 private final class OnPermissionChangeListeners extends Handler { 17211 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17212 17213 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17214 new RemoteCallbackList<>(); 17215 17216 public OnPermissionChangeListeners(Looper looper) { 17217 super(looper); 17218 } 17219 17220 @Override 17221 public void handleMessage(Message msg) { 17222 switch (msg.what) { 17223 case MSG_ON_PERMISSIONS_CHANGED: { 17224 final int uid = msg.arg1; 17225 handleOnPermissionsChanged(uid); 17226 } break; 17227 } 17228 } 17229 17230 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17231 mPermissionListeners.register(listener); 17232 17233 } 17234 17235 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17236 mPermissionListeners.unregister(listener); 17237 } 17238 17239 public void onPermissionsChanged(int uid) { 17240 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17241 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17242 } 17243 } 17244 17245 private void handleOnPermissionsChanged(int uid) { 17246 final int count = mPermissionListeners.beginBroadcast(); 17247 try { 17248 for (int i = 0; i < count; i++) { 17249 IOnPermissionsChangeListener callback = mPermissionListeners 17250 .getBroadcastItem(i); 17251 try { 17252 callback.onPermissionsChanged(uid); 17253 } catch (RemoteException e) { 17254 Log.e(TAG, "Permission listener is dead", e); 17255 } 17256 } 17257 } finally { 17258 mPermissionListeners.finishBroadcast(); 17259 } 17260 } 17261 } 17262 17263 private class PackageManagerInternalImpl extends PackageManagerInternal { 17264 @Override 17265 public void setLocationPackagesProvider(PackagesProvider provider) { 17266 synchronized (mPackages) { 17267 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17268 } 17269 } 17270 17271 @Override 17272 public void setImePackagesProvider(PackagesProvider provider) { 17273 synchronized (mPackages) { 17274 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17275 } 17276 } 17277 17278 @Override 17279 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17280 synchronized (mPackages) { 17281 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17282 } 17283 } 17284 17285 @Override 17286 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17287 synchronized (mPackages) { 17288 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17289 } 17290 } 17291 17292 @Override 17293 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17294 synchronized (mPackages) { 17295 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17296 } 17297 } 17298 17299 @Override 17300 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17301 synchronized (mPackages) { 17302 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17303 } 17304 } 17305 17306 @Override 17307 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17308 synchronized (mPackages) { 17309 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17310 } 17311 } 17312 17313 @Override 17314 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17315 synchronized (mPackages) { 17316 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17317 packageName, userId); 17318 } 17319 } 17320 17321 @Override 17322 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17323 synchronized (mPackages) { 17324 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17325 packageName, userId); 17326 } 17327 } 17328 17329 @Override 17330 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17331 synchronized (mPackages) { 17332 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17333 packageName, userId); 17334 } 17335 } 17336 17337 @Override 17338 public void setKeepUninstalledPackages(final List<String> packageList) { 17339 Preconditions.checkNotNull(packageList); 17340 List<String> removedFromList = null; 17341 synchronized (mPackages) { 17342 if (mKeepUninstalledPackages != null) { 17343 final int packagesCount = mKeepUninstalledPackages.size(); 17344 for (int i = 0; i < packagesCount; i++) { 17345 String oldPackage = mKeepUninstalledPackages.get(i); 17346 if (packageList != null && packageList.contains(oldPackage)) { 17347 continue; 17348 } 17349 if (removedFromList == null) { 17350 removedFromList = new ArrayList<>(); 17351 } 17352 removedFromList.add(oldPackage); 17353 } 17354 } 17355 mKeepUninstalledPackages = new ArrayList<>(packageList); 17356 if (removedFromList != null) { 17357 final int removedCount = removedFromList.size(); 17358 for (int i = 0; i < removedCount; i++) { 17359 deletePackageIfUnusedLPr(removedFromList.get(i)); 17360 } 17361 } 17362 } 17363 } 17364 17365 @Override 17366 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17367 synchronized (mPackages) { 17368 // If we do not support permission review, done. 17369 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17370 return false; 17371 } 17372 17373 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17374 if (packageSetting == null) { 17375 return false; 17376 } 17377 17378 // Permission review applies only to apps not supporting the new permission model. 17379 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17380 return false; 17381 } 17382 17383 // Legacy apps have the permission and get user consent on launch. 17384 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17385 return permissionsState.isPermissionReviewRequired(userId); 17386 } 17387 } 17388 } 17389 17390 @Override 17391 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17392 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17393 synchronized (mPackages) { 17394 final long identity = Binder.clearCallingIdentity(); 17395 try { 17396 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17397 packageNames, userId); 17398 } finally { 17399 Binder.restoreCallingIdentity(identity); 17400 } 17401 } 17402 } 17403 17404 private static void enforceSystemOrPhoneCaller(String tag) { 17405 int callingUid = Binder.getCallingUid(); 17406 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17407 throw new SecurityException( 17408 "Cannot call " + tag + " from UID " + callingUid); 17409 } 17410 } 17411} 17412