PackageManagerService.java revision d8327bd864e52bbc6cc57e933488aa7e99654d4f
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_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 66import static android.content.pm.PackageManager.PERMISSION_DENIED; 67import static android.content.pm.PackageManager.PERMISSION_GRANTED; 68import static android.content.pm.PackageParser.isApkFile; 69import static android.os.Process.PACKAGE_INFO_GID; 70import static android.os.Process.SYSTEM_UID; 71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 72import static android.system.OsConstants.O_CREAT; 73import static android.system.OsConstants.O_RDWR; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 78import static com.android.internal.util.ArrayUtils.appendInt; 79import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 88 89import android.Manifest; 90import android.app.ActivityManager; 91import android.app.ActivityManagerNative; 92import android.app.AppGlobals; 93import android.app.IActivityManager; 94import android.app.admin.IDevicePolicyManager; 95import android.app.backup.IBackupManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.AppsQueryHelper; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.EphemeralResolveInfo; 212import com.android.internal.app.IMediaContainerService; 213import com.android.internal.app.ResolverActivity; 214import com.android.internal.content.NativeLibraryHelper; 215import com.android.internal.content.PackageHelper; 216import com.android.internal.os.IParcelFileDescriptorFactory; 217import com.android.internal.os.SomeArgs; 218import com.android.internal.os.Zygote; 219import com.android.internal.util.ArrayUtils; 220import com.android.internal.util.FastPrintWriter; 221import com.android.internal.util.FastXmlSerializer; 222import com.android.internal.util.IndentingPrintWriter; 223import com.android.internal.util.Preconditions; 224import com.android.server.EventLogTags; 225import com.android.server.FgThread; 226import com.android.server.IntentResolver; 227import com.android.server.LocalServices; 228import com.android.server.ServiceThread; 229import com.android.server.SystemConfig; 230import com.android.server.Watchdog; 231import com.android.server.pm.PermissionsState.PermissionState; 232import com.android.server.pm.Settings.DatabaseVersion; 233import com.android.server.pm.Settings.VersionInfo; 234import com.android.server.storage.DeviceStorageMonitorInternal; 235 236import org.xmlpull.v1.XmlPullParser; 237import org.xmlpull.v1.XmlPullParserException; 238import org.xmlpull.v1.XmlSerializer; 239 240import java.io.BufferedInputStream; 241import java.io.BufferedOutputStream; 242import java.io.BufferedReader; 243import java.io.ByteArrayInputStream; 244import java.io.ByteArrayOutputStream; 245import java.io.File; 246import java.io.FileDescriptor; 247import java.io.FileNotFoundException; 248import java.io.FileOutputStream; 249import java.io.FileReader; 250import java.io.FilenameFilter; 251import java.io.IOException; 252import java.io.InputStream; 253import java.io.PrintWriter; 254import java.nio.charset.StandardCharsets; 255import java.security.MessageDigest; 256import java.security.NoSuchAlgorithmException; 257import java.security.PublicKey; 258import java.security.cert.CertificateEncodingException; 259import java.security.cert.CertificateException; 260import java.text.SimpleDateFormat; 261import java.util.ArrayList; 262import java.util.Arrays; 263import java.util.Collection; 264import java.util.Collections; 265import java.util.Comparator; 266import java.util.Date; 267import java.util.Iterator; 268import java.util.List; 269import java.util.Map; 270import java.util.Objects; 271import java.util.Set; 272import java.util.concurrent.CountDownLatch; 273import java.util.concurrent.TimeUnit; 274import java.util.concurrent.atomic.AtomicBoolean; 275import java.util.concurrent.atomic.AtomicInteger; 276import java.util.concurrent.atomic.AtomicLong; 277 278/** 279 * Keep track of all those .apks everywhere. 280 * 281 * This is very central to the platform's security; please run the unit 282 * tests whenever making modifications here: 283 * 284runtest -c android.content.pm.PackageManagerTests frameworks-core 285 * 286 * {@hide} 287 */ 288public class PackageManagerService extends IPackageManager.Stub { 289 static final String TAG = "PackageManager"; 290 static final boolean DEBUG_SETTINGS = false; 291 static final boolean DEBUG_PREFERRED = false; 292 static final boolean DEBUG_UPGRADE = false; 293 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 294 private static final boolean DEBUG_BACKUP = false; 295 private static final boolean DEBUG_INSTALL = false; 296 private static final boolean DEBUG_REMOVE = false; 297 private static final boolean DEBUG_BROADCASTS = false; 298 private static final boolean DEBUG_SHOW_INFO = false; 299 private static final boolean DEBUG_PACKAGE_INFO = false; 300 private static final boolean DEBUG_INTENT_MATCHING = false; 301 private static final boolean DEBUG_PACKAGE_SCANNING = false; 302 private static final boolean DEBUG_VERIFY = false; 303 private static final boolean DEBUG_DEXOPT = false; 304 private static final boolean DEBUG_ABI_SELECTION = false; 305 private static final boolean DEBUG_EPHEMERAL = false; 306 307 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 308 309 private static final int RADIO_UID = Process.PHONE_UID; 310 private static final int LOG_UID = Process.LOG_UID; 311 private static final int NFC_UID = Process.NFC_UID; 312 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 313 private static final int SHELL_UID = Process.SHELL_UID; 314 315 // Cap the size of permission trees that 3rd party apps can define 316 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 317 318 // Suffix used during package installation when copying/moving 319 // package apks to install directory. 320 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 321 322 static final int SCAN_NO_DEX = 1<<1; 323 static final int SCAN_FORCE_DEX = 1<<2; 324 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 325 static final int SCAN_NEW_INSTALL = 1<<4; 326 static final int SCAN_NO_PATHS = 1<<5; 327 static final int SCAN_UPDATE_TIME = 1<<6; 328 static final int SCAN_DEFER_DEX = 1<<7; 329 static final int SCAN_BOOTING = 1<<8; 330 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 331 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 332 static final int SCAN_REPLACING = 1<<11; 333 static final int SCAN_REQUIRE_KNOWN = 1<<12; 334 static final int SCAN_MOVE = 1<<13; 335 static final int SCAN_INITIAL = 1<<14; 336 337 static final int REMOVE_CHATTY = 1<<16; 338 339 private static final int[] EMPTY_INT_ARRAY = new int[0]; 340 341 /** 342 * Timeout (in milliseconds) after which the watchdog should declare that 343 * our handler thread is wedged. The usual default for such things is one 344 * minute but we sometimes do very lengthy I/O operations on this thread, 345 * such as installing multi-gigabyte applications, so ours needs to be longer. 346 */ 347 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 348 349 /** 350 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 351 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 352 * settings entry if available, otherwise we use the hardcoded default. If it's been 353 * more than this long since the last fstrim, we force one during the boot sequence. 354 * 355 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 356 * one gets run at the next available charging+idle time. This final mandatory 357 * no-fstrim check kicks in only of the other scheduling criteria is never met. 358 */ 359 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 360 361 /** 362 * Whether verification is enabled by default. 363 */ 364 private static final boolean DEFAULT_VERIFY_ENABLE = true; 365 366 /** 367 * The default maximum time to wait for the verification agent to return in 368 * milliseconds. 369 */ 370 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 371 372 /** 373 * The default response for package verification timeout. 374 * 375 * This can be either PackageManager.VERIFICATION_ALLOW or 376 * PackageManager.VERIFICATION_REJECT. 377 */ 378 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 379 380 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 381 382 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 383 DEFAULT_CONTAINER_PACKAGE, 384 "com.android.defcontainer.DefaultContainerService"); 385 386 private static final String KILL_APP_REASON_GIDS_CHANGED = 387 "permission grant or revoke changed gids"; 388 389 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 390 "permissions revoked"; 391 392 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 393 394 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 395 396 /** Permission grant: not grant the permission. */ 397 private static final int GRANT_DENIED = 1; 398 399 /** Permission grant: grant the permission as an install permission. */ 400 private static final int GRANT_INSTALL = 2; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 3; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 4; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 final File mEphemeralInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 /** Component that knows whether or not an ephemeral application exists */ 602 final ComponentName mEphemeralResolverComponent; 603 /** The service connection to the ephemeral resolver */ 604 final EphemeralResolverConnection mEphemeralResolverConnection; 605 606 /** Component used to install ephemeral applications */ 607 final ComponentName mEphemeralInstallerComponent; 608 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 609 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 610 611 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 612 = new SparseArray<IntentFilterVerificationState>(); 613 614 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 615 new DefaultPermissionGrantPolicy(this); 616 617 // List of packages names to keep cached, even if they are uninstalled for all users 618 private List<String> mKeepUninstalledPackages; 619 620 private static class IFVerificationParams { 621 PackageParser.Package pkg; 622 boolean replacing; 623 int userId; 624 int verifierUid; 625 626 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 627 int _userId, int _verifierUid) { 628 pkg = _pkg; 629 replacing = _replacing; 630 userId = _userId; 631 replacing = _replacing; 632 verifierUid = _verifierUid; 633 } 634 } 635 636 private interface IntentFilterVerifier<T extends IntentFilter> { 637 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 638 T filter, String packageName); 639 void startVerifications(int userId); 640 void receiveVerificationResponse(int verificationId); 641 } 642 643 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 644 private Context mContext; 645 private ComponentName mIntentFilterVerifierComponent; 646 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 647 648 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 649 mContext = context; 650 mIntentFilterVerifierComponent = verifierComponent; 651 } 652 653 private String getDefaultScheme() { 654 return IntentFilter.SCHEME_HTTPS; 655 } 656 657 @Override 658 public void startVerifications(int userId) { 659 // Launch verifications requests 660 int count = mCurrentIntentFilterVerifications.size(); 661 for (int n=0; n<count; n++) { 662 int verificationId = mCurrentIntentFilterVerifications.get(n); 663 final IntentFilterVerificationState ivs = 664 mIntentFilterVerificationStates.get(verificationId); 665 666 String packageName = ivs.getPackageName(); 667 668 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 669 final int filterCount = filters.size(); 670 ArraySet<String> domainsSet = new ArraySet<>(); 671 for (int m=0; m<filterCount; m++) { 672 PackageParser.ActivityIntentInfo filter = filters.get(m); 673 domainsSet.addAll(filter.getHostsList()); 674 } 675 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 676 synchronized (mPackages) { 677 if (mSettings.createIntentFilterVerificationIfNeededLPw( 678 packageName, domainsList) != null) { 679 scheduleWriteSettingsLocked(); 680 } 681 } 682 sendVerificationRequest(userId, verificationId, ivs); 683 } 684 mCurrentIntentFilterVerifications.clear(); 685 } 686 687 private void sendVerificationRequest(int userId, int verificationId, 688 IntentFilterVerificationState ivs) { 689 690 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 691 verificationIntent.putExtra( 692 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 693 verificationId); 694 verificationIntent.putExtra( 695 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 696 getDefaultScheme()); 697 verificationIntent.putExtra( 698 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 699 ivs.getHostsString()); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 702 ivs.getPackageName()); 703 verificationIntent.setComponent(mIntentFilterVerifierComponent); 704 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 705 706 UserHandle user = new UserHandle(userId); 707 mContext.sendBroadcastAsUser(verificationIntent, user); 708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 709 "Sending IntentFilter verification broadcast"); 710 } 711 712 public void receiveVerificationResponse(int verificationId) { 713 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 714 715 final boolean verified = ivs.isVerified(); 716 717 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 718 final int count = filters.size(); 719 if (DEBUG_DOMAIN_VERIFICATION) { 720 Slog.i(TAG, "Received verification response " + verificationId 721 + " for " + count + " filters, verified=" + verified); 722 } 723 for (int n=0; n<count; n++) { 724 PackageParser.ActivityIntentInfo filter = filters.get(n); 725 filter.setVerified(verified); 726 727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 728 + " verified with result:" + verified + " and hosts:" 729 + ivs.getHostsString()); 730 } 731 732 mIntentFilterVerificationStates.remove(verificationId); 733 734 final String packageName = ivs.getPackageName(); 735 IntentFilterVerificationInfo ivi = null; 736 737 synchronized (mPackages) { 738 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 739 } 740 if (ivi == null) { 741 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 742 + verificationId + " packageName:" + packageName); 743 return; 744 } 745 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 746 "Updating IntentFilterVerificationInfo for package " + packageName 747 +" verificationId:" + verificationId); 748 749 synchronized (mPackages) { 750 if (verified) { 751 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 752 } else { 753 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 754 } 755 scheduleWriteSettingsLocked(); 756 757 final int userId = ivs.getUserId(); 758 if (userId != UserHandle.USER_ALL) { 759 final int userStatus = 760 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 761 762 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 763 boolean needUpdate = false; 764 765 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 766 // already been set by the User thru the Disambiguation dialog 767 switch (userStatus) { 768 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 769 if (verified) { 770 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 771 } else { 772 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 773 } 774 needUpdate = true; 775 break; 776 777 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 778 if (verified) { 779 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 780 needUpdate = true; 781 } 782 break; 783 784 default: 785 // Nothing to do 786 } 787 788 if (needUpdate) { 789 mSettings.updateIntentFilterVerificationStatusLPw( 790 packageName, updatedStatus, userId); 791 scheduleWritePackageRestrictionsLocked(userId); 792 } 793 } 794 } 795 } 796 797 @Override 798 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 799 ActivityIntentInfo filter, String packageName) { 800 if (!hasValidDomains(filter)) { 801 return false; 802 } 803 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 804 if (ivs == null) { 805 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 806 packageName); 807 } 808 if (DEBUG_DOMAIN_VERIFICATION) { 809 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 810 } 811 ivs.addFilter(filter); 812 return true; 813 } 814 815 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 816 int userId, int verificationId, String packageName) { 817 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 818 verifierUid, userId, packageName); 819 ivs.setPendingState(); 820 synchronized (mPackages) { 821 mIntentFilterVerificationStates.append(verificationId, ivs); 822 mCurrentIntentFilterVerifications.add(verificationId); 823 } 824 return ivs; 825 } 826 } 827 828 private static boolean hasValidDomains(ActivityIntentInfo filter) { 829 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 830 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 831 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 832 } 833 834 private IntentFilterVerifier mIntentFilterVerifier; 835 836 // Set of pending broadcasts for aggregating enable/disable of components. 837 static class PendingPackageBroadcasts { 838 // for each user id, a map of <package name -> components within that package> 839 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 840 841 public PendingPackageBroadcasts() { 842 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 843 } 844 845 public ArrayList<String> get(int userId, String packageName) { 846 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 847 return packages.get(packageName); 848 } 849 850 public void put(int userId, String packageName, ArrayList<String> components) { 851 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 852 packages.put(packageName, components); 853 } 854 855 public void remove(int userId, String packageName) { 856 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 857 if (packages != null) { 858 packages.remove(packageName); 859 } 860 } 861 862 public void remove(int userId) { 863 mUidMap.remove(userId); 864 } 865 866 public int userIdCount() { 867 return mUidMap.size(); 868 } 869 870 public int userIdAt(int n) { 871 return mUidMap.keyAt(n); 872 } 873 874 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 875 return mUidMap.get(userId); 876 } 877 878 public int size() { 879 // total number of pending broadcast entries across all userIds 880 int num = 0; 881 for (int i = 0; i< mUidMap.size(); i++) { 882 num += mUidMap.valueAt(i).size(); 883 } 884 return num; 885 } 886 887 public void clear() { 888 mUidMap.clear(); 889 } 890 891 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 892 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 893 if (map == null) { 894 map = new ArrayMap<String, ArrayList<String>>(); 895 mUidMap.put(userId, map); 896 } 897 return map; 898 } 899 } 900 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 901 902 // Service Connection to remote media container service to copy 903 // package uri's from external media onto secure containers 904 // or internal storage. 905 private IMediaContainerService mContainerService = null; 906 907 static final int SEND_PENDING_BROADCAST = 1; 908 static final int MCS_BOUND = 3; 909 static final int END_COPY = 4; 910 static final int INIT_COPY = 5; 911 static final int MCS_UNBIND = 6; 912 static final int START_CLEANING_PACKAGE = 7; 913 static final int FIND_INSTALL_LOC = 8; 914 static final int POST_INSTALL = 9; 915 static final int MCS_RECONNECT = 10; 916 static final int MCS_GIVE_UP = 11; 917 static final int UPDATED_MEDIA_STATUS = 12; 918 static final int WRITE_SETTINGS = 13; 919 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 920 static final int PACKAGE_VERIFIED = 15; 921 static final int CHECK_PENDING_VERIFICATION = 16; 922 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 923 static final int INTENT_FILTER_VERIFIED = 18; 924 925 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 926 927 // Delay time in millisecs 928 static final int BROADCAST_DELAY = 10 * 1000; 929 930 static UserManagerService sUserManager; 931 932 // Stores a list of users whose package restrictions file needs to be updated 933 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 934 935 final private DefaultContainerConnection mDefContainerConn = 936 new DefaultContainerConnection(); 937 class DefaultContainerConnection implements ServiceConnection { 938 public void onServiceConnected(ComponentName name, IBinder service) { 939 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 940 IMediaContainerService imcs = 941 IMediaContainerService.Stub.asInterface(service); 942 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 943 } 944 945 public void onServiceDisconnected(ComponentName name) { 946 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 947 } 948 } 949 950 // Recordkeeping of restore-after-install operations that are currently in flight 951 // between the Package Manager and the Backup Manager 952 class PostInstallData { 953 public InstallArgs args; 954 public PackageInstalledInfo res; 955 956 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 957 args = _a; 958 res = _r; 959 } 960 } 961 962 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 963 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 964 965 // XML tags for backup/restore of various bits of state 966 private static final String TAG_PREFERRED_BACKUP = "pa"; 967 private static final String TAG_DEFAULT_APPS = "da"; 968 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 969 970 final String mRequiredVerifierPackage; 971 final String mRequiredInstallerPackage; 972 973 private final PackageUsage mPackageUsage = new PackageUsage(); 974 975 private class PackageUsage { 976 private static final int WRITE_INTERVAL 977 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 978 979 private final Object mFileLock = new Object(); 980 private final AtomicLong mLastWritten = new AtomicLong(0); 981 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 982 983 private boolean mIsHistoricalPackageUsageAvailable = true; 984 985 boolean isHistoricalPackageUsageAvailable() { 986 return mIsHistoricalPackageUsageAvailable; 987 } 988 989 void write(boolean force) { 990 if (force) { 991 writeInternal(); 992 return; 993 } 994 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 995 && !DEBUG_DEXOPT) { 996 return; 997 } 998 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 999 new Thread("PackageUsage_DiskWriter") { 1000 @Override 1001 public void run() { 1002 try { 1003 writeInternal(); 1004 } finally { 1005 mBackgroundWriteRunning.set(false); 1006 } 1007 } 1008 }.start(); 1009 } 1010 } 1011 1012 private void writeInternal() { 1013 synchronized (mPackages) { 1014 synchronized (mFileLock) { 1015 AtomicFile file = getFile(); 1016 FileOutputStream f = null; 1017 try { 1018 f = file.startWrite(); 1019 BufferedOutputStream out = new BufferedOutputStream(f); 1020 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1021 StringBuilder sb = new StringBuilder(); 1022 for (PackageParser.Package pkg : mPackages.values()) { 1023 if (pkg.mLastPackageUsageTimeInMills == 0) { 1024 continue; 1025 } 1026 sb.setLength(0); 1027 sb.append(pkg.packageName); 1028 sb.append(' '); 1029 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1030 sb.append('\n'); 1031 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1032 } 1033 out.flush(); 1034 file.finishWrite(f); 1035 } catch (IOException e) { 1036 if (f != null) { 1037 file.failWrite(f); 1038 } 1039 Log.e(TAG, "Failed to write package usage times", e); 1040 } 1041 } 1042 } 1043 mLastWritten.set(SystemClock.elapsedRealtime()); 1044 } 1045 1046 void readLP() { 1047 synchronized (mFileLock) { 1048 AtomicFile file = getFile(); 1049 BufferedInputStream in = null; 1050 try { 1051 in = new BufferedInputStream(file.openRead()); 1052 StringBuffer sb = new StringBuffer(); 1053 while (true) { 1054 String packageName = readToken(in, sb, ' '); 1055 if (packageName == null) { 1056 break; 1057 } 1058 String timeInMillisString = readToken(in, sb, '\n'); 1059 if (timeInMillisString == null) { 1060 throw new IOException("Failed to find last usage time for package " 1061 + packageName); 1062 } 1063 PackageParser.Package pkg = mPackages.get(packageName); 1064 if (pkg == null) { 1065 continue; 1066 } 1067 long timeInMillis; 1068 try { 1069 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1070 } catch (NumberFormatException e) { 1071 throw new IOException("Failed to parse " + timeInMillisString 1072 + " as a long.", e); 1073 } 1074 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1075 } 1076 } catch (FileNotFoundException expected) { 1077 mIsHistoricalPackageUsageAvailable = false; 1078 } catch (IOException e) { 1079 Log.w(TAG, "Failed to read package usage times", e); 1080 } finally { 1081 IoUtils.closeQuietly(in); 1082 } 1083 } 1084 mLastWritten.set(SystemClock.elapsedRealtime()); 1085 } 1086 1087 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1088 throws IOException { 1089 sb.setLength(0); 1090 while (true) { 1091 int ch = in.read(); 1092 if (ch == -1) { 1093 if (sb.length() == 0) { 1094 return null; 1095 } 1096 throw new IOException("Unexpected EOF"); 1097 } 1098 if (ch == endOfToken) { 1099 return sb.toString(); 1100 } 1101 sb.append((char)ch); 1102 } 1103 } 1104 1105 private AtomicFile getFile() { 1106 File dataDir = Environment.getDataDirectory(); 1107 File systemDir = new File(dataDir, "system"); 1108 File fname = new File(systemDir, "package-usage.list"); 1109 return new AtomicFile(fname); 1110 } 1111 } 1112 1113 class PackageHandler extends Handler { 1114 private boolean mBound = false; 1115 final ArrayList<HandlerParams> mPendingInstalls = 1116 new ArrayList<HandlerParams>(); 1117 1118 private boolean connectToService() { 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1120 " DefaultContainerService"); 1121 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1124 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 mBound = true; 1127 return true; 1128 } 1129 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1130 return false; 1131 } 1132 1133 private void disconnectService() { 1134 mContainerService = null; 1135 mBound = false; 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1137 mContext.unbindService(mDefContainerConn); 1138 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1139 } 1140 1141 PackageHandler(Looper looper) { 1142 super(looper); 1143 } 1144 1145 public void handleMessage(Message msg) { 1146 try { 1147 doHandleMessage(msg); 1148 } finally { 1149 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1150 } 1151 } 1152 1153 void doHandleMessage(Message msg) { 1154 switch (msg.what) { 1155 case INIT_COPY: { 1156 HandlerParams params = (HandlerParams) msg.obj; 1157 int idx = mPendingInstalls.size(); 1158 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1159 // If a bind was already initiated we dont really 1160 // need to do anything. The pending install 1161 // will be processed later on. 1162 if (!mBound) { 1163 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1164 System.identityHashCode(mHandler)); 1165 // If this is the only one pending we might 1166 // have to bind to the service again. 1167 if (!connectToService()) { 1168 Slog.e(TAG, "Failed to bind to media container service"); 1169 params.serviceError(); 1170 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1171 System.identityHashCode(mHandler)); 1172 if (params.traceMethod != null) { 1173 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1174 params.traceCookie); 1175 } 1176 return; 1177 } else { 1178 // Once we bind to the service, the first 1179 // pending request will be processed. 1180 mPendingInstalls.add(idx, params); 1181 } 1182 } else { 1183 mPendingInstalls.add(idx, params); 1184 // Already bound to the service. Just make 1185 // sure we trigger off processing the first request. 1186 if (idx == 0) { 1187 mHandler.sendEmptyMessage(MCS_BOUND); 1188 } 1189 } 1190 break; 1191 } 1192 case MCS_BOUND: { 1193 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1194 if (msg.obj != null) { 1195 mContainerService = (IMediaContainerService) msg.obj; 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1197 System.identityHashCode(mHandler)); 1198 } 1199 if (mContainerService == null) { 1200 if (!mBound) { 1201 // Something seriously wrong since we are not bound and we are not 1202 // waiting for connection. Bail out. 1203 Slog.e(TAG, "Cannot bind to media container service"); 1204 for (HandlerParams params : mPendingInstalls) { 1205 // Indicate service bind error 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1208 System.identityHashCode(params)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1211 params.traceMethod, params.traceCookie); 1212 } 1213 return; 1214 } 1215 mPendingInstalls.clear(); 1216 } else { 1217 Slog.w(TAG, "Waiting to connect to media container service"); 1218 } 1219 } else if (mPendingInstalls.size() > 0) { 1220 HandlerParams params = mPendingInstalls.get(0); 1221 if (params != null) { 1222 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1223 System.identityHashCode(params)); 1224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1225 if (params.startCopy()) { 1226 // We are done... look for more work or to 1227 // go idle. 1228 if (DEBUG_SD_INSTALL) Log.i(TAG, 1229 "Checking for more work or unbind..."); 1230 // Delete pending install 1231 if (mPendingInstalls.size() > 0) { 1232 mPendingInstalls.remove(0); 1233 } 1234 if (mPendingInstalls.size() == 0) { 1235 if (mBound) { 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Posting delayed MCS_UNBIND"); 1238 removeMessages(MCS_UNBIND); 1239 Message ubmsg = obtainMessage(MCS_UNBIND); 1240 // Unbind after a little delay, to avoid 1241 // continual thrashing. 1242 sendMessageDelayed(ubmsg, 10000); 1243 } 1244 } else { 1245 // There are more pending requests in queue. 1246 // Just post MCS_BOUND message to trigger processing 1247 // of next pending install. 1248 if (DEBUG_SD_INSTALL) Log.i(TAG, 1249 "Posting MCS_BOUND for next work"); 1250 mHandler.sendEmptyMessage(MCS_BOUND); 1251 } 1252 } 1253 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1254 } 1255 } else { 1256 // Should never happen ideally. 1257 Slog.w(TAG, "Empty queue"); 1258 } 1259 break; 1260 } 1261 case MCS_RECONNECT: { 1262 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1263 if (mPendingInstalls.size() > 0) { 1264 if (mBound) { 1265 disconnectService(); 1266 } 1267 if (!connectToService()) { 1268 Slog.e(TAG, "Failed to bind to media container service"); 1269 for (HandlerParams params : mPendingInstalls) { 1270 // Indicate service bind error 1271 params.serviceError(); 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1273 System.identityHashCode(params)); 1274 } 1275 mPendingInstalls.clear(); 1276 } 1277 } 1278 break; 1279 } 1280 case MCS_UNBIND: { 1281 // If there is no actual work left, then time to unbind. 1282 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1283 1284 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1285 if (mBound) { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1287 1288 disconnectService(); 1289 } 1290 } else if (mPendingInstalls.size() > 0) { 1291 // There are more pending requests in queue. 1292 // Just post MCS_BOUND message to trigger processing 1293 // of next pending install. 1294 mHandler.sendEmptyMessage(MCS_BOUND); 1295 } 1296 1297 break; 1298 } 1299 case MCS_GIVE_UP: { 1300 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1301 HandlerParams params = mPendingInstalls.remove(0); 1302 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1303 System.identityHashCode(params)); 1304 break; 1305 } 1306 case SEND_PENDING_BROADCAST: { 1307 String packages[]; 1308 ArrayList<String> components[]; 1309 int size = 0; 1310 int uids[]; 1311 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1312 synchronized (mPackages) { 1313 if (mPendingBroadcasts == null) { 1314 return; 1315 } 1316 size = mPendingBroadcasts.size(); 1317 if (size <= 0) { 1318 // Nothing to be done. Just return 1319 return; 1320 } 1321 packages = new String[size]; 1322 components = new ArrayList[size]; 1323 uids = new int[size]; 1324 int i = 0; // filling out the above arrays 1325 1326 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1327 int packageUserId = mPendingBroadcasts.userIdAt(n); 1328 Iterator<Map.Entry<String, ArrayList<String>>> it 1329 = mPendingBroadcasts.packagesForUserId(packageUserId) 1330 .entrySet().iterator(); 1331 while (it.hasNext() && i < size) { 1332 Map.Entry<String, ArrayList<String>> ent = it.next(); 1333 packages[i] = ent.getKey(); 1334 components[i] = ent.getValue(); 1335 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1336 uids[i] = (ps != null) 1337 ? UserHandle.getUid(packageUserId, ps.appId) 1338 : -1; 1339 i++; 1340 } 1341 } 1342 size = i; 1343 mPendingBroadcasts.clear(); 1344 } 1345 // Send broadcasts 1346 for (int i = 0; i < size; i++) { 1347 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1348 } 1349 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1350 break; 1351 } 1352 case START_CLEANING_PACKAGE: { 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 final String packageName = (String)msg.obj; 1355 final int userId = msg.arg1; 1356 final boolean andCode = msg.arg2 != 0; 1357 synchronized (mPackages) { 1358 if (userId == UserHandle.USER_ALL) { 1359 int[] users = sUserManager.getUserIds(); 1360 for (int user : users) { 1361 mSettings.addPackageToCleanLPw( 1362 new PackageCleanItem(user, packageName, andCode)); 1363 } 1364 } else { 1365 mSettings.addPackageToCleanLPw( 1366 new PackageCleanItem(userId, packageName, andCode)); 1367 } 1368 } 1369 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1370 startCleaningPackages(); 1371 } break; 1372 case POST_INSTALL: { 1373 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1374 1375 PostInstallData data = mRunningInstalls.get(msg.arg1); 1376 mRunningInstalls.delete(msg.arg1); 1377 boolean deleteOld = false; 1378 1379 if (data != null) { 1380 InstallArgs args = data.args; 1381 PackageInstalledInfo res = data.res; 1382 1383 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1384 final String packageName = res.pkg.applicationInfo.packageName; 1385 res.removedInfo.sendBroadcast(false, true, false); 1386 Bundle extras = new Bundle(1); 1387 extras.putInt(Intent.EXTRA_UID, res.uid); 1388 1389 // Now that we successfully installed the package, grant runtime 1390 // permissions if requested before broadcasting the install. 1391 if ((args.installFlags 1392 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1393 && res.pkg.applicationInfo.targetSdkVersion 1394 >= Build.VERSION_CODES.M) { 1395 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1396 args.installGrantPermissions); 1397 } 1398 1399 // Determine the set of users who are adding this 1400 // package for the first time vs. those who are seeing 1401 // an update. 1402 int[] firstUsers; 1403 int[] updateUsers = new int[0]; 1404 if (res.origUsers == null || res.origUsers.length == 0) { 1405 firstUsers = res.newUsers; 1406 } else { 1407 firstUsers = new int[0]; 1408 for (int i=0; i<res.newUsers.length; i++) { 1409 int user = res.newUsers[i]; 1410 boolean isNew = true; 1411 for (int j=0; j<res.origUsers.length; j++) { 1412 if (res.origUsers[j] == user) { 1413 isNew = false; 1414 break; 1415 } 1416 } 1417 if (isNew) { 1418 int[] newFirst = new int[firstUsers.length+1]; 1419 System.arraycopy(firstUsers, 0, newFirst, 0, 1420 firstUsers.length); 1421 newFirst[firstUsers.length] = user; 1422 firstUsers = newFirst; 1423 } else { 1424 int[] newUpdate = new int[updateUsers.length+1]; 1425 System.arraycopy(updateUsers, 0, newUpdate, 0, 1426 updateUsers.length); 1427 newUpdate[updateUsers.length] = user; 1428 updateUsers = newUpdate; 1429 } 1430 } 1431 } 1432 // don't broadcast for ephemeral installs/updates 1433 final boolean isEphemeral = isEphemeral(res.pkg); 1434 if (!isEphemeral) { 1435 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1436 extras, 0 /*flags*/, null /*targetPackage*/, 1437 null /*finishedReceiver*/, firstUsers); 1438 } 1439 final boolean update = res.removedInfo.removedPackage != null; 1440 if (update) { 1441 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1442 } 1443 if (!isEphemeral) { 1444 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1445 extras, 0 /*flags*/, null /*targetPackage*/, 1446 null /*finishedReceiver*/, updateUsers); 1447 } 1448 if (update) { 1449 if (!isEphemeral) { 1450 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1451 packageName, extras, 0 /*flags*/, 1452 null /*targetPackage*/, null /*finishedReceiver*/, 1453 updateUsers); 1454 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1455 null /*package*/, null /*extras*/, 0 /*flags*/, 1456 packageName /*targetPackage*/, 1457 null /*finishedReceiver*/, updateUsers); 1458 } 1459 1460 // treat asec-hosted packages like removable media on upgrade 1461 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1462 if (DEBUG_INSTALL) { 1463 Slog.i(TAG, "upgrading pkg " + res.pkg 1464 + " is ASEC-hosted -> AVAILABLE"); 1465 } 1466 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1467 ArrayList<String> pkgList = new ArrayList<String>(1); 1468 pkgList.add(packageName); 1469 sendResourcesChangedBroadcast(true, true, 1470 pkgList,uidArray, null); 1471 } 1472 } 1473 if (res.removedInfo.args != null) { 1474 // Remove the replaced package's older resources safely now 1475 deleteOld = true; 1476 } 1477 1478 // If this app is a browser and it's newly-installed for some 1479 // users, clear any default-browser state in those users 1480 if (firstUsers.length > 0) { 1481 // the app's nature doesn't depend on the user, so we can just 1482 // check its browser nature in any user and generalize. 1483 if (packageIsBrowser(packageName, firstUsers[0])) { 1484 synchronized (mPackages) { 1485 for (int userId : firstUsers) { 1486 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1487 } 1488 } 1489 } 1490 } 1491 // Log current value of "unknown sources" setting 1492 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1493 getUnknownSourcesSettings()); 1494 } 1495 // Force a gc to clear up things 1496 Runtime.getRuntime().gc(); 1497 // We delete after a gc for applications on sdcard. 1498 if (deleteOld) { 1499 synchronized (mInstallLock) { 1500 res.removedInfo.args.doPostDeleteLI(true); 1501 } 1502 } 1503 if (args.observer != null) { 1504 try { 1505 Bundle extras = extrasForInstallResult(res); 1506 args.observer.onPackageInstalled(res.name, res.returnCode, 1507 res.returnMsg, extras); 1508 } catch (RemoteException e) { 1509 Slog.i(TAG, "Observer no longer exists."); 1510 } 1511 } 1512 if (args.traceMethod != null) { 1513 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1514 args.traceCookie); 1515 } 1516 return; 1517 } else { 1518 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1519 } 1520 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1522 } break; 1523 case UPDATED_MEDIA_STATUS: { 1524 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1525 boolean reportStatus = msg.arg1 == 1; 1526 boolean doGc = msg.arg2 == 1; 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1528 if (doGc) { 1529 // Force a gc to clear up stale containers. 1530 Runtime.getRuntime().gc(); 1531 } 1532 if (msg.obj != null) { 1533 @SuppressWarnings("unchecked") 1534 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1536 // Unload containers 1537 unloadAllContainers(args); 1538 } 1539 if (reportStatus) { 1540 try { 1541 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1542 PackageHelper.getMountService().finishMediaUpdate(); 1543 } catch (RemoteException e) { 1544 Log.e(TAG, "MountService not running?"); 1545 } 1546 } 1547 } break; 1548 case WRITE_SETTINGS: { 1549 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1550 synchronized (mPackages) { 1551 removeMessages(WRITE_SETTINGS); 1552 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1553 mSettings.writeLPr(); 1554 mDirtyUsers.clear(); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 } break; 1558 case WRITE_PACKAGE_RESTRICTIONS: { 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1560 synchronized (mPackages) { 1561 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1562 for (int userId : mDirtyUsers) { 1563 mSettings.writePackageRestrictionsLPr(userId); 1564 } 1565 mDirtyUsers.clear(); 1566 } 1567 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1568 } break; 1569 case CHECK_PENDING_VERIFICATION: { 1570 final int verificationId = msg.arg1; 1571 final PackageVerificationState state = mPendingVerification.get(verificationId); 1572 1573 if ((state != null) && !state.timeoutExtended()) { 1574 final InstallArgs args = state.getInstallArgs(); 1575 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1576 1577 Slog.i(TAG, "Verification timed out for " + originUri); 1578 mPendingVerification.remove(verificationId); 1579 1580 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1581 1582 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1583 Slog.i(TAG, "Continuing with installation of " + originUri); 1584 state.setVerifierResponse(Binder.getCallingUid(), 1585 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1586 broadcastPackageVerified(verificationId, originUri, 1587 PackageManager.VERIFICATION_ALLOW, 1588 state.getInstallArgs().getUser()); 1589 try { 1590 ret = args.copyApk(mContainerService, true); 1591 } catch (RemoteException e) { 1592 Slog.e(TAG, "Could not contact the ContainerService"); 1593 } 1594 } else { 1595 broadcastPackageVerified(verificationId, originUri, 1596 PackageManager.VERIFICATION_REJECT, 1597 state.getInstallArgs().getUser()); 1598 } 1599 1600 Trace.asyncTraceEnd( 1601 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1602 1603 processPendingInstall(args, ret); 1604 mHandler.sendEmptyMessage(MCS_UNBIND); 1605 } 1606 break; 1607 } 1608 case PACKAGE_VERIFIED: { 1609 final int verificationId = msg.arg1; 1610 1611 final PackageVerificationState state = mPendingVerification.get(verificationId); 1612 if (state == null) { 1613 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1614 break; 1615 } 1616 1617 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1618 1619 state.setVerifierResponse(response.callerUid, response.code); 1620 1621 if (state.isVerificationComplete()) { 1622 mPendingVerification.remove(verificationId); 1623 1624 final InstallArgs args = state.getInstallArgs(); 1625 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1626 1627 int ret; 1628 if (state.isInstallAllowed()) { 1629 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1630 broadcastPackageVerified(verificationId, originUri, 1631 response.code, state.getInstallArgs().getUser()); 1632 try { 1633 ret = args.copyApk(mContainerService, true); 1634 } catch (RemoteException e) { 1635 Slog.e(TAG, "Could not contact the ContainerService"); 1636 } 1637 } else { 1638 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1639 } 1640 1641 Trace.asyncTraceEnd( 1642 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1643 1644 processPendingInstall(args, ret); 1645 mHandler.sendEmptyMessage(MCS_UNBIND); 1646 } 1647 1648 break; 1649 } 1650 case START_INTENT_FILTER_VERIFICATIONS: { 1651 IFVerificationParams params = (IFVerificationParams) msg.obj; 1652 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1653 params.replacing, params.pkg); 1654 break; 1655 } 1656 case INTENT_FILTER_VERIFIED: { 1657 final int verificationId = msg.arg1; 1658 1659 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1660 verificationId); 1661 if (state == null) { 1662 Slog.w(TAG, "Invalid IntentFilter verification token " 1663 + verificationId + " received"); 1664 break; 1665 } 1666 1667 final int userId = state.getUserId(); 1668 1669 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1670 "Processing IntentFilter verification with token:" 1671 + verificationId + " and userId:" + userId); 1672 1673 final IntentFilterVerificationResponse response = 1674 (IntentFilterVerificationResponse) msg.obj; 1675 1676 state.setVerifierResponse(response.callerUid, response.code); 1677 1678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1679 "IntentFilter verification with token:" + verificationId 1680 + " and userId:" + userId 1681 + " is settings verifier response with response code:" 1682 + response.code); 1683 1684 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1685 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1686 + response.getFailedDomainsString()); 1687 } 1688 1689 if (state.isVerificationComplete()) { 1690 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1691 } else { 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "IntentFilter verification with token:" + verificationId 1694 + " was not said to be complete"); 1695 } 1696 1697 break; 1698 } 1699 } 1700 } 1701 } 1702 1703 private StorageEventListener mStorageListener = new StorageEventListener() { 1704 @Override 1705 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1706 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1707 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1708 final String volumeUuid = vol.getFsUuid(); 1709 1710 // Clean up any users or apps that were removed or recreated 1711 // while this volume was missing 1712 reconcileUsers(volumeUuid); 1713 reconcileApps(volumeUuid); 1714 1715 // Clean up any install sessions that expired or were 1716 // cancelled while this volume was missing 1717 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1718 1719 loadPrivatePackages(vol); 1720 1721 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1722 unloadPrivatePackages(vol); 1723 } 1724 } 1725 1726 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1727 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1728 updateExternalMediaStatus(true, false); 1729 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1730 updateExternalMediaStatus(false, false); 1731 } 1732 } 1733 } 1734 1735 @Override 1736 public void onVolumeForgotten(String fsUuid) { 1737 if (TextUtils.isEmpty(fsUuid)) { 1738 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1739 return; 1740 } 1741 1742 // Remove any apps installed on the forgotten volume 1743 synchronized (mPackages) { 1744 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1745 for (PackageSetting ps : packages) { 1746 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1747 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1748 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1749 } 1750 1751 mSettings.onVolumeForgotten(fsUuid); 1752 mSettings.writeLPr(); 1753 } 1754 } 1755 }; 1756 1757 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1758 String[] grantedPermissions) { 1759 if (userId >= UserHandle.USER_SYSTEM) { 1760 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1761 } else if (userId == UserHandle.USER_ALL) { 1762 final int[] userIds; 1763 synchronized (mPackages) { 1764 userIds = UserManagerService.getInstance().getUserIds(); 1765 } 1766 for (int someUserId : userIds) { 1767 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1768 } 1769 } 1770 1771 // We could have touched GID membership, so flush out packages.list 1772 synchronized (mPackages) { 1773 mSettings.writePackageListLPr(); 1774 } 1775 } 1776 1777 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1778 String[] grantedPermissions) { 1779 SettingBase sb = (SettingBase) pkg.mExtras; 1780 if (sb == null) { 1781 return; 1782 } 1783 1784 PermissionsState permissionsState = sb.getPermissionsState(); 1785 1786 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1787 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1788 1789 synchronized (mPackages) { 1790 for (String permission : pkg.requestedPermissions) { 1791 BasePermission bp = mSettings.mPermissions.get(permission); 1792 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1793 && (grantedPermissions == null 1794 || ArrayUtils.contains(grantedPermissions, permission))) { 1795 final int flags = permissionsState.getPermissionFlags(permission, userId); 1796 // Installer cannot change immutable permissions. 1797 if ((flags & immutableFlags) == 0) { 1798 grantRuntimePermission(pkg.packageName, permission, userId); 1799 } 1800 } 1801 } 1802 } 1803 } 1804 1805 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1806 Bundle extras = null; 1807 switch (res.returnCode) { 1808 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1809 extras = new Bundle(); 1810 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1811 res.origPermission); 1812 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1813 res.origPackage); 1814 break; 1815 } 1816 case PackageManager.INSTALL_SUCCEEDED: { 1817 extras = new Bundle(); 1818 extras.putBoolean(Intent.EXTRA_REPLACING, 1819 res.removedInfo != null && res.removedInfo.removedPackage != null); 1820 break; 1821 } 1822 } 1823 return extras; 1824 } 1825 1826 void scheduleWriteSettingsLocked() { 1827 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1828 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1829 } 1830 } 1831 1832 void scheduleWritePackageRestrictionsLocked(int userId) { 1833 if (!sUserManager.exists(userId)) return; 1834 mDirtyUsers.add(userId); 1835 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1836 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1837 } 1838 } 1839 1840 public static PackageManagerService main(Context context, Installer installer, 1841 boolean factoryTest, boolean onlyCore) { 1842 PackageManagerService m = new PackageManagerService(context, installer, 1843 factoryTest, onlyCore); 1844 m.enableSystemUserApps(); 1845 ServiceManager.addService("package", m); 1846 return m; 1847 } 1848 1849 private void enableSystemUserApps() { 1850 if (!UserManager.isSplitSystemUser()) { 1851 return; 1852 } 1853 // For system user, enable apps based on the following conditions: 1854 // - app is whitelisted or belong to one of these groups: 1855 // -- system app which has no launcher icons 1856 // -- system app which has INTERACT_ACROSS_USERS permission 1857 // -- system IME app 1858 // - app is not in the blacklist 1859 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1860 Set<String> enableApps = new ArraySet<>(); 1861 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1862 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1863 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1864 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1865 enableApps.addAll(wlApps); 1866 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1867 enableApps.removeAll(blApps); 1868 1869 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1870 UserHandle.SYSTEM); 1871 final int systemAppsSize = systemApps.size(); 1872 synchronized (mPackages) { 1873 for (int i = 0; i < systemAppsSize; i++) { 1874 String pName = systemApps.get(i); 1875 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1876 // Should not happen, but we shouldn't be failing if it does 1877 if (pkgSetting == null) { 1878 continue; 1879 } 1880 boolean installed = enableApps.contains(pName); 1881 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1882 } 1883 } 1884 } 1885 1886 static String[] splitString(String str, char sep) { 1887 int count = 1; 1888 int i = 0; 1889 while ((i=str.indexOf(sep, i)) >= 0) { 1890 count++; 1891 i++; 1892 } 1893 1894 String[] res = new String[count]; 1895 i=0; 1896 count = 0; 1897 int lastI=0; 1898 while ((i=str.indexOf(sep, i)) >= 0) { 1899 res[count] = str.substring(lastI, i); 1900 count++; 1901 i++; 1902 lastI = i; 1903 } 1904 res[count] = str.substring(lastI, str.length()); 1905 return res; 1906 } 1907 1908 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1909 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1910 Context.DISPLAY_SERVICE); 1911 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1912 } 1913 1914 public PackageManagerService(Context context, Installer installer, 1915 boolean factoryTest, boolean onlyCore) { 1916 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1917 SystemClock.uptimeMillis()); 1918 1919 if (mSdkVersion <= 0) { 1920 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1921 } 1922 1923 mContext = context; 1924 mFactoryTest = factoryTest; 1925 mOnlyCore = onlyCore; 1926 mMetrics = new DisplayMetrics(); 1927 mSettings = new Settings(mPackages); 1928 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1929 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1930 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1931 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1932 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1933 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1934 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1935 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1936 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1937 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1938 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1939 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1940 1941 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1942 if (separateProcesses != null && separateProcesses.length() > 0) { 1943 if ("*".equals(separateProcesses)) { 1944 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1945 mSeparateProcesses = null; 1946 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1947 } else { 1948 mDefParseFlags = 0; 1949 mSeparateProcesses = separateProcesses.split(","); 1950 Slog.w(TAG, "Running with debug.separate_processes: " 1951 + separateProcesses); 1952 } 1953 } else { 1954 mDefParseFlags = 0; 1955 mSeparateProcesses = null; 1956 } 1957 1958 mInstaller = installer; 1959 mPackageDexOptimizer = new PackageDexOptimizer(this); 1960 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1961 1962 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1963 FgThread.get().getLooper()); 1964 1965 getDefaultDisplayMetrics(context, mMetrics); 1966 1967 SystemConfig systemConfig = SystemConfig.getInstance(); 1968 mGlobalGids = systemConfig.getGlobalGids(); 1969 mSystemPermissions = systemConfig.getSystemPermissions(); 1970 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1971 1972 synchronized (mInstallLock) { 1973 // writer 1974 synchronized (mPackages) { 1975 mHandlerThread = new ServiceThread(TAG, 1976 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1977 mHandlerThread.start(); 1978 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1979 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1980 1981 File dataDir = Environment.getDataDirectory(); 1982 mAppDataDir = new File(dataDir, "data"); 1983 mAppInstallDir = new File(dataDir, "app"); 1984 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1985 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1986 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1987 mUserAppDataDir = new File(dataDir, "user"); 1988 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1989 1990 sUserManager = new UserManagerService(context, this, mPackages); 1991 1992 // Propagate permission configuration in to package manager. 1993 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1994 = systemConfig.getPermissions(); 1995 for (int i=0; i<permConfig.size(); i++) { 1996 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1997 BasePermission bp = mSettings.mPermissions.get(perm.name); 1998 if (bp == null) { 1999 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2000 mSettings.mPermissions.put(perm.name, bp); 2001 } 2002 if (perm.gids != null) { 2003 bp.setGids(perm.gids, perm.perUser); 2004 } 2005 } 2006 2007 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2008 for (int i=0; i<libConfig.size(); i++) { 2009 mSharedLibraries.put(libConfig.keyAt(i), 2010 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2011 } 2012 2013 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2014 2015 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2016 2017 String customResolverActivity = Resources.getSystem().getString( 2018 R.string.config_customResolverActivity); 2019 if (TextUtils.isEmpty(customResolverActivity)) { 2020 customResolverActivity = null; 2021 } else { 2022 mCustomResolverComponentName = ComponentName.unflattenFromString( 2023 customResolverActivity); 2024 } 2025 2026 long startTime = SystemClock.uptimeMillis(); 2027 2028 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2029 startTime); 2030 2031 // Set flag to monitor and not change apk file paths when 2032 // scanning install directories. 2033 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2034 2035 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2036 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2037 2038 if (bootClassPath == null) { 2039 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2040 } 2041 2042 if (systemServerClassPath == null) { 2043 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2044 } 2045 2046 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2047 final String[] dexCodeInstructionSets = 2048 getDexCodeInstructionSets( 2049 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2050 2051 /** 2052 * Ensure all external libraries have had dexopt run on them. 2053 */ 2054 if (mSharedLibraries.size() > 0) { 2055 // NOTE: For now, we're compiling these system "shared libraries" 2056 // (and framework jars) into all available architectures. It's possible 2057 // to compile them only when we come across an app that uses them (there's 2058 // already logic for that in scanPackageLI) but that adds some complexity. 2059 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2060 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2061 final String lib = libEntry.path; 2062 if (lib == null) { 2063 continue; 2064 } 2065 2066 try { 2067 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2068 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2069 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2070 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2071 } 2072 } catch (FileNotFoundException e) { 2073 Slog.w(TAG, "Library not found: " + lib); 2074 } catch (IOException e) { 2075 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2076 + e.getMessage()); 2077 } 2078 } 2079 } 2080 } 2081 2082 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2083 2084 final VersionInfo ver = mSettings.getInternalVersion(); 2085 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2086 // when upgrading from pre-M, promote system app permissions from install to runtime 2087 mPromoteSystemApps = 2088 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2089 2090 // save off the names of pre-existing system packages prior to scanning; we don't 2091 // want to automatically grant runtime permissions for new system apps 2092 if (mPromoteSystemApps) { 2093 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2094 while (pkgSettingIter.hasNext()) { 2095 PackageSetting ps = pkgSettingIter.next(); 2096 if (isSystemApp(ps)) { 2097 mExistingSystemPackages.add(ps.name); 2098 } 2099 } 2100 } 2101 2102 // Collect vendor overlay packages. 2103 // (Do this before scanning any apps.) 2104 // For security and version matching reason, only consider 2105 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2106 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2107 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2108 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2109 2110 // Find base frameworks (resource packages without code). 2111 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2112 | PackageParser.PARSE_IS_SYSTEM_DIR 2113 | PackageParser.PARSE_IS_PRIVILEGED, 2114 scanFlags | SCAN_NO_DEX, 0); 2115 2116 // Collected privileged system packages. 2117 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2118 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2119 | PackageParser.PARSE_IS_SYSTEM_DIR 2120 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2121 2122 // Collect ordinary system packages. 2123 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2124 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2125 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2126 2127 // Collect all vendor packages. 2128 File vendorAppDir = new File("/vendor/app"); 2129 try { 2130 vendorAppDir = vendorAppDir.getCanonicalFile(); 2131 } catch (IOException e) { 2132 // failed to look up canonical path, continue with original one 2133 } 2134 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2135 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2136 2137 // Collect all OEM packages. 2138 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2139 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2140 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2141 2142 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2143 mInstaller.moveFiles(); 2144 2145 // Prune any system packages that no longer exist. 2146 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2147 if (!mOnlyCore) { 2148 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2149 while (psit.hasNext()) { 2150 PackageSetting ps = psit.next(); 2151 2152 /* 2153 * If this is not a system app, it can't be a 2154 * disable system app. 2155 */ 2156 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2157 continue; 2158 } 2159 2160 /* 2161 * If the package is scanned, it's not erased. 2162 */ 2163 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2164 if (scannedPkg != null) { 2165 /* 2166 * If the system app is both scanned and in the 2167 * disabled packages list, then it must have been 2168 * added via OTA. Remove it from the currently 2169 * scanned package so the previously user-installed 2170 * application can be scanned. 2171 */ 2172 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2173 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2174 + ps.name + "; removing system app. Last known codePath=" 2175 + ps.codePathString + ", installStatus=" + ps.installStatus 2176 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2177 + scannedPkg.mVersionCode); 2178 removePackageLI(ps, true); 2179 mExpectingBetter.put(ps.name, ps.codePath); 2180 } 2181 2182 continue; 2183 } 2184 2185 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2186 psit.remove(); 2187 logCriticalInfo(Log.WARN, "System package " + ps.name 2188 + " no longer exists; wiping its data"); 2189 removeDataDirsLI(null, ps.name); 2190 } else { 2191 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2192 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2193 possiblyDeletedUpdatedSystemApps.add(ps.name); 2194 } 2195 } 2196 } 2197 } 2198 2199 //look for any incomplete package installations 2200 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2201 //clean up list 2202 for(int i = 0; i < deletePkgsList.size(); i++) { 2203 //clean up here 2204 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2205 } 2206 //delete tmp files 2207 deleteTempPackageFiles(); 2208 2209 // Remove any shared userIDs that have no associated packages 2210 mSettings.pruneSharedUsersLPw(); 2211 2212 if (!mOnlyCore) { 2213 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2214 SystemClock.uptimeMillis()); 2215 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2216 2217 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2218 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2219 2220 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2221 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2222 2223 /** 2224 * Remove disable package settings for any updated system 2225 * apps that were removed via an OTA. If they're not a 2226 * previously-updated app, remove them completely. 2227 * Otherwise, just revoke their system-level permissions. 2228 */ 2229 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2230 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2231 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2232 2233 String msg; 2234 if (deletedPkg == null) { 2235 msg = "Updated system package " + deletedAppName 2236 + " no longer exists; wiping its data"; 2237 removeDataDirsLI(null, deletedAppName); 2238 } else { 2239 msg = "Updated system app + " + deletedAppName 2240 + " no longer present; removing system privileges for " 2241 + deletedAppName; 2242 2243 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2244 2245 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2246 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2247 } 2248 logCriticalInfo(Log.WARN, msg); 2249 } 2250 2251 /** 2252 * Make sure all system apps that we expected to appear on 2253 * the userdata partition actually showed up. If they never 2254 * appeared, crawl back and revive the system version. 2255 */ 2256 for (int i = 0; i < mExpectingBetter.size(); i++) { 2257 final String packageName = mExpectingBetter.keyAt(i); 2258 if (!mPackages.containsKey(packageName)) { 2259 final File scanFile = mExpectingBetter.valueAt(i); 2260 2261 logCriticalInfo(Log.WARN, "Expected better " + packageName 2262 + " but never showed up; reverting to system"); 2263 2264 final int reparseFlags; 2265 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR 2268 | PackageParser.PARSE_IS_PRIVILEGED; 2269 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2270 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR; 2272 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2273 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2274 | PackageParser.PARSE_IS_SYSTEM_DIR; 2275 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2276 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR; 2278 } else { 2279 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2280 continue; 2281 } 2282 2283 mSettings.enableSystemPackageLPw(packageName); 2284 2285 try { 2286 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2287 } catch (PackageManagerException e) { 2288 Slog.e(TAG, "Failed to parse original system package: " 2289 + e.getMessage()); 2290 } 2291 } 2292 } 2293 } 2294 mExpectingBetter.clear(); 2295 2296 // Now that we know all of the shared libraries, update all clients to have 2297 // the correct library paths. 2298 updateAllSharedLibrariesLPw(); 2299 2300 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2301 // NOTE: We ignore potential failures here during a system scan (like 2302 // the rest of the commands above) because there's precious little we 2303 // can do about it. A settings error is reported, though. 2304 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2305 false /* boot complete */); 2306 } 2307 2308 // Now that we know all the packages we are keeping, 2309 // read and update their last usage times. 2310 mPackageUsage.readLP(); 2311 2312 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2313 SystemClock.uptimeMillis()); 2314 Slog.i(TAG, "Time to scan packages: " 2315 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2316 + " seconds"); 2317 2318 // If the platform SDK has changed since the last time we booted, 2319 // we need to re-grant app permission to catch any new ones that 2320 // appear. This is really a hack, and means that apps can in some 2321 // cases get permissions that the user didn't initially explicitly 2322 // allow... it would be nice to have some better way to handle 2323 // this situation. 2324 int updateFlags = UPDATE_PERMISSIONS_ALL; 2325 if (ver.sdkVersion != mSdkVersion) { 2326 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2327 + mSdkVersion + "; regranting permissions for internal storage"); 2328 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2329 } 2330 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2331 ver.sdkVersion = mSdkVersion; 2332 2333 // If this is the first boot or an update from pre-M, and it is a normal 2334 // boot, then we need to initialize the default preferred apps across 2335 // all defined users. 2336 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2337 for (UserInfo user : sUserManager.getUsers(true)) { 2338 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2339 applyFactoryDefaultBrowserLPw(user.id); 2340 primeDomainVerificationsLPw(user.id); 2341 } 2342 } 2343 2344 // If this is first boot after an OTA, and a normal boot, then 2345 // we need to clear code cache directories. 2346 if (mIsUpgrade && !onlyCore) { 2347 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2348 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2349 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2350 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2351 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2352 } 2353 } 2354 ver.fingerprint = Build.FINGERPRINT; 2355 } 2356 2357 checkDefaultBrowser(); 2358 2359 // clear only after permissions and other defaults have been updated 2360 mExistingSystemPackages.clear(); 2361 mPromoteSystemApps = false; 2362 2363 // All the changes are done during package scanning. 2364 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2365 2366 // can downgrade to reader 2367 mSettings.writeLPr(); 2368 2369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2370 SystemClock.uptimeMillis()); 2371 2372 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2373 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2374 2375 mInstallerService = new PackageInstallerService(context, this); 2376 2377 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2378 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2379 mIntentFilterVerifierComponent); 2380 2381 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2382 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2383 // both the installer and resolver must be present to enable ephemeral 2384 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2385 if (DEBUG_EPHEMERAL) { 2386 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2387 + " installer:" + ephemeralInstallerComponent); 2388 } 2389 mEphemeralResolverComponent = ephemeralResolverComponent; 2390 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2391 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2392 mEphemeralResolverConnection = 2393 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2394 } else { 2395 if (DEBUG_EPHEMERAL) { 2396 final String missingComponent = 2397 (ephemeralResolverComponent == null) 2398 ? (ephemeralInstallerComponent == null) 2399 ? "resolver and installer" 2400 : "resolver" 2401 : "installer"; 2402 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2403 } 2404 mEphemeralResolverComponent = null; 2405 mEphemeralInstallerComponent = null; 2406 mEphemeralResolverConnection = null; 2407 } 2408 } // synchronized (mPackages) 2409 } // synchronized (mInstallLock) 2410 2411 // Now after opening every single application zip, make sure they 2412 // are all flushed. Not really needed, but keeps things nice and 2413 // tidy. 2414 Runtime.getRuntime().gc(); 2415 2416 // The initial scanning above does many calls into installd while 2417 // holding the mPackages lock, but we're mostly interested in yelling 2418 // once we have a booted system. 2419 mInstaller.setWarnIfHeld(mPackages); 2420 2421 // Expose private service for system components to use. 2422 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2423 } 2424 2425 @Override 2426 public boolean isFirstBoot() { 2427 return !mRestoredSettings; 2428 } 2429 2430 @Override 2431 public boolean isOnlyCoreApps() { 2432 return mOnlyCore; 2433 } 2434 2435 @Override 2436 public boolean isUpgrade() { 2437 return mIsUpgrade; 2438 } 2439 2440 private String getRequiredVerifierLPr() { 2441 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2442 // We only care about verifier that's installed under system user. 2443 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2444 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2445 2446 String requiredVerifier = null; 2447 2448 final int N = receivers.size(); 2449 for (int i = 0; i < N; i++) { 2450 final ResolveInfo info = receivers.get(i); 2451 2452 if (info.activityInfo == null) { 2453 continue; 2454 } 2455 2456 final String packageName = info.activityInfo.packageName; 2457 2458 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2459 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2460 continue; 2461 } 2462 2463 if (requiredVerifier != null) { 2464 throw new RuntimeException("There can be only one required verifier"); 2465 } 2466 2467 requiredVerifier = packageName; 2468 } 2469 2470 return requiredVerifier; 2471 } 2472 2473 private String getRequiredInstallerLPr() { 2474 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2475 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2476 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2477 2478 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2479 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2480 2481 String requiredInstaller = null; 2482 2483 final int N = installers.size(); 2484 for (int i = 0; i < N; i++) { 2485 final ResolveInfo info = installers.get(i); 2486 final String packageName = info.activityInfo.packageName; 2487 2488 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2489 continue; 2490 } 2491 2492 if (requiredInstaller != null) { 2493 throw new RuntimeException("There must be one required installer"); 2494 } 2495 2496 requiredInstaller = packageName; 2497 } 2498 2499 if (requiredInstaller == null) { 2500 throw new RuntimeException("There must be one required installer"); 2501 } 2502 2503 return requiredInstaller; 2504 } 2505 2506 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2507 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2508 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2509 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2510 2511 ComponentName verifierComponentName = null; 2512 2513 int priority = -1000; 2514 final int N = receivers.size(); 2515 for (int i = 0; i < N; i++) { 2516 final ResolveInfo info = receivers.get(i); 2517 2518 if (info.activityInfo == null) { 2519 continue; 2520 } 2521 2522 final String packageName = info.activityInfo.packageName; 2523 2524 final PackageSetting ps = mSettings.mPackages.get(packageName); 2525 if (ps == null) { 2526 continue; 2527 } 2528 2529 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2530 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2531 continue; 2532 } 2533 2534 // Select the IntentFilterVerifier with the highest priority 2535 if (priority < info.priority) { 2536 priority = info.priority; 2537 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2538 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2539 + verifierComponentName + " with priority: " + info.priority); 2540 } 2541 } 2542 2543 return verifierComponentName; 2544 } 2545 2546 private ComponentName getEphemeralResolverLPr() { 2547 final String[] packageArray = 2548 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2549 if (packageArray.length == 0) { 2550 if (DEBUG_EPHEMERAL) { 2551 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2552 } 2553 return null; 2554 } 2555 2556 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2557 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2558 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2559 2560 final int N = resolvers.size(); 2561 if (N == 0) { 2562 if (DEBUG_EPHEMERAL) { 2563 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2564 } 2565 return null; 2566 } 2567 2568 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2569 for (int i = 0; i < N; i++) { 2570 final ResolveInfo info = resolvers.get(i); 2571 2572 if (info.serviceInfo == null) { 2573 continue; 2574 } 2575 2576 final String packageName = info.serviceInfo.packageName; 2577 if (!possiblePackages.contains(packageName)) { 2578 if (DEBUG_EPHEMERAL) { 2579 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2580 + " pkg: " + packageName + ", info:" + info); 2581 } 2582 continue; 2583 } 2584 2585 if (DEBUG_EPHEMERAL) { 2586 Slog.v(TAG, "Ephemeral resolver found;" 2587 + " pkg: " + packageName + ", info:" + info); 2588 } 2589 return new ComponentName(packageName, info.serviceInfo.name); 2590 } 2591 if (DEBUG_EPHEMERAL) { 2592 Slog.v(TAG, "Ephemeral resolver NOT found"); 2593 } 2594 return null; 2595 } 2596 2597 private ComponentName getEphemeralInstallerLPr() { 2598 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2599 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2600 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2601 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2602 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2603 2604 ComponentName ephemeralInstaller = null; 2605 2606 final int N = installers.size(); 2607 for (int i = 0; i < N; i++) { 2608 final ResolveInfo info = installers.get(i); 2609 final String packageName = info.activityInfo.packageName; 2610 2611 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2612 if (DEBUG_EPHEMERAL) { 2613 Slog.d(TAG, "Ephemeral installer is not system app;" 2614 + " pkg: " + packageName + ", info:" + info); 2615 } 2616 continue; 2617 } 2618 2619 if (ephemeralInstaller != null) { 2620 throw new RuntimeException("There must only be one ephemeral installer"); 2621 } 2622 2623 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2624 } 2625 2626 return ephemeralInstaller; 2627 } 2628 2629 private void primeDomainVerificationsLPw(int userId) { 2630 if (DEBUG_DOMAIN_VERIFICATION) { 2631 Slog.d(TAG, "Priming domain verifications in user " + userId); 2632 } 2633 2634 SystemConfig systemConfig = SystemConfig.getInstance(); 2635 ArraySet<String> packages = systemConfig.getLinkedApps(); 2636 ArraySet<String> domains = new ArraySet<String>(); 2637 2638 for (String packageName : packages) { 2639 PackageParser.Package pkg = mPackages.get(packageName); 2640 if (pkg != null) { 2641 if (!pkg.isSystemApp()) { 2642 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2643 continue; 2644 } 2645 2646 domains.clear(); 2647 for (PackageParser.Activity a : pkg.activities) { 2648 for (ActivityIntentInfo filter : a.intents) { 2649 if (hasValidDomains(filter)) { 2650 domains.addAll(filter.getHostsList()); 2651 } 2652 } 2653 } 2654 2655 if (domains.size() > 0) { 2656 if (DEBUG_DOMAIN_VERIFICATION) { 2657 Slog.v(TAG, " + " + packageName); 2658 } 2659 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2660 // state w.r.t. the formal app-linkage "no verification attempted" state; 2661 // and then 'always' in the per-user state actually used for intent resolution. 2662 final IntentFilterVerificationInfo ivi; 2663 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2664 new ArrayList<String>(domains)); 2665 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2666 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2667 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2668 } else { 2669 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2670 + "' does not handle web links"); 2671 } 2672 } else { 2673 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2674 } 2675 } 2676 2677 scheduleWritePackageRestrictionsLocked(userId); 2678 scheduleWriteSettingsLocked(); 2679 } 2680 2681 private void applyFactoryDefaultBrowserLPw(int userId) { 2682 // The default browser app's package name is stored in a string resource, 2683 // with a product-specific overlay used for vendor customization. 2684 String browserPkg = mContext.getResources().getString( 2685 com.android.internal.R.string.default_browser); 2686 if (!TextUtils.isEmpty(browserPkg)) { 2687 // non-empty string => required to be a known package 2688 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2689 if (ps == null) { 2690 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2691 browserPkg = null; 2692 } else { 2693 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2694 } 2695 } 2696 2697 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2698 // default. If there's more than one, just leave everything alone. 2699 if (browserPkg == null) { 2700 calculateDefaultBrowserLPw(userId); 2701 } 2702 } 2703 2704 private void calculateDefaultBrowserLPw(int userId) { 2705 List<String> allBrowsers = resolveAllBrowserApps(userId); 2706 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2707 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2708 } 2709 2710 private List<String> resolveAllBrowserApps(int userId) { 2711 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2712 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2713 PackageManager.MATCH_ALL, userId); 2714 2715 final int count = list.size(); 2716 List<String> result = new ArrayList<String>(count); 2717 for (int i=0; i<count; i++) { 2718 ResolveInfo info = list.get(i); 2719 if (info.activityInfo == null 2720 || !info.handleAllWebDataURI 2721 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2722 || result.contains(info.activityInfo.packageName)) { 2723 continue; 2724 } 2725 result.add(info.activityInfo.packageName); 2726 } 2727 2728 return result; 2729 } 2730 2731 private boolean packageIsBrowser(String packageName, int userId) { 2732 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2733 PackageManager.MATCH_ALL, userId); 2734 final int N = list.size(); 2735 for (int i = 0; i < N; i++) { 2736 ResolveInfo info = list.get(i); 2737 if (packageName.equals(info.activityInfo.packageName)) { 2738 return true; 2739 } 2740 } 2741 return false; 2742 } 2743 2744 private void checkDefaultBrowser() { 2745 final int myUserId = UserHandle.myUserId(); 2746 final String packageName = getDefaultBrowserPackageName(myUserId); 2747 if (packageName != null) { 2748 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2749 if (info == null) { 2750 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2751 synchronized (mPackages) { 2752 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2753 } 2754 } 2755 } 2756 } 2757 2758 @Override 2759 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2760 throws RemoteException { 2761 try { 2762 return super.onTransact(code, data, reply, flags); 2763 } catch (RuntimeException e) { 2764 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2765 Slog.wtf(TAG, "Package Manager Crash", e); 2766 } 2767 throw e; 2768 } 2769 } 2770 2771 void cleanupInstallFailedPackage(PackageSetting ps) { 2772 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2773 2774 removeDataDirsLI(ps.volumeUuid, ps.name); 2775 if (ps.codePath != null) { 2776 if (ps.codePath.isDirectory()) { 2777 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2778 } else { 2779 ps.codePath.delete(); 2780 } 2781 } 2782 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2783 if (ps.resourcePath.isDirectory()) { 2784 FileUtils.deleteContents(ps.resourcePath); 2785 } 2786 ps.resourcePath.delete(); 2787 } 2788 mSettings.removePackageLPw(ps.name); 2789 } 2790 2791 static int[] appendInts(int[] cur, int[] add) { 2792 if (add == null) return cur; 2793 if (cur == null) return add; 2794 final int N = add.length; 2795 for (int i=0; i<N; i++) { 2796 cur = appendInt(cur, add[i]); 2797 } 2798 return cur; 2799 } 2800 2801 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2802 if (!sUserManager.exists(userId)) return null; 2803 final PackageSetting ps = (PackageSetting) p.mExtras; 2804 if (ps == null) { 2805 return null; 2806 } 2807 2808 final PermissionsState permissionsState = ps.getPermissionsState(); 2809 2810 final int[] gids = permissionsState.computeGids(userId); 2811 final Set<String> permissions = permissionsState.getPermissions(userId); 2812 final PackageUserState state = ps.readUserState(userId); 2813 2814 return PackageParser.generatePackageInfo(p, gids, flags, 2815 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2816 } 2817 2818 @Override 2819 public void checkPackageStartable(String packageName, int userId) { 2820 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2821 2822 synchronized (mPackages) { 2823 final PackageSetting ps = mSettings.mPackages.get(packageName); 2824 if (ps == null) { 2825 throw new SecurityException("Package " + packageName + " was not found!"); 2826 } 2827 2828 if (ps.frozen) { 2829 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2830 } 2831 2832 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2833 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2834 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2835 } 2836 } 2837 } 2838 2839 @Override 2840 public boolean isPackageAvailable(String packageName, int userId) { 2841 if (!sUserManager.exists(userId)) return false; 2842 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2843 synchronized (mPackages) { 2844 PackageParser.Package p = mPackages.get(packageName); 2845 if (p != null) { 2846 final PackageSetting ps = (PackageSetting) p.mExtras; 2847 if (ps != null) { 2848 final PackageUserState state = ps.readUserState(userId); 2849 if (state != null) { 2850 return PackageParser.isAvailable(state); 2851 } 2852 } 2853 } 2854 } 2855 return false; 2856 } 2857 2858 @Override 2859 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2860 if (!sUserManager.exists(userId)) return null; 2861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2862 // reader 2863 synchronized (mPackages) { 2864 PackageParser.Package p = mPackages.get(packageName); 2865 if (DEBUG_PACKAGE_INFO) 2866 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2867 if (p != null) { 2868 return generatePackageInfo(p, flags, userId); 2869 } 2870 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2871 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2872 } 2873 } 2874 return null; 2875 } 2876 2877 @Override 2878 public String[] currentToCanonicalPackageNames(String[] names) { 2879 String[] out = new String[names.length]; 2880 // reader 2881 synchronized (mPackages) { 2882 for (int i=names.length-1; i>=0; i--) { 2883 PackageSetting ps = mSettings.mPackages.get(names[i]); 2884 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2885 } 2886 } 2887 return out; 2888 } 2889 2890 @Override 2891 public String[] canonicalToCurrentPackageNames(String[] names) { 2892 String[] out = new String[names.length]; 2893 // reader 2894 synchronized (mPackages) { 2895 for (int i=names.length-1; i>=0; i--) { 2896 String cur = mSettings.mRenamedPackages.get(names[i]); 2897 out[i] = cur != null ? cur : names[i]; 2898 } 2899 } 2900 return out; 2901 } 2902 2903 @Override 2904 public int getPackageUid(String packageName, int userId) { 2905 return getPackageUidEtc(packageName, 0, userId); 2906 } 2907 2908 @Override 2909 public int getPackageUidEtc(String packageName, int flags, int userId) { 2910 if (!sUserManager.exists(userId)) return -1; 2911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2912 2913 // reader 2914 synchronized (mPackages) { 2915 final PackageParser.Package p = mPackages.get(packageName); 2916 if (p != null) { 2917 return UserHandle.getUid(userId, p.applicationInfo.uid); 2918 } 2919 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2920 final PackageSetting ps = mSettings.mPackages.get(packageName); 2921 if (ps != null) { 2922 return UserHandle.getUid(userId, ps.appId); 2923 } 2924 } 2925 } 2926 2927 return -1; 2928 } 2929 2930 @Override 2931 public int[] getPackageGids(String packageName, int userId) { 2932 return getPackageGidsEtc(packageName, 0, userId); 2933 } 2934 2935 @Override 2936 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2937 if (!sUserManager.exists(userId)) { 2938 return null; 2939 } 2940 2941 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2942 "getPackageGids"); 2943 2944 // reader 2945 synchronized (mPackages) { 2946 final PackageParser.Package p = mPackages.get(packageName); 2947 if (p != null) { 2948 PackageSetting ps = (PackageSetting) p.mExtras; 2949 return ps.getPermissionsState().computeGids(userId); 2950 } 2951 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2952 final PackageSetting ps = mSettings.mPackages.get(packageName); 2953 if (ps != null) { 2954 return ps.getPermissionsState().computeGids(userId); 2955 } 2956 } 2957 } 2958 2959 return null; 2960 } 2961 2962 static PermissionInfo generatePermissionInfo( 2963 BasePermission bp, int flags) { 2964 if (bp.perm != null) { 2965 return PackageParser.generatePermissionInfo(bp.perm, flags); 2966 } 2967 PermissionInfo pi = new PermissionInfo(); 2968 pi.name = bp.name; 2969 pi.packageName = bp.sourcePackage; 2970 pi.nonLocalizedLabel = bp.name; 2971 pi.protectionLevel = bp.protectionLevel; 2972 return pi; 2973 } 2974 2975 @Override 2976 public PermissionInfo getPermissionInfo(String name, int flags) { 2977 // reader 2978 synchronized (mPackages) { 2979 final BasePermission p = mSettings.mPermissions.get(name); 2980 if (p != null) { 2981 return generatePermissionInfo(p, flags); 2982 } 2983 return null; 2984 } 2985 } 2986 2987 @Override 2988 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2989 // reader 2990 synchronized (mPackages) { 2991 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2992 for (BasePermission p : mSettings.mPermissions.values()) { 2993 if (group == null) { 2994 if (p.perm == null || p.perm.info.group == null) { 2995 out.add(generatePermissionInfo(p, flags)); 2996 } 2997 } else { 2998 if (p.perm != null && group.equals(p.perm.info.group)) { 2999 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3000 } 3001 } 3002 } 3003 3004 if (out.size() > 0) { 3005 return out; 3006 } 3007 return mPermissionGroups.containsKey(group) ? out : null; 3008 } 3009 } 3010 3011 @Override 3012 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3013 // reader 3014 synchronized (mPackages) { 3015 return PackageParser.generatePermissionGroupInfo( 3016 mPermissionGroups.get(name), flags); 3017 } 3018 } 3019 3020 @Override 3021 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3022 // reader 3023 synchronized (mPackages) { 3024 final int N = mPermissionGroups.size(); 3025 ArrayList<PermissionGroupInfo> out 3026 = new ArrayList<PermissionGroupInfo>(N); 3027 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3028 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3029 } 3030 return out; 3031 } 3032 } 3033 3034 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3035 int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 PackageSetting ps = mSettings.mPackages.get(packageName); 3038 if (ps != null) { 3039 if (ps.pkg == null) { 3040 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3041 flags, userId); 3042 if (pInfo != null) { 3043 return pInfo.applicationInfo; 3044 } 3045 return null; 3046 } 3047 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3048 ps.readUserState(userId), userId); 3049 } 3050 return null; 3051 } 3052 3053 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3054 int userId) { 3055 if (!sUserManager.exists(userId)) return null; 3056 PackageSetting ps = mSettings.mPackages.get(packageName); 3057 if (ps != null) { 3058 PackageParser.Package pkg = ps.pkg; 3059 if (pkg == null) { 3060 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3061 return null; 3062 } 3063 // Only data remains, so we aren't worried about code paths 3064 pkg = new PackageParser.Package(packageName); 3065 pkg.applicationInfo.packageName = packageName; 3066 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3067 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3068 pkg.applicationInfo.uid = ps.appId; 3069 pkg.applicationInfo.initForUser(userId); 3070 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3071 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3072 } 3073 return generatePackageInfo(pkg, flags, userId); 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3080 if (!sUserManager.exists(userId)) return null; 3081 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3082 // writer 3083 synchronized (mPackages) { 3084 PackageParser.Package p = mPackages.get(packageName); 3085 if (DEBUG_PACKAGE_INFO) Log.v( 3086 TAG, "getApplicationInfo " + packageName 3087 + ": " + p); 3088 if (p != null) { 3089 PackageSetting ps = mSettings.mPackages.get(packageName); 3090 if (ps == null) return null; 3091 // Note: isEnabledLP() does not apply here - always return info 3092 return PackageParser.generateApplicationInfo( 3093 p, flags, ps.readUserState(userId), userId); 3094 } 3095 if ("android".equals(packageName)||"system".equals(packageName)) { 3096 return mAndroidApplication; 3097 } 3098 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3099 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3107 final IPackageDataObserver observer) { 3108 mContext.enforceCallingOrSelfPermission( 3109 android.Manifest.permission.CLEAR_APP_CACHE, null); 3110 // Queue up an async operation since clearing cache may take a little while. 3111 mHandler.post(new Runnable() { 3112 public void run() { 3113 mHandler.removeCallbacks(this); 3114 int retCode = -1; 3115 synchronized (mInstallLock) { 3116 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3117 if (retCode < 0) { 3118 Slog.w(TAG, "Couldn't clear application caches"); 3119 } 3120 } 3121 if (observer != null) { 3122 try { 3123 observer.onRemoveCompleted(null, (retCode >= 0)); 3124 } catch (RemoteException e) { 3125 Slog.w(TAG, "RemoveException when invoking call back"); 3126 } 3127 } 3128 } 3129 }); 3130 } 3131 3132 @Override 3133 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3134 final IntentSender pi) { 3135 mContext.enforceCallingOrSelfPermission( 3136 android.Manifest.permission.CLEAR_APP_CACHE, null); 3137 // Queue up an async operation since clearing cache may take a little while. 3138 mHandler.post(new Runnable() { 3139 public void run() { 3140 mHandler.removeCallbacks(this); 3141 int retCode = -1; 3142 synchronized (mInstallLock) { 3143 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3144 if (retCode < 0) { 3145 Slog.w(TAG, "Couldn't clear application caches"); 3146 } 3147 } 3148 if(pi != null) { 3149 try { 3150 // Callback via pending intent 3151 int code = (retCode >= 0) ? 1 : 0; 3152 pi.sendIntent(null, code, null, 3153 null, null); 3154 } catch (SendIntentException e1) { 3155 Slog.i(TAG, "Failed to send pending intent"); 3156 } 3157 } 3158 } 3159 }); 3160 } 3161 3162 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3163 synchronized (mInstallLock) { 3164 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3165 throw new IOException("Failed to free enough space"); 3166 } 3167 } 3168 } 3169 3170 /** 3171 * Return if the user key is currently unlocked. 3172 */ 3173 private boolean isUserKeyUnlocked(int userId) { 3174 if (StorageManager.isFileBasedEncryptionEnabled()) { 3175 final IMountService mount = IMountService.Stub 3176 .asInterface(ServiceManager.getService("mount")); 3177 if (mount == null) { 3178 Slog.w(TAG, "Early during boot, assuming locked"); 3179 return false; 3180 } 3181 final long token = Binder.clearCallingIdentity(); 3182 try { 3183 return mount.isUserKeyUnlocked(userId); 3184 } catch (RemoteException e) { 3185 throw e.rethrowAsRuntimeException(); 3186 } finally { 3187 Binder.restoreCallingIdentity(token); 3188 } 3189 } else { 3190 return true; 3191 } 3192 } 3193 3194 /** 3195 * Augment the given flags depending on current user running state. This is 3196 * purposefully done before acquiring {@link #mPackages} lock. 3197 */ 3198 private int augmentFlagsForUser(int flags, int userId) { 3199 if (!isUserKeyUnlocked(userId)) { 3200 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3201 } 3202 return flags; 3203 } 3204 3205 @Override 3206 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3207 if (!sUserManager.exists(userId)) return null; 3208 flags = augmentFlagsForUser(flags, userId); 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3210 synchronized (mPackages) { 3211 PackageParser.Activity a = mActivities.mActivities.get(component); 3212 3213 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3214 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3215 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3216 if (ps == null) return null; 3217 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3218 userId); 3219 } 3220 if (mResolveComponentName.equals(component)) { 3221 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3222 new PackageUserState(), userId); 3223 } 3224 } 3225 return null; 3226 } 3227 3228 @Override 3229 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3230 String resolvedType) { 3231 synchronized (mPackages) { 3232 if (component.equals(mResolveComponentName)) { 3233 // The resolver supports EVERYTHING! 3234 return true; 3235 } 3236 PackageParser.Activity a = mActivities.mActivities.get(component); 3237 if (a == null) { 3238 return false; 3239 } 3240 for (int i=0; i<a.intents.size(); i++) { 3241 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3242 intent.getData(), intent.getCategories(), TAG) >= 0) { 3243 return true; 3244 } 3245 } 3246 return false; 3247 } 3248 } 3249 3250 @Override 3251 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3252 if (!sUserManager.exists(userId)) return null; 3253 flags = augmentFlagsForUser(flags, userId); 3254 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3255 synchronized (mPackages) { 3256 PackageParser.Activity a = mReceivers.mActivities.get(component); 3257 if (DEBUG_PACKAGE_INFO) Log.v( 3258 TAG, "getReceiverInfo " + component + ": " + a); 3259 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3260 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3261 if (ps == null) return null; 3262 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3263 userId); 3264 } 3265 } 3266 return null; 3267 } 3268 3269 @Override 3270 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3271 if (!sUserManager.exists(userId)) return null; 3272 flags = augmentFlagsForUser(flags, userId); 3273 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3274 synchronized (mPackages) { 3275 PackageParser.Service s = mServices.mServices.get(component); 3276 if (DEBUG_PACKAGE_INFO) Log.v( 3277 TAG, "getServiceInfo " + component + ": " + s); 3278 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3279 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3280 if (ps == null) return null; 3281 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3282 userId); 3283 } 3284 } 3285 return null; 3286 } 3287 3288 @Override 3289 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3290 if (!sUserManager.exists(userId)) return null; 3291 flags = augmentFlagsForUser(flags, userId); 3292 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3293 synchronized (mPackages) { 3294 PackageParser.Provider p = mProviders.mProviders.get(component); 3295 if (DEBUG_PACKAGE_INFO) Log.v( 3296 TAG, "getProviderInfo " + component + ": " + p); 3297 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3298 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3299 if (ps == null) return null; 3300 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3301 userId); 3302 } 3303 } 3304 return null; 3305 } 3306 3307 @Override 3308 public String[] getSystemSharedLibraryNames() { 3309 Set<String> libSet; 3310 synchronized (mPackages) { 3311 libSet = mSharedLibraries.keySet(); 3312 int size = libSet.size(); 3313 if (size > 0) { 3314 String[] libs = new String[size]; 3315 libSet.toArray(libs); 3316 return libs; 3317 } 3318 } 3319 return null; 3320 } 3321 3322 /** 3323 * @hide 3324 */ 3325 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3326 synchronized (mPackages) { 3327 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3328 if (lib != null && lib.apk != null) { 3329 return mPackages.get(lib.apk); 3330 } 3331 } 3332 return null; 3333 } 3334 3335 @Override 3336 public FeatureInfo[] getSystemAvailableFeatures() { 3337 Collection<FeatureInfo> featSet; 3338 synchronized (mPackages) { 3339 featSet = mAvailableFeatures.values(); 3340 int size = featSet.size(); 3341 if (size > 0) { 3342 FeatureInfo[] features = new FeatureInfo[size+1]; 3343 featSet.toArray(features); 3344 FeatureInfo fi = new FeatureInfo(); 3345 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3346 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3347 features[size] = fi; 3348 return features; 3349 } 3350 } 3351 return null; 3352 } 3353 3354 @Override 3355 public boolean hasSystemFeature(String name) { 3356 synchronized (mPackages) { 3357 return mAvailableFeatures.containsKey(name); 3358 } 3359 } 3360 3361 private void checkValidCaller(int uid, int userId) { 3362 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3363 return; 3364 3365 throw new SecurityException("Caller uid=" + uid 3366 + " is not privileged to communicate with user=" + userId); 3367 } 3368 3369 @Override 3370 public int checkPermission(String permName, String pkgName, int userId) { 3371 if (!sUserManager.exists(userId)) { 3372 return PackageManager.PERMISSION_DENIED; 3373 } 3374 3375 synchronized (mPackages) { 3376 final PackageParser.Package p = mPackages.get(pkgName); 3377 if (p != null && p.mExtras != null) { 3378 final PackageSetting ps = (PackageSetting) p.mExtras; 3379 final PermissionsState permissionsState = ps.getPermissionsState(); 3380 if (permissionsState.hasPermission(permName, userId)) { 3381 return PackageManager.PERMISSION_GRANTED; 3382 } 3383 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3384 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3385 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3386 return PackageManager.PERMISSION_GRANTED; 3387 } 3388 } 3389 } 3390 3391 return PackageManager.PERMISSION_DENIED; 3392 } 3393 3394 @Override 3395 public int checkUidPermission(String permName, int uid) { 3396 final int userId = UserHandle.getUserId(uid); 3397 3398 if (!sUserManager.exists(userId)) { 3399 return PackageManager.PERMISSION_DENIED; 3400 } 3401 3402 synchronized (mPackages) { 3403 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3404 if (obj != null) { 3405 final SettingBase ps = (SettingBase) obj; 3406 final PermissionsState permissionsState = ps.getPermissionsState(); 3407 if (permissionsState.hasPermission(permName, userId)) { 3408 return PackageManager.PERMISSION_GRANTED; 3409 } 3410 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3411 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3412 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3413 return PackageManager.PERMISSION_GRANTED; 3414 } 3415 } else { 3416 ArraySet<String> perms = mSystemPermissions.get(uid); 3417 if (perms != null) { 3418 if (perms.contains(permName)) { 3419 return PackageManager.PERMISSION_GRANTED; 3420 } 3421 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3422 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3423 return PackageManager.PERMISSION_GRANTED; 3424 } 3425 } 3426 } 3427 } 3428 3429 return PackageManager.PERMISSION_DENIED; 3430 } 3431 3432 @Override 3433 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3434 if (UserHandle.getCallingUserId() != userId) { 3435 mContext.enforceCallingPermission( 3436 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3437 "isPermissionRevokedByPolicy for user " + userId); 3438 } 3439 3440 if (checkPermission(permission, packageName, userId) 3441 == PackageManager.PERMISSION_GRANTED) { 3442 return false; 3443 } 3444 3445 final long identity = Binder.clearCallingIdentity(); 3446 try { 3447 final int flags = getPermissionFlags(permission, packageName, userId); 3448 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3449 } finally { 3450 Binder.restoreCallingIdentity(identity); 3451 } 3452 } 3453 3454 @Override 3455 public String getPermissionControllerPackageName() { 3456 synchronized (mPackages) { 3457 return mRequiredInstallerPackage; 3458 } 3459 } 3460 3461 /** 3462 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3463 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3464 * @param checkShell TODO(yamasani): 3465 * @param message the message to log on security exception 3466 */ 3467 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3468 boolean checkShell, String message) { 3469 if (userId < 0) { 3470 throw new IllegalArgumentException("Invalid userId " + userId); 3471 } 3472 if (checkShell) { 3473 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3474 } 3475 if (userId == UserHandle.getUserId(callingUid)) return; 3476 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3477 if (requireFullPermission) { 3478 mContext.enforceCallingOrSelfPermission( 3479 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3480 } else { 3481 try { 3482 mContext.enforceCallingOrSelfPermission( 3483 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3484 } catch (SecurityException se) { 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3487 } 3488 } 3489 } 3490 } 3491 3492 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3493 if (callingUid == Process.SHELL_UID) { 3494 if (userHandle >= 0 3495 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3496 throw new SecurityException("Shell does not have permission to access user " 3497 + userHandle); 3498 } else if (userHandle < 0) { 3499 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3500 + Debug.getCallers(3)); 3501 } 3502 } 3503 } 3504 3505 private BasePermission findPermissionTreeLP(String permName) { 3506 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3507 if (permName.startsWith(bp.name) && 3508 permName.length() > bp.name.length() && 3509 permName.charAt(bp.name.length()) == '.') { 3510 return bp; 3511 } 3512 } 3513 return null; 3514 } 3515 3516 private BasePermission checkPermissionTreeLP(String permName) { 3517 if (permName != null) { 3518 BasePermission bp = findPermissionTreeLP(permName); 3519 if (bp != null) { 3520 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3521 return bp; 3522 } 3523 throw new SecurityException("Calling uid " 3524 + Binder.getCallingUid() 3525 + " is not allowed to add to permission tree " 3526 + bp.name + " owned by uid " + bp.uid); 3527 } 3528 } 3529 throw new SecurityException("No permission tree found for " + permName); 3530 } 3531 3532 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3533 if (s1 == null) { 3534 return s2 == null; 3535 } 3536 if (s2 == null) { 3537 return false; 3538 } 3539 if (s1.getClass() != s2.getClass()) { 3540 return false; 3541 } 3542 return s1.equals(s2); 3543 } 3544 3545 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3546 if (pi1.icon != pi2.icon) return false; 3547 if (pi1.logo != pi2.logo) return false; 3548 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3549 if (!compareStrings(pi1.name, pi2.name)) return false; 3550 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3551 // We'll take care of setting this one. 3552 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3553 // These are not currently stored in settings. 3554 //if (!compareStrings(pi1.group, pi2.group)) return false; 3555 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3556 //if (pi1.labelRes != pi2.labelRes) return false; 3557 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3558 return true; 3559 } 3560 3561 int permissionInfoFootprint(PermissionInfo info) { 3562 int size = info.name.length(); 3563 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3564 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3565 return size; 3566 } 3567 3568 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3569 int size = 0; 3570 for (BasePermission perm : mSettings.mPermissions.values()) { 3571 if (perm.uid == tree.uid) { 3572 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3573 } 3574 } 3575 return size; 3576 } 3577 3578 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3579 // We calculate the max size of permissions defined by this uid and throw 3580 // if that plus the size of 'info' would exceed our stated maximum. 3581 if (tree.uid != Process.SYSTEM_UID) { 3582 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3583 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3584 throw new SecurityException("Permission tree size cap exceeded"); 3585 } 3586 } 3587 } 3588 3589 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3590 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3591 throw new SecurityException("Label must be specified in permission"); 3592 } 3593 BasePermission tree = checkPermissionTreeLP(info.name); 3594 BasePermission bp = mSettings.mPermissions.get(info.name); 3595 boolean added = bp == null; 3596 boolean changed = true; 3597 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3598 if (added) { 3599 enforcePermissionCapLocked(info, tree); 3600 bp = new BasePermission(info.name, tree.sourcePackage, 3601 BasePermission.TYPE_DYNAMIC); 3602 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3603 throw new SecurityException( 3604 "Not allowed to modify non-dynamic permission " 3605 + info.name); 3606 } else { 3607 if (bp.protectionLevel == fixedLevel 3608 && bp.perm.owner.equals(tree.perm.owner) 3609 && bp.uid == tree.uid 3610 && comparePermissionInfos(bp.perm.info, info)) { 3611 changed = false; 3612 } 3613 } 3614 bp.protectionLevel = fixedLevel; 3615 info = new PermissionInfo(info); 3616 info.protectionLevel = fixedLevel; 3617 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3618 bp.perm.info.packageName = tree.perm.info.packageName; 3619 bp.uid = tree.uid; 3620 if (added) { 3621 mSettings.mPermissions.put(info.name, bp); 3622 } 3623 if (changed) { 3624 if (!async) { 3625 mSettings.writeLPr(); 3626 } else { 3627 scheduleWriteSettingsLocked(); 3628 } 3629 } 3630 return added; 3631 } 3632 3633 @Override 3634 public boolean addPermission(PermissionInfo info) { 3635 synchronized (mPackages) { 3636 return addPermissionLocked(info, false); 3637 } 3638 } 3639 3640 @Override 3641 public boolean addPermissionAsync(PermissionInfo info) { 3642 synchronized (mPackages) { 3643 return addPermissionLocked(info, true); 3644 } 3645 } 3646 3647 @Override 3648 public void removePermission(String name) { 3649 synchronized (mPackages) { 3650 checkPermissionTreeLP(name); 3651 BasePermission bp = mSettings.mPermissions.get(name); 3652 if (bp != null) { 3653 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3654 throw new SecurityException( 3655 "Not allowed to modify non-dynamic permission " 3656 + name); 3657 } 3658 mSettings.mPermissions.remove(name); 3659 mSettings.writeLPr(); 3660 } 3661 } 3662 } 3663 3664 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3665 BasePermission bp) { 3666 int index = pkg.requestedPermissions.indexOf(bp.name); 3667 if (index == -1) { 3668 throw new SecurityException("Package " + pkg.packageName 3669 + " has not requested permission " + bp.name); 3670 } 3671 if (!bp.isRuntime() && !bp.isDevelopment()) { 3672 throw new SecurityException("Permission " + bp.name 3673 + " is not a changeable permission type"); 3674 } 3675 } 3676 3677 @Override 3678 public void grantRuntimePermission(String packageName, String name, final int userId) { 3679 if (!sUserManager.exists(userId)) { 3680 Log.e(TAG, "No such user:" + userId); 3681 return; 3682 } 3683 3684 mContext.enforceCallingOrSelfPermission( 3685 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3686 "grantRuntimePermission"); 3687 3688 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3689 "grantRuntimePermission"); 3690 3691 final int uid; 3692 final SettingBase sb; 3693 3694 synchronized (mPackages) { 3695 final PackageParser.Package pkg = mPackages.get(packageName); 3696 if (pkg == null) { 3697 throw new IllegalArgumentException("Unknown package: " + packageName); 3698 } 3699 3700 final BasePermission bp = mSettings.mPermissions.get(name); 3701 if (bp == null) { 3702 throw new IllegalArgumentException("Unknown permission: " + name); 3703 } 3704 3705 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3706 3707 // If a permission review is required for legacy apps we represent 3708 // their permissions as always granted runtime ones since we need 3709 // to keep the review required permission flag per user while an 3710 // install permission's state is shared across all users. 3711 if (Build.PERMISSIONS_REVIEW_REQUIRED 3712 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3713 && bp.isRuntime()) { 3714 return; 3715 } 3716 3717 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3718 sb = (SettingBase) pkg.mExtras; 3719 if (sb == null) { 3720 throw new IllegalArgumentException("Unknown package: " + packageName); 3721 } 3722 3723 final PermissionsState permissionsState = sb.getPermissionsState(); 3724 3725 final int flags = permissionsState.getPermissionFlags(name, userId); 3726 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3727 throw new SecurityException("Cannot grant system fixed permission: " 3728 + name + " for package: " + packageName); 3729 } 3730 3731 if (bp.isDevelopment()) { 3732 // Development permissions must be handled specially, since they are not 3733 // normal runtime permissions. For now they apply to all users. 3734 if (permissionsState.grantInstallPermission(bp) != 3735 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3736 scheduleWriteSettingsLocked(); 3737 } 3738 return; 3739 } 3740 3741 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3742 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3743 return; 3744 } 3745 3746 final int result = permissionsState.grantRuntimePermission(bp, userId); 3747 switch (result) { 3748 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3749 return; 3750 } 3751 3752 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3753 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3754 mHandler.post(new Runnable() { 3755 @Override 3756 public void run() { 3757 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3758 } 3759 }); 3760 } 3761 break; 3762 } 3763 3764 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3765 3766 // Not critical if that is lost - app has to request again. 3767 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3768 } 3769 3770 // Only need to do this if user is initialized. Otherwise it's a new user 3771 // and there are no processes running as the user yet and there's no need 3772 // to make an expensive call to remount processes for the changed permissions. 3773 if (READ_EXTERNAL_STORAGE.equals(name) 3774 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3775 final long token = Binder.clearCallingIdentity(); 3776 try { 3777 if (sUserManager.isInitialized(userId)) { 3778 MountServiceInternal mountServiceInternal = LocalServices.getService( 3779 MountServiceInternal.class); 3780 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3781 } 3782 } finally { 3783 Binder.restoreCallingIdentity(token); 3784 } 3785 } 3786 } 3787 3788 @Override 3789 public void revokeRuntimePermission(String packageName, String name, int userId) { 3790 if (!sUserManager.exists(userId)) { 3791 Log.e(TAG, "No such user:" + userId); 3792 return; 3793 } 3794 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3797 "revokeRuntimePermission"); 3798 3799 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3800 "revokeRuntimePermission"); 3801 3802 final int appId; 3803 3804 synchronized (mPackages) { 3805 final PackageParser.Package pkg = mPackages.get(packageName); 3806 if (pkg == null) { 3807 throw new IllegalArgumentException("Unknown package: " + packageName); 3808 } 3809 3810 final BasePermission bp = mSettings.mPermissions.get(name); 3811 if (bp == null) { 3812 throw new IllegalArgumentException("Unknown permission: " + name); 3813 } 3814 3815 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3816 3817 // If a permission review is required for legacy apps we represent 3818 // their permissions as always granted runtime ones since we need 3819 // to keep the review required permission flag per user while an 3820 // install permission's state is shared across all users. 3821 if (Build.PERMISSIONS_REVIEW_REQUIRED 3822 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3823 && bp.isRuntime()) { 3824 return; 3825 } 3826 3827 SettingBase sb = (SettingBase) pkg.mExtras; 3828 if (sb == null) { 3829 throw new IllegalArgumentException("Unknown package: " + packageName); 3830 } 3831 3832 final PermissionsState permissionsState = sb.getPermissionsState(); 3833 3834 final int flags = permissionsState.getPermissionFlags(name, userId); 3835 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3836 throw new SecurityException("Cannot revoke system fixed permission: " 3837 + name + " for package: " + packageName); 3838 } 3839 3840 if (bp.isDevelopment()) { 3841 // Development permissions must be handled specially, since they are not 3842 // normal runtime permissions. For now they apply to all users. 3843 if (permissionsState.revokeInstallPermission(bp) != 3844 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3845 scheduleWriteSettingsLocked(); 3846 } 3847 return; 3848 } 3849 3850 if (permissionsState.revokeRuntimePermission(bp, userId) == 3851 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3852 return; 3853 } 3854 3855 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3856 3857 // Critical, after this call app should never have the permission. 3858 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3859 3860 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3861 } 3862 3863 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3864 } 3865 3866 @Override 3867 public void resetRuntimePermissions() { 3868 mContext.enforceCallingOrSelfPermission( 3869 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3870 "revokeRuntimePermission"); 3871 3872 int callingUid = Binder.getCallingUid(); 3873 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3874 mContext.enforceCallingOrSelfPermission( 3875 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3876 "resetRuntimePermissions"); 3877 } 3878 3879 synchronized (mPackages) { 3880 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3881 for (int userId : UserManagerService.getInstance().getUserIds()) { 3882 final int packageCount = mPackages.size(); 3883 for (int i = 0; i < packageCount; i++) { 3884 PackageParser.Package pkg = mPackages.valueAt(i); 3885 if (!(pkg.mExtras instanceof PackageSetting)) { 3886 continue; 3887 } 3888 PackageSetting ps = (PackageSetting) pkg.mExtras; 3889 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3890 } 3891 } 3892 } 3893 } 3894 3895 @Override 3896 public int getPermissionFlags(String name, String packageName, int userId) { 3897 if (!sUserManager.exists(userId)) { 3898 return 0; 3899 } 3900 3901 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3902 3903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3904 "getPermissionFlags"); 3905 3906 synchronized (mPackages) { 3907 final PackageParser.Package pkg = mPackages.get(packageName); 3908 if (pkg == null) { 3909 throw new IllegalArgumentException("Unknown package: " + packageName); 3910 } 3911 3912 final BasePermission bp = mSettings.mPermissions.get(name); 3913 if (bp == null) { 3914 throw new IllegalArgumentException("Unknown permission: " + name); 3915 } 3916 3917 SettingBase sb = (SettingBase) pkg.mExtras; 3918 if (sb == null) { 3919 throw new IllegalArgumentException("Unknown package: " + packageName); 3920 } 3921 3922 PermissionsState permissionsState = sb.getPermissionsState(); 3923 return permissionsState.getPermissionFlags(name, userId); 3924 } 3925 } 3926 3927 @Override 3928 public void updatePermissionFlags(String name, String packageName, int flagMask, 3929 int flagValues, int userId) { 3930 if (!sUserManager.exists(userId)) { 3931 return; 3932 } 3933 3934 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3935 3936 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3937 "updatePermissionFlags"); 3938 3939 // Only the system can change these flags and nothing else. 3940 if (getCallingUid() != Process.SYSTEM_UID) { 3941 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3942 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3943 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3944 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3945 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3946 } 3947 3948 synchronized (mPackages) { 3949 final PackageParser.Package pkg = mPackages.get(packageName); 3950 if (pkg == null) { 3951 throw new IllegalArgumentException("Unknown package: " + packageName); 3952 } 3953 3954 final BasePermission bp = mSettings.mPermissions.get(name); 3955 if (bp == null) { 3956 throw new IllegalArgumentException("Unknown permission: " + name); 3957 } 3958 3959 SettingBase sb = (SettingBase) pkg.mExtras; 3960 if (sb == null) { 3961 throw new IllegalArgumentException("Unknown package: " + packageName); 3962 } 3963 3964 PermissionsState permissionsState = sb.getPermissionsState(); 3965 3966 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3967 3968 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3969 // Install and runtime permissions are stored in different places, 3970 // so figure out what permission changed and persist the change. 3971 if (permissionsState.getInstallPermissionState(name) != null) { 3972 scheduleWriteSettingsLocked(); 3973 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3974 || hadState) { 3975 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3976 } 3977 } 3978 } 3979 } 3980 3981 /** 3982 * Update the permission flags for all packages and runtime permissions of a user in order 3983 * to allow device or profile owner to remove POLICY_FIXED. 3984 */ 3985 @Override 3986 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3987 if (!sUserManager.exists(userId)) { 3988 return; 3989 } 3990 3991 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3992 3993 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3994 "updatePermissionFlagsForAllApps"); 3995 3996 // Only the system can change system fixed flags. 3997 if (getCallingUid() != Process.SYSTEM_UID) { 3998 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3999 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4000 } 4001 4002 synchronized (mPackages) { 4003 boolean changed = false; 4004 final int packageCount = mPackages.size(); 4005 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4006 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4007 SettingBase sb = (SettingBase) pkg.mExtras; 4008 if (sb == null) { 4009 continue; 4010 } 4011 PermissionsState permissionsState = sb.getPermissionsState(); 4012 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4013 userId, flagMask, flagValues); 4014 } 4015 if (changed) { 4016 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4017 } 4018 } 4019 } 4020 4021 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4022 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4023 != PackageManager.PERMISSION_GRANTED 4024 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4025 != PackageManager.PERMISSION_GRANTED) { 4026 throw new SecurityException(message + " requires " 4027 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4028 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4029 } 4030 } 4031 4032 @Override 4033 public boolean shouldShowRequestPermissionRationale(String permissionName, 4034 String packageName, int userId) { 4035 if (UserHandle.getCallingUserId() != userId) { 4036 mContext.enforceCallingPermission( 4037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4038 "canShowRequestPermissionRationale for user " + userId); 4039 } 4040 4041 final int uid = getPackageUid(packageName, userId); 4042 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4043 return false; 4044 } 4045 4046 if (checkPermission(permissionName, packageName, userId) 4047 == PackageManager.PERMISSION_GRANTED) { 4048 return false; 4049 } 4050 4051 final int flags; 4052 4053 final long identity = Binder.clearCallingIdentity(); 4054 try { 4055 flags = getPermissionFlags(permissionName, 4056 packageName, userId); 4057 } finally { 4058 Binder.restoreCallingIdentity(identity); 4059 } 4060 4061 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4062 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4063 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4064 4065 if ((flags & fixedFlags) != 0) { 4066 return false; 4067 } 4068 4069 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4070 } 4071 4072 @Override 4073 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4074 mContext.enforceCallingOrSelfPermission( 4075 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4076 "addOnPermissionsChangeListener"); 4077 4078 synchronized (mPackages) { 4079 mOnPermissionChangeListeners.addListenerLocked(listener); 4080 } 4081 } 4082 4083 @Override 4084 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4085 synchronized (mPackages) { 4086 mOnPermissionChangeListeners.removeListenerLocked(listener); 4087 } 4088 } 4089 4090 @Override 4091 public boolean isProtectedBroadcast(String actionName) { 4092 synchronized (mPackages) { 4093 return mProtectedBroadcasts.contains(actionName); 4094 } 4095 } 4096 4097 @Override 4098 public int checkSignatures(String pkg1, String pkg2) { 4099 synchronized (mPackages) { 4100 final PackageParser.Package p1 = mPackages.get(pkg1); 4101 final PackageParser.Package p2 = mPackages.get(pkg2); 4102 if (p1 == null || p1.mExtras == null 4103 || p2 == null || p2.mExtras == null) { 4104 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4105 } 4106 return compareSignatures(p1.mSignatures, p2.mSignatures); 4107 } 4108 } 4109 4110 @Override 4111 public int checkUidSignatures(int uid1, int uid2) { 4112 // Map to base uids. 4113 uid1 = UserHandle.getAppId(uid1); 4114 uid2 = UserHandle.getAppId(uid2); 4115 // reader 4116 synchronized (mPackages) { 4117 Signature[] s1; 4118 Signature[] s2; 4119 Object obj = mSettings.getUserIdLPr(uid1); 4120 if (obj != null) { 4121 if (obj instanceof SharedUserSetting) { 4122 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4123 } else if (obj instanceof PackageSetting) { 4124 s1 = ((PackageSetting)obj).signatures.mSignatures; 4125 } else { 4126 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4127 } 4128 } else { 4129 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4130 } 4131 obj = mSettings.getUserIdLPr(uid2); 4132 if (obj != null) { 4133 if (obj instanceof SharedUserSetting) { 4134 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4135 } else if (obj instanceof PackageSetting) { 4136 s2 = ((PackageSetting)obj).signatures.mSignatures; 4137 } else { 4138 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4139 } 4140 } else { 4141 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4142 } 4143 return compareSignatures(s1, s2); 4144 } 4145 } 4146 4147 private void killUid(int appId, int userId, String reason) { 4148 final long identity = Binder.clearCallingIdentity(); 4149 try { 4150 IActivityManager am = ActivityManagerNative.getDefault(); 4151 if (am != null) { 4152 try { 4153 am.killUid(appId, userId, reason); 4154 } catch (RemoteException e) { 4155 /* ignore - same process */ 4156 } 4157 } 4158 } finally { 4159 Binder.restoreCallingIdentity(identity); 4160 } 4161 } 4162 4163 /** 4164 * Compares two sets of signatures. Returns: 4165 * <br /> 4166 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4167 * <br /> 4168 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4169 * <br /> 4170 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4171 * <br /> 4172 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4173 * <br /> 4174 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4175 */ 4176 static int compareSignatures(Signature[] s1, Signature[] s2) { 4177 if (s1 == null) { 4178 return s2 == null 4179 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4180 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4181 } 4182 4183 if (s2 == null) { 4184 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4185 } 4186 4187 if (s1.length != s2.length) { 4188 return PackageManager.SIGNATURE_NO_MATCH; 4189 } 4190 4191 // Since both signature sets are of size 1, we can compare without HashSets. 4192 if (s1.length == 1) { 4193 return s1[0].equals(s2[0]) ? 4194 PackageManager.SIGNATURE_MATCH : 4195 PackageManager.SIGNATURE_NO_MATCH; 4196 } 4197 4198 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4199 for (Signature sig : s1) { 4200 set1.add(sig); 4201 } 4202 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4203 for (Signature sig : s2) { 4204 set2.add(sig); 4205 } 4206 // Make sure s2 contains all signatures in s1. 4207 if (set1.equals(set2)) { 4208 return PackageManager.SIGNATURE_MATCH; 4209 } 4210 return PackageManager.SIGNATURE_NO_MATCH; 4211 } 4212 4213 /** 4214 * If the database version for this type of package (internal storage or 4215 * external storage) is less than the version where package signatures 4216 * were updated, return true. 4217 */ 4218 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4219 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4220 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4221 } 4222 4223 /** 4224 * Used for backward compatibility to make sure any packages with 4225 * certificate chains get upgraded to the new style. {@code existingSigs} 4226 * will be in the old format (since they were stored on disk from before the 4227 * system upgrade) and {@code scannedSigs} will be in the newer format. 4228 */ 4229 private int compareSignaturesCompat(PackageSignatures existingSigs, 4230 PackageParser.Package scannedPkg) { 4231 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4232 return PackageManager.SIGNATURE_NO_MATCH; 4233 } 4234 4235 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4236 for (Signature sig : existingSigs.mSignatures) { 4237 existingSet.add(sig); 4238 } 4239 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4240 for (Signature sig : scannedPkg.mSignatures) { 4241 try { 4242 Signature[] chainSignatures = sig.getChainSignatures(); 4243 for (Signature chainSig : chainSignatures) { 4244 scannedCompatSet.add(chainSig); 4245 } 4246 } catch (CertificateEncodingException e) { 4247 scannedCompatSet.add(sig); 4248 } 4249 } 4250 /* 4251 * Make sure the expanded scanned set contains all signatures in the 4252 * existing one. 4253 */ 4254 if (scannedCompatSet.equals(existingSet)) { 4255 // Migrate the old signatures to the new scheme. 4256 existingSigs.assignSignatures(scannedPkg.mSignatures); 4257 // The new KeySets will be re-added later in the scanning process. 4258 synchronized (mPackages) { 4259 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4260 } 4261 return PackageManager.SIGNATURE_MATCH; 4262 } 4263 return PackageManager.SIGNATURE_NO_MATCH; 4264 } 4265 4266 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4267 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4268 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4269 } 4270 4271 private int compareSignaturesRecover(PackageSignatures existingSigs, 4272 PackageParser.Package scannedPkg) { 4273 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4274 return PackageManager.SIGNATURE_NO_MATCH; 4275 } 4276 4277 String msg = null; 4278 try { 4279 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4280 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4281 + scannedPkg.packageName); 4282 return PackageManager.SIGNATURE_MATCH; 4283 } 4284 } catch (CertificateException e) { 4285 msg = e.getMessage(); 4286 } 4287 4288 logCriticalInfo(Log.INFO, 4289 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4290 return PackageManager.SIGNATURE_NO_MATCH; 4291 } 4292 4293 @Override 4294 public String[] getPackagesForUid(int uid) { 4295 uid = UserHandle.getAppId(uid); 4296 // reader 4297 synchronized (mPackages) { 4298 Object obj = mSettings.getUserIdLPr(uid); 4299 if (obj instanceof SharedUserSetting) { 4300 final SharedUserSetting sus = (SharedUserSetting) obj; 4301 final int N = sus.packages.size(); 4302 final String[] res = new String[N]; 4303 final Iterator<PackageSetting> it = sus.packages.iterator(); 4304 int i = 0; 4305 while (it.hasNext()) { 4306 res[i++] = it.next().name; 4307 } 4308 return res; 4309 } else if (obj instanceof PackageSetting) { 4310 final PackageSetting ps = (PackageSetting) obj; 4311 return new String[] { ps.name }; 4312 } 4313 } 4314 return null; 4315 } 4316 4317 @Override 4318 public String getNameForUid(int uid) { 4319 // reader 4320 synchronized (mPackages) { 4321 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4322 if (obj instanceof SharedUserSetting) { 4323 final SharedUserSetting sus = (SharedUserSetting) obj; 4324 return sus.name + ":" + sus.userId; 4325 } else if (obj instanceof PackageSetting) { 4326 final PackageSetting ps = (PackageSetting) obj; 4327 return ps.name; 4328 } 4329 } 4330 return null; 4331 } 4332 4333 @Override 4334 public int getUidForSharedUser(String sharedUserName) { 4335 if(sharedUserName == null) { 4336 return -1; 4337 } 4338 // reader 4339 synchronized (mPackages) { 4340 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4341 if (suid == null) { 4342 return -1; 4343 } 4344 return suid.userId; 4345 } 4346 } 4347 4348 @Override 4349 public int getFlagsForUid(int uid) { 4350 synchronized (mPackages) { 4351 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4352 if (obj instanceof SharedUserSetting) { 4353 final SharedUserSetting sus = (SharedUserSetting) obj; 4354 return sus.pkgFlags; 4355 } else if (obj instanceof PackageSetting) { 4356 final PackageSetting ps = (PackageSetting) obj; 4357 return ps.pkgFlags; 4358 } 4359 } 4360 return 0; 4361 } 4362 4363 @Override 4364 public int getPrivateFlagsForUid(int uid) { 4365 synchronized (mPackages) { 4366 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4367 if (obj instanceof SharedUserSetting) { 4368 final SharedUserSetting sus = (SharedUserSetting) obj; 4369 return sus.pkgPrivateFlags; 4370 } else if (obj instanceof PackageSetting) { 4371 final PackageSetting ps = (PackageSetting) obj; 4372 return ps.pkgPrivateFlags; 4373 } 4374 } 4375 return 0; 4376 } 4377 4378 @Override 4379 public boolean isUidPrivileged(int uid) { 4380 uid = UserHandle.getAppId(uid); 4381 // reader 4382 synchronized (mPackages) { 4383 Object obj = mSettings.getUserIdLPr(uid); 4384 if (obj instanceof SharedUserSetting) { 4385 final SharedUserSetting sus = (SharedUserSetting) obj; 4386 final Iterator<PackageSetting> it = sus.packages.iterator(); 4387 while (it.hasNext()) { 4388 if (it.next().isPrivileged()) { 4389 return true; 4390 } 4391 } 4392 } else if (obj instanceof PackageSetting) { 4393 final PackageSetting ps = (PackageSetting) obj; 4394 return ps.isPrivileged(); 4395 } 4396 } 4397 return false; 4398 } 4399 4400 @Override 4401 public String[] getAppOpPermissionPackages(String permissionName) { 4402 synchronized (mPackages) { 4403 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4404 if (pkgs == null) { 4405 return null; 4406 } 4407 return pkgs.toArray(new String[pkgs.size()]); 4408 } 4409 } 4410 4411 @Override 4412 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4413 int flags, int userId) { 4414 if (!sUserManager.exists(userId)) return null; 4415 flags = augmentFlagsForUser(flags, userId); 4416 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4417 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4418 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4419 } 4420 4421 @Override 4422 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4423 IntentFilter filter, int match, ComponentName activity) { 4424 final int userId = UserHandle.getCallingUserId(); 4425 if (DEBUG_PREFERRED) { 4426 Log.v(TAG, "setLastChosenActivity intent=" + intent 4427 + " resolvedType=" + resolvedType 4428 + " flags=" + flags 4429 + " filter=" + filter 4430 + " match=" + match 4431 + " activity=" + activity); 4432 filter.dump(new PrintStreamPrinter(System.out), " "); 4433 } 4434 intent.setComponent(null); 4435 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4436 // Find any earlier preferred or last chosen entries and nuke them 4437 findPreferredActivity(intent, resolvedType, 4438 flags, query, 0, false, true, false, userId); 4439 // Add the new activity as the last chosen for this filter 4440 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4441 "Setting last chosen"); 4442 } 4443 4444 @Override 4445 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4446 final int userId = UserHandle.getCallingUserId(); 4447 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4448 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4449 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4450 false, false, false, userId); 4451 } 4452 4453 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4454 MessageDigest digest = null; 4455 try { 4456 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4457 } catch (NoSuchAlgorithmException e) { 4458 // If we can't create a digest, ignore ephemeral apps. 4459 return false; 4460 } 4461 4462 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4463 final byte[] digestBytes = digest.digest(hostBytes); 4464 int shaPrefix = 4465 digestBytes[0] << 24 4466 | digestBytes[1] << 16 4467 | digestBytes[2] << 8 4468 | digestBytes[3] << 0; 4469 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4470 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4471 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4472 // No hash prefix match; there are no ephemeral apps for this domain. 4473 return false; 4474 } 4475 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4476 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4477 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4478 continue; 4479 } 4480 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4481 // No filters; this should never happen. 4482 if (filters.isEmpty()) { 4483 continue; 4484 } 4485 // We have a domain match; resolve the filters to see if anything matches. 4486 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4487 for (int j = filters.size() - 1; j >= 0; --j) { 4488 ephemeralResolver.addFilter(filters.get(j)); 4489 } 4490 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4491 intent, resolvedType, false /*defaultOnly*/, userId); 4492 return !ephemeralResolveList.isEmpty(); 4493 } 4494 // Hash or filter mis-match; no ephemeral apps for this domain. 4495 return false; 4496 } 4497 4498 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4499 int flags, List<ResolveInfo> query, int userId) { 4500 final boolean isWebUri = hasWebURI(intent); 4501 // Check whether or not an ephemeral app exists to handle the URI. 4502 if (isWebUri && mEphemeralResolverConnection != null) { 4503 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4504 boolean hasAlwaysHandler = false; 4505 synchronized (mPackages) { 4506 final int count = query.size(); 4507 for (int n=0; n<count; n++) { 4508 ResolveInfo info = query.get(n); 4509 String packageName = info.activityInfo.packageName; 4510 PackageSetting ps = mSettings.mPackages.get(packageName); 4511 if (ps != null) { 4512 // Try to get the status from User settings first 4513 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4514 int status = (int) (packedStatus >> 32); 4515 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4516 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4517 hasAlwaysHandler = true; 4518 break; 4519 } 4520 } 4521 } 4522 } 4523 4524 // Only consider installing an ephemeral app if there isn't already a verified handler. 4525 // We've determined that there's an ephemeral app available for the URI, ignore any 4526 // ResolveInfo's and just return the ephemeral installer 4527 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4528 if (DEBUG_EPHEMERAL) { 4529 Slog.v(TAG, "Resolving to the ephemeral installer"); 4530 } 4531 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4532 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4533 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4534 // make a deep copy of the applicationInfo 4535 ri.activityInfo.applicationInfo = new ApplicationInfo( 4536 ri.activityInfo.applicationInfo); 4537 if (userId != 0) { 4538 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4539 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4540 } 4541 return ri; 4542 } 4543 } 4544 if (query != null) { 4545 final int N = query.size(); 4546 if (N == 1) { 4547 return query.get(0); 4548 } else if (N > 1) { 4549 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4550 // If there is more than one activity with the same priority, 4551 // then let the user decide between them. 4552 ResolveInfo r0 = query.get(0); 4553 ResolveInfo r1 = query.get(1); 4554 if (DEBUG_INTENT_MATCHING || debug) { 4555 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4556 + r1.activityInfo.name + "=" + r1.priority); 4557 } 4558 // If the first activity has a higher priority, or a different 4559 // default, then it is always desireable to pick it. 4560 if (r0.priority != r1.priority 4561 || r0.preferredOrder != r1.preferredOrder 4562 || r0.isDefault != r1.isDefault) { 4563 return query.get(0); 4564 } 4565 // If we have saved a preference for a preferred activity for 4566 // this Intent, use that. 4567 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4568 flags, query, r0.priority, true, false, debug, userId); 4569 if (ri != null) { 4570 return ri; 4571 } 4572 ri = new ResolveInfo(mResolveInfo); 4573 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4574 ri.activityInfo.applicationInfo = new ApplicationInfo( 4575 ri.activityInfo.applicationInfo); 4576 if (userId != 0) { 4577 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4578 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4579 } 4580 // Make sure that the resolver is displayable in car mode 4581 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4582 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4583 return ri; 4584 } 4585 } 4586 return null; 4587 } 4588 4589 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4590 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4591 final int N = query.size(); 4592 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4593 .get(userId); 4594 // Get the list of persistent preferred activities that handle the intent 4595 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4596 List<PersistentPreferredActivity> pprefs = ppir != null 4597 ? ppir.queryIntent(intent, resolvedType, 4598 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4599 : null; 4600 if (pprefs != null && pprefs.size() > 0) { 4601 final int M = pprefs.size(); 4602 for (int i=0; i<M; i++) { 4603 final PersistentPreferredActivity ppa = pprefs.get(i); 4604 if (DEBUG_PREFERRED || debug) { 4605 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4606 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4607 + "\n component=" + ppa.mComponent); 4608 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4609 } 4610 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4611 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4612 if (DEBUG_PREFERRED || debug) { 4613 Slog.v(TAG, "Found persistent preferred activity:"); 4614 if (ai != null) { 4615 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4616 } else { 4617 Slog.v(TAG, " null"); 4618 } 4619 } 4620 if (ai == null) { 4621 // This previously registered persistent preferred activity 4622 // component is no longer known. Ignore it and do NOT remove it. 4623 continue; 4624 } 4625 for (int j=0; j<N; j++) { 4626 final ResolveInfo ri = query.get(j); 4627 if (!ri.activityInfo.applicationInfo.packageName 4628 .equals(ai.applicationInfo.packageName)) { 4629 continue; 4630 } 4631 if (!ri.activityInfo.name.equals(ai.name)) { 4632 continue; 4633 } 4634 // Found a persistent preference that can handle the intent. 4635 if (DEBUG_PREFERRED || debug) { 4636 Slog.v(TAG, "Returning persistent preferred activity: " + 4637 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4638 } 4639 return ri; 4640 } 4641 } 4642 } 4643 return null; 4644 } 4645 4646 // TODO: handle preferred activities missing while user has amnesia 4647 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4648 List<ResolveInfo> query, int priority, boolean always, 4649 boolean removeMatches, boolean debug, int userId) { 4650 if (!sUserManager.exists(userId)) return null; 4651 flags = augmentFlagsForUser(flags, userId); 4652 // writer 4653 synchronized (mPackages) { 4654 if (intent.getSelector() != null) { 4655 intent = intent.getSelector(); 4656 } 4657 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4658 4659 // Try to find a matching persistent preferred activity. 4660 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4661 debug, userId); 4662 4663 // If a persistent preferred activity matched, use it. 4664 if (pri != null) { 4665 return pri; 4666 } 4667 4668 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4669 // Get the list of preferred activities that handle the intent 4670 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4671 List<PreferredActivity> prefs = pir != null 4672 ? pir.queryIntent(intent, resolvedType, 4673 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4674 : null; 4675 if (prefs != null && prefs.size() > 0) { 4676 boolean changed = false; 4677 try { 4678 // First figure out how good the original match set is. 4679 // We will only allow preferred activities that came 4680 // from the same match quality. 4681 int match = 0; 4682 4683 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4684 4685 final int N = query.size(); 4686 for (int j=0; j<N; j++) { 4687 final ResolveInfo ri = query.get(j); 4688 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4689 + ": 0x" + Integer.toHexString(match)); 4690 if (ri.match > match) { 4691 match = ri.match; 4692 } 4693 } 4694 4695 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4696 + Integer.toHexString(match)); 4697 4698 match &= IntentFilter.MATCH_CATEGORY_MASK; 4699 final int M = prefs.size(); 4700 for (int i=0; i<M; i++) { 4701 final PreferredActivity pa = prefs.get(i); 4702 if (DEBUG_PREFERRED || debug) { 4703 Slog.v(TAG, "Checking PreferredActivity ds=" 4704 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4705 + "\n component=" + pa.mPref.mComponent); 4706 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4707 } 4708 if (pa.mPref.mMatch != match) { 4709 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4710 + Integer.toHexString(pa.mPref.mMatch)); 4711 continue; 4712 } 4713 // If it's not an "always" type preferred activity and that's what we're 4714 // looking for, skip it. 4715 if (always && !pa.mPref.mAlways) { 4716 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4717 continue; 4718 } 4719 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4720 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4721 if (DEBUG_PREFERRED || debug) { 4722 Slog.v(TAG, "Found preferred activity:"); 4723 if (ai != null) { 4724 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4725 } else { 4726 Slog.v(TAG, " null"); 4727 } 4728 } 4729 if (ai == null) { 4730 // This previously registered preferred activity 4731 // component is no longer known. Most likely an update 4732 // to the app was installed and in the new version this 4733 // component no longer exists. Clean it up by removing 4734 // it from the preferred activities list, and skip it. 4735 Slog.w(TAG, "Removing dangling preferred activity: " 4736 + pa.mPref.mComponent); 4737 pir.removeFilter(pa); 4738 changed = true; 4739 continue; 4740 } 4741 for (int j=0; j<N; j++) { 4742 final ResolveInfo ri = query.get(j); 4743 if (!ri.activityInfo.applicationInfo.packageName 4744 .equals(ai.applicationInfo.packageName)) { 4745 continue; 4746 } 4747 if (!ri.activityInfo.name.equals(ai.name)) { 4748 continue; 4749 } 4750 4751 if (removeMatches) { 4752 pir.removeFilter(pa); 4753 changed = true; 4754 if (DEBUG_PREFERRED) { 4755 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4756 } 4757 break; 4758 } 4759 4760 // Okay we found a previously set preferred or last chosen app. 4761 // If the result set is different from when this 4762 // was created, we need to clear it and re-ask the 4763 // user their preference, if we're looking for an "always" type entry. 4764 if (always && !pa.mPref.sameSet(query)) { 4765 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4766 + intent + " type " + resolvedType); 4767 if (DEBUG_PREFERRED) { 4768 Slog.v(TAG, "Removing preferred activity since set changed " 4769 + pa.mPref.mComponent); 4770 } 4771 pir.removeFilter(pa); 4772 // Re-add the filter as a "last chosen" entry (!always) 4773 PreferredActivity lastChosen = new PreferredActivity( 4774 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4775 pir.addFilter(lastChosen); 4776 changed = true; 4777 return null; 4778 } 4779 4780 // Yay! Either the set matched or we're looking for the last chosen 4781 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4782 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4783 return ri; 4784 } 4785 } 4786 } finally { 4787 if (changed) { 4788 if (DEBUG_PREFERRED) { 4789 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4790 } 4791 scheduleWritePackageRestrictionsLocked(userId); 4792 } 4793 } 4794 } 4795 } 4796 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4797 return null; 4798 } 4799 4800 /* 4801 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4802 */ 4803 @Override 4804 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4805 int targetUserId) { 4806 mContext.enforceCallingOrSelfPermission( 4807 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4808 List<CrossProfileIntentFilter> matches = 4809 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4810 if (matches != null) { 4811 int size = matches.size(); 4812 for (int i = 0; i < size; i++) { 4813 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4814 } 4815 } 4816 if (hasWebURI(intent)) { 4817 // cross-profile app linking works only towards the parent. 4818 final UserInfo parent = getProfileParent(sourceUserId); 4819 synchronized(mPackages) { 4820 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4821 intent, resolvedType, 0, sourceUserId, parent.id); 4822 return xpDomainInfo != null; 4823 } 4824 } 4825 return false; 4826 } 4827 4828 private UserInfo getProfileParent(int userId) { 4829 final long identity = Binder.clearCallingIdentity(); 4830 try { 4831 return sUserManager.getProfileParent(userId); 4832 } finally { 4833 Binder.restoreCallingIdentity(identity); 4834 } 4835 } 4836 4837 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4838 String resolvedType, int userId) { 4839 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4840 if (resolver != null) { 4841 return resolver.queryIntent(intent, resolvedType, false, userId); 4842 } 4843 return null; 4844 } 4845 4846 @Override 4847 public List<ResolveInfo> queryIntentActivities(Intent intent, 4848 String resolvedType, int flags, int userId) { 4849 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4850 flags = augmentFlagsForUser(flags, userId); 4851 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4852 ComponentName comp = intent.getComponent(); 4853 if (comp == null) { 4854 if (intent.getSelector() != null) { 4855 intent = intent.getSelector(); 4856 comp = intent.getComponent(); 4857 } 4858 } 4859 4860 if (comp != null) { 4861 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4862 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4863 if (ai != null) { 4864 final ResolveInfo ri = new ResolveInfo(); 4865 ri.activityInfo = ai; 4866 list.add(ri); 4867 } 4868 return list; 4869 } 4870 4871 // reader 4872 synchronized (mPackages) { 4873 final String pkgName = intent.getPackage(); 4874 if (pkgName == null) { 4875 List<CrossProfileIntentFilter> matchingFilters = 4876 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4877 // Check for results that need to skip the current profile. 4878 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4879 resolvedType, flags, userId); 4880 if (xpResolveInfo != null) { 4881 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4882 result.add(xpResolveInfo); 4883 return filterIfNotSystemUser(result, userId); 4884 } 4885 4886 // Check for results in the current profile. 4887 List<ResolveInfo> result = mActivities.queryIntent( 4888 intent, resolvedType, flags, userId); 4889 result = filterIfNotSystemUser(result, userId); 4890 4891 // Check for cross profile results. 4892 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4893 xpResolveInfo = queryCrossProfileIntents( 4894 matchingFilters, intent, resolvedType, flags, userId, 4895 hasNonNegativePriorityResult); 4896 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4897 boolean isVisibleToUser = filterIfNotSystemUser( 4898 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4899 if (isVisibleToUser) { 4900 result.add(xpResolveInfo); 4901 Collections.sort(result, mResolvePrioritySorter); 4902 } 4903 } 4904 if (hasWebURI(intent)) { 4905 CrossProfileDomainInfo xpDomainInfo = null; 4906 final UserInfo parent = getProfileParent(userId); 4907 if (parent != null) { 4908 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4909 flags, userId, parent.id); 4910 } 4911 if (xpDomainInfo != null) { 4912 if (xpResolveInfo != null) { 4913 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4914 // in the result. 4915 result.remove(xpResolveInfo); 4916 } 4917 if (result.size() == 0) { 4918 result.add(xpDomainInfo.resolveInfo); 4919 return result; 4920 } 4921 } else if (result.size() <= 1) { 4922 return result; 4923 } 4924 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4925 xpDomainInfo, userId); 4926 Collections.sort(result, mResolvePrioritySorter); 4927 } 4928 return result; 4929 } 4930 final PackageParser.Package pkg = mPackages.get(pkgName); 4931 if (pkg != null) { 4932 return filterIfNotSystemUser( 4933 mActivities.queryIntentForPackage( 4934 intent, resolvedType, flags, pkg.activities, userId), 4935 userId); 4936 } 4937 return new ArrayList<ResolveInfo>(); 4938 } 4939 } 4940 4941 private static class CrossProfileDomainInfo { 4942 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4943 ResolveInfo resolveInfo; 4944 /* Best domain verification status of the activities found in the other profile */ 4945 int bestDomainVerificationStatus; 4946 } 4947 4948 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4949 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4950 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4951 sourceUserId)) { 4952 return null; 4953 } 4954 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4955 resolvedType, flags, parentUserId); 4956 4957 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4958 return null; 4959 } 4960 CrossProfileDomainInfo result = null; 4961 int size = resultTargetUser.size(); 4962 for (int i = 0; i < size; i++) { 4963 ResolveInfo riTargetUser = resultTargetUser.get(i); 4964 // Intent filter verification is only for filters that specify a host. So don't return 4965 // those that handle all web uris. 4966 if (riTargetUser.handleAllWebDataURI) { 4967 continue; 4968 } 4969 String packageName = riTargetUser.activityInfo.packageName; 4970 PackageSetting ps = mSettings.mPackages.get(packageName); 4971 if (ps == null) { 4972 continue; 4973 } 4974 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4975 int status = (int)(verificationState >> 32); 4976 if (result == null) { 4977 result = new CrossProfileDomainInfo(); 4978 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4979 sourceUserId, parentUserId); 4980 result.bestDomainVerificationStatus = status; 4981 } else { 4982 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4983 result.bestDomainVerificationStatus); 4984 } 4985 } 4986 // Don't consider matches with status NEVER across profiles. 4987 if (result != null && result.bestDomainVerificationStatus 4988 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4989 return null; 4990 } 4991 return result; 4992 } 4993 4994 /** 4995 * Verification statuses are ordered from the worse to the best, except for 4996 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4997 */ 4998 private int bestDomainVerificationStatus(int status1, int status2) { 4999 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5000 return status2; 5001 } 5002 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5003 return status1; 5004 } 5005 return (int) MathUtils.max(status1, status2); 5006 } 5007 5008 private boolean isUserEnabled(int userId) { 5009 long callingId = Binder.clearCallingIdentity(); 5010 try { 5011 UserInfo userInfo = sUserManager.getUserInfo(userId); 5012 return userInfo != null && userInfo.isEnabled(); 5013 } finally { 5014 Binder.restoreCallingIdentity(callingId); 5015 } 5016 } 5017 5018 /** 5019 * Filter out activities with systemUserOnly flag set, when current user is not System. 5020 * 5021 * @return filtered list 5022 */ 5023 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5024 if (userId == UserHandle.USER_SYSTEM) { 5025 return resolveInfos; 5026 } 5027 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5028 ResolveInfo info = resolveInfos.get(i); 5029 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5030 resolveInfos.remove(i); 5031 } 5032 } 5033 return resolveInfos; 5034 } 5035 5036 /** 5037 * @param resolveInfos list of resolve infos in descending priority order 5038 * @return if the list contains a resolve info with non-negative priority 5039 */ 5040 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5041 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5042 } 5043 5044 private static boolean hasWebURI(Intent intent) { 5045 if (intent.getData() == null) { 5046 return false; 5047 } 5048 final String scheme = intent.getScheme(); 5049 if (TextUtils.isEmpty(scheme)) { 5050 return false; 5051 } 5052 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5053 } 5054 5055 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5056 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5057 int userId) { 5058 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5059 5060 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5061 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5062 candidates.size()); 5063 } 5064 5065 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5066 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5067 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5068 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5069 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5070 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5071 5072 synchronized (mPackages) { 5073 final int count = candidates.size(); 5074 // First, try to use linked apps. Partition the candidates into four lists: 5075 // one for the final results, one for the "do not use ever", one for "undefined status" 5076 // and finally one for "browser app type". 5077 for (int n=0; n<count; n++) { 5078 ResolveInfo info = candidates.get(n); 5079 String packageName = info.activityInfo.packageName; 5080 PackageSetting ps = mSettings.mPackages.get(packageName); 5081 if (ps != null) { 5082 // Add to the special match all list (Browser use case) 5083 if (info.handleAllWebDataURI) { 5084 matchAllList.add(info); 5085 continue; 5086 } 5087 // Try to get the status from User settings first 5088 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5089 int status = (int)(packedStatus >> 32); 5090 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5091 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5092 if (DEBUG_DOMAIN_VERIFICATION) { 5093 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5094 + " : linkgen=" + linkGeneration); 5095 } 5096 // Use link-enabled generation as preferredOrder, i.e. 5097 // prefer newly-enabled over earlier-enabled. 5098 info.preferredOrder = linkGeneration; 5099 alwaysList.add(info); 5100 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5101 if (DEBUG_DOMAIN_VERIFICATION) { 5102 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5103 } 5104 neverList.add(info); 5105 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5106 if (DEBUG_DOMAIN_VERIFICATION) { 5107 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5108 } 5109 alwaysAskList.add(info); 5110 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5111 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5112 if (DEBUG_DOMAIN_VERIFICATION) { 5113 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5114 } 5115 undefinedList.add(info); 5116 } 5117 } 5118 } 5119 5120 // We'll want to include browser possibilities in a few cases 5121 boolean includeBrowser = false; 5122 5123 // First try to add the "always" resolution(s) for the current user, if any 5124 if (alwaysList.size() > 0) { 5125 result.addAll(alwaysList); 5126 } else { 5127 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5128 result.addAll(undefinedList); 5129 // Maybe add one for the other profile. 5130 if (xpDomainInfo != null && ( 5131 xpDomainInfo.bestDomainVerificationStatus 5132 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5133 result.add(xpDomainInfo.resolveInfo); 5134 } 5135 includeBrowser = true; 5136 } 5137 5138 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5139 // If there were 'always' entries their preferred order has been set, so we also 5140 // back that off to make the alternatives equivalent 5141 if (alwaysAskList.size() > 0) { 5142 for (ResolveInfo i : result) { 5143 i.preferredOrder = 0; 5144 } 5145 result.addAll(alwaysAskList); 5146 includeBrowser = true; 5147 } 5148 5149 if (includeBrowser) { 5150 // Also add browsers (all of them or only the default one) 5151 if (DEBUG_DOMAIN_VERIFICATION) { 5152 Slog.v(TAG, " ...including browsers in candidate set"); 5153 } 5154 if ((matchFlags & MATCH_ALL) != 0) { 5155 result.addAll(matchAllList); 5156 } else { 5157 // Browser/generic handling case. If there's a default browser, go straight 5158 // to that (but only if there is no other higher-priority match). 5159 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5160 int maxMatchPrio = 0; 5161 ResolveInfo defaultBrowserMatch = null; 5162 final int numCandidates = matchAllList.size(); 5163 for (int n = 0; n < numCandidates; n++) { 5164 ResolveInfo info = matchAllList.get(n); 5165 // track the highest overall match priority... 5166 if (info.priority > maxMatchPrio) { 5167 maxMatchPrio = info.priority; 5168 } 5169 // ...and the highest-priority default browser match 5170 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5171 if (defaultBrowserMatch == null 5172 || (defaultBrowserMatch.priority < info.priority)) { 5173 if (debug) { 5174 Slog.v(TAG, "Considering default browser match " + info); 5175 } 5176 defaultBrowserMatch = info; 5177 } 5178 } 5179 } 5180 if (defaultBrowserMatch != null 5181 && defaultBrowserMatch.priority >= maxMatchPrio 5182 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5183 { 5184 if (debug) { 5185 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5186 } 5187 result.add(defaultBrowserMatch); 5188 } else { 5189 result.addAll(matchAllList); 5190 } 5191 } 5192 5193 // If there is nothing selected, add all candidates and remove the ones that the user 5194 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5195 if (result.size() == 0) { 5196 result.addAll(candidates); 5197 result.removeAll(neverList); 5198 } 5199 } 5200 } 5201 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5202 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5203 result.size()); 5204 for (ResolveInfo info : result) { 5205 Slog.v(TAG, " + " + info.activityInfo); 5206 } 5207 } 5208 return result; 5209 } 5210 5211 // Returns a packed value as a long: 5212 // 5213 // high 'int'-sized word: link status: undefined/ask/never/always. 5214 // low 'int'-sized word: relative priority among 'always' results. 5215 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5216 long result = ps.getDomainVerificationStatusForUser(userId); 5217 // if none available, get the master status 5218 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5219 if (ps.getIntentFilterVerificationInfo() != null) { 5220 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5221 } 5222 } 5223 return result; 5224 } 5225 5226 private ResolveInfo querySkipCurrentProfileIntents( 5227 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5228 int flags, int sourceUserId) { 5229 if (matchingFilters != null) { 5230 int size = matchingFilters.size(); 5231 for (int i = 0; i < size; i ++) { 5232 CrossProfileIntentFilter filter = matchingFilters.get(i); 5233 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5234 // Checking if there are activities in the target user that can handle the 5235 // intent. 5236 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5237 resolvedType, flags, sourceUserId); 5238 if (resolveInfo != null) { 5239 return resolveInfo; 5240 } 5241 } 5242 } 5243 } 5244 return null; 5245 } 5246 5247 // Return matching ResolveInfo in target user if any. 5248 private ResolveInfo queryCrossProfileIntents( 5249 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5250 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5251 if (matchingFilters != null) { 5252 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5253 // match the same intent. For performance reasons, it is better not to 5254 // run queryIntent twice for the same userId 5255 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5256 int size = matchingFilters.size(); 5257 for (int i = 0; i < size; i++) { 5258 CrossProfileIntentFilter filter = matchingFilters.get(i); 5259 int targetUserId = filter.getTargetUserId(); 5260 boolean skipCurrentProfile = 5261 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5262 boolean skipCurrentProfileIfNoMatchFound = 5263 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5264 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5265 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5266 // Checking if there are activities in the target user that can handle the 5267 // intent. 5268 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5269 resolvedType, flags, sourceUserId); 5270 if (resolveInfo != null) return resolveInfo; 5271 alreadyTriedUserIds.put(targetUserId, true); 5272 } 5273 } 5274 } 5275 return null; 5276 } 5277 5278 /** 5279 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5280 * will forward the intent to the filter's target user. 5281 * Otherwise, returns null. 5282 */ 5283 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5284 String resolvedType, int flags, int sourceUserId) { 5285 int targetUserId = filter.getTargetUserId(); 5286 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5287 resolvedType, flags, targetUserId); 5288 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5289 && isUserEnabled(targetUserId)) { 5290 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5291 } 5292 return null; 5293 } 5294 5295 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5296 int sourceUserId, int targetUserId) { 5297 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5298 long ident = Binder.clearCallingIdentity(); 5299 boolean targetIsProfile; 5300 try { 5301 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5302 } finally { 5303 Binder.restoreCallingIdentity(ident); 5304 } 5305 String className; 5306 if (targetIsProfile) { 5307 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5308 } else { 5309 className = FORWARD_INTENT_TO_PARENT; 5310 } 5311 ComponentName forwardingActivityComponentName = new ComponentName( 5312 mAndroidApplication.packageName, className); 5313 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5314 sourceUserId); 5315 if (!targetIsProfile) { 5316 forwardingActivityInfo.showUserIcon = targetUserId; 5317 forwardingResolveInfo.noResourceId = true; 5318 } 5319 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5320 forwardingResolveInfo.priority = 0; 5321 forwardingResolveInfo.preferredOrder = 0; 5322 forwardingResolveInfo.match = 0; 5323 forwardingResolveInfo.isDefault = true; 5324 forwardingResolveInfo.filter = filter; 5325 forwardingResolveInfo.targetUserId = targetUserId; 5326 return forwardingResolveInfo; 5327 } 5328 5329 @Override 5330 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5331 Intent[] specifics, String[] specificTypes, Intent intent, 5332 String resolvedType, int flags, int userId) { 5333 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5334 flags = augmentFlagsForUser(flags, userId); 5335 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5336 false, "query intent activity options"); 5337 final String resultsAction = intent.getAction(); 5338 5339 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5340 | PackageManager.GET_RESOLVED_FILTER, userId); 5341 5342 if (DEBUG_INTENT_MATCHING) { 5343 Log.v(TAG, "Query " + intent + ": " + results); 5344 } 5345 5346 int specificsPos = 0; 5347 int N; 5348 5349 // todo: note that the algorithm used here is O(N^2). This 5350 // isn't a problem in our current environment, but if we start running 5351 // into situations where we have more than 5 or 10 matches then this 5352 // should probably be changed to something smarter... 5353 5354 // First we go through and resolve each of the specific items 5355 // that were supplied, taking care of removing any corresponding 5356 // duplicate items in the generic resolve list. 5357 if (specifics != null) { 5358 for (int i=0; i<specifics.length; i++) { 5359 final Intent sintent = specifics[i]; 5360 if (sintent == null) { 5361 continue; 5362 } 5363 5364 if (DEBUG_INTENT_MATCHING) { 5365 Log.v(TAG, "Specific #" + i + ": " + sintent); 5366 } 5367 5368 String action = sintent.getAction(); 5369 if (resultsAction != null && resultsAction.equals(action)) { 5370 // If this action was explicitly requested, then don't 5371 // remove things that have it. 5372 action = null; 5373 } 5374 5375 ResolveInfo ri = null; 5376 ActivityInfo ai = null; 5377 5378 ComponentName comp = sintent.getComponent(); 5379 if (comp == null) { 5380 ri = resolveIntent( 5381 sintent, 5382 specificTypes != null ? specificTypes[i] : null, 5383 flags, userId); 5384 if (ri == null) { 5385 continue; 5386 } 5387 if (ri == mResolveInfo) { 5388 // ACK! Must do something better with this. 5389 } 5390 ai = ri.activityInfo; 5391 comp = new ComponentName(ai.applicationInfo.packageName, 5392 ai.name); 5393 } else { 5394 ai = getActivityInfo(comp, flags, userId); 5395 if (ai == null) { 5396 continue; 5397 } 5398 } 5399 5400 // Look for any generic query activities that are duplicates 5401 // of this specific one, and remove them from the results. 5402 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5403 N = results.size(); 5404 int j; 5405 for (j=specificsPos; j<N; j++) { 5406 ResolveInfo sri = results.get(j); 5407 if ((sri.activityInfo.name.equals(comp.getClassName()) 5408 && sri.activityInfo.applicationInfo.packageName.equals( 5409 comp.getPackageName())) 5410 || (action != null && sri.filter.matchAction(action))) { 5411 results.remove(j); 5412 if (DEBUG_INTENT_MATCHING) Log.v( 5413 TAG, "Removing duplicate item from " + j 5414 + " due to specific " + specificsPos); 5415 if (ri == null) { 5416 ri = sri; 5417 } 5418 j--; 5419 N--; 5420 } 5421 } 5422 5423 // Add this specific item to its proper place. 5424 if (ri == null) { 5425 ri = new ResolveInfo(); 5426 ri.activityInfo = ai; 5427 } 5428 results.add(specificsPos, ri); 5429 ri.specificIndex = i; 5430 specificsPos++; 5431 } 5432 } 5433 5434 // Now we go through the remaining generic results and remove any 5435 // duplicate actions that are found here. 5436 N = results.size(); 5437 for (int i=specificsPos; i<N-1; i++) { 5438 final ResolveInfo rii = results.get(i); 5439 if (rii.filter == null) { 5440 continue; 5441 } 5442 5443 // Iterate over all of the actions of this result's intent 5444 // filter... typically this should be just one. 5445 final Iterator<String> it = rii.filter.actionsIterator(); 5446 if (it == null) { 5447 continue; 5448 } 5449 while (it.hasNext()) { 5450 final String action = it.next(); 5451 if (resultsAction != null && resultsAction.equals(action)) { 5452 // If this action was explicitly requested, then don't 5453 // remove things that have it. 5454 continue; 5455 } 5456 for (int j=i+1; j<N; j++) { 5457 final ResolveInfo rij = results.get(j); 5458 if (rij.filter != null && rij.filter.hasAction(action)) { 5459 results.remove(j); 5460 if (DEBUG_INTENT_MATCHING) Log.v( 5461 TAG, "Removing duplicate item from " + j 5462 + " due to action " + action + " at " + i); 5463 j--; 5464 N--; 5465 } 5466 } 5467 } 5468 5469 // If the caller didn't request filter information, drop it now 5470 // so we don't have to marshall/unmarshall it. 5471 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5472 rii.filter = null; 5473 } 5474 } 5475 5476 // Filter out the caller activity if so requested. 5477 if (caller != null) { 5478 N = results.size(); 5479 for (int i=0; i<N; i++) { 5480 ActivityInfo ainfo = results.get(i).activityInfo; 5481 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5482 && caller.getClassName().equals(ainfo.name)) { 5483 results.remove(i); 5484 break; 5485 } 5486 } 5487 } 5488 5489 // If the caller didn't request filter information, 5490 // drop them now so we don't have to 5491 // marshall/unmarshall it. 5492 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5493 N = results.size(); 5494 for (int i=0; i<N; i++) { 5495 results.get(i).filter = null; 5496 } 5497 } 5498 5499 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5500 return results; 5501 } 5502 5503 @Override 5504 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5505 int userId) { 5506 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5507 flags = augmentFlagsForUser(flags, userId); 5508 ComponentName comp = intent.getComponent(); 5509 if (comp == null) { 5510 if (intent.getSelector() != null) { 5511 intent = intent.getSelector(); 5512 comp = intent.getComponent(); 5513 } 5514 } 5515 if (comp != null) { 5516 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5517 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5518 if (ai != null) { 5519 ResolveInfo ri = new ResolveInfo(); 5520 ri.activityInfo = ai; 5521 list.add(ri); 5522 } 5523 return list; 5524 } 5525 5526 // reader 5527 synchronized (mPackages) { 5528 String pkgName = intent.getPackage(); 5529 if (pkgName == null) { 5530 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5531 } 5532 final PackageParser.Package pkg = mPackages.get(pkgName); 5533 if (pkg != null) { 5534 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5535 userId); 5536 } 5537 return null; 5538 } 5539 } 5540 5541 @Override 5542 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5543 if (!sUserManager.exists(userId)) return null; 5544 flags = augmentFlagsForUser(flags, userId); 5545 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5546 if (query != null) { 5547 if (query.size() >= 1) { 5548 // If there is more than one service with the same priority, 5549 // just arbitrarily pick the first one. 5550 return query.get(0); 5551 } 5552 } 5553 return null; 5554 } 5555 5556 @Override 5557 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5558 int userId) { 5559 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5560 flags = augmentFlagsForUser(flags, userId); 5561 ComponentName comp = intent.getComponent(); 5562 if (comp == null) { 5563 if (intent.getSelector() != null) { 5564 intent = intent.getSelector(); 5565 comp = intent.getComponent(); 5566 } 5567 } 5568 if (comp != null) { 5569 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5570 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5571 if (si != null) { 5572 final ResolveInfo ri = new ResolveInfo(); 5573 ri.serviceInfo = si; 5574 list.add(ri); 5575 } 5576 return list; 5577 } 5578 5579 // reader 5580 synchronized (mPackages) { 5581 String pkgName = intent.getPackage(); 5582 if (pkgName == null) { 5583 return mServices.queryIntent(intent, resolvedType, flags, userId); 5584 } 5585 final PackageParser.Package pkg = mPackages.get(pkgName); 5586 if (pkg != null) { 5587 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5588 userId); 5589 } 5590 return null; 5591 } 5592 } 5593 5594 @Override 5595 public List<ResolveInfo> queryIntentContentProviders( 5596 Intent intent, String resolvedType, int flags, int userId) { 5597 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5598 flags = augmentFlagsForUser(flags, userId); 5599 ComponentName comp = intent.getComponent(); 5600 if (comp == null) { 5601 if (intent.getSelector() != null) { 5602 intent = intent.getSelector(); 5603 comp = intent.getComponent(); 5604 } 5605 } 5606 if (comp != null) { 5607 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5608 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5609 if (pi != null) { 5610 final ResolveInfo ri = new ResolveInfo(); 5611 ri.providerInfo = pi; 5612 list.add(ri); 5613 } 5614 return list; 5615 } 5616 5617 // reader 5618 synchronized (mPackages) { 5619 String pkgName = intent.getPackage(); 5620 if (pkgName == null) { 5621 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5622 } 5623 final PackageParser.Package pkg = mPackages.get(pkgName); 5624 if (pkg != null) { 5625 return mProviders.queryIntentForPackage( 5626 intent, resolvedType, flags, pkg.providers, userId); 5627 } 5628 return null; 5629 } 5630 } 5631 5632 @Override 5633 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5634 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5635 5636 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5637 5638 // writer 5639 synchronized (mPackages) { 5640 ArrayList<PackageInfo> list; 5641 if (listUninstalled) { 5642 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5643 for (PackageSetting ps : mSettings.mPackages.values()) { 5644 PackageInfo pi; 5645 if (ps.pkg != null) { 5646 pi = generatePackageInfo(ps.pkg, flags, userId); 5647 } else { 5648 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5649 } 5650 if (pi != null) { 5651 list.add(pi); 5652 } 5653 } 5654 } else { 5655 list = new ArrayList<PackageInfo>(mPackages.size()); 5656 for (PackageParser.Package p : mPackages.values()) { 5657 PackageInfo pi = generatePackageInfo(p, flags, userId); 5658 if (pi != null) { 5659 list.add(pi); 5660 } 5661 } 5662 } 5663 5664 return new ParceledListSlice<PackageInfo>(list); 5665 } 5666 } 5667 5668 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5669 String[] permissions, boolean[] tmp, int flags, int userId) { 5670 int numMatch = 0; 5671 final PermissionsState permissionsState = ps.getPermissionsState(); 5672 for (int i=0; i<permissions.length; i++) { 5673 final String permission = permissions[i]; 5674 if (permissionsState.hasPermission(permission, userId)) { 5675 tmp[i] = true; 5676 numMatch++; 5677 } else { 5678 tmp[i] = false; 5679 } 5680 } 5681 if (numMatch == 0) { 5682 return; 5683 } 5684 PackageInfo pi; 5685 if (ps.pkg != null) { 5686 pi = generatePackageInfo(ps.pkg, flags, userId); 5687 } else { 5688 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5689 } 5690 // The above might return null in cases of uninstalled apps or install-state 5691 // skew across users/profiles. 5692 if (pi != null) { 5693 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5694 if (numMatch == permissions.length) { 5695 pi.requestedPermissions = permissions; 5696 } else { 5697 pi.requestedPermissions = new String[numMatch]; 5698 numMatch = 0; 5699 for (int i=0; i<permissions.length; i++) { 5700 if (tmp[i]) { 5701 pi.requestedPermissions[numMatch] = permissions[i]; 5702 numMatch++; 5703 } 5704 } 5705 } 5706 } 5707 list.add(pi); 5708 } 5709 } 5710 5711 @Override 5712 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5713 String[] permissions, int flags, int userId) { 5714 if (!sUserManager.exists(userId)) return null; 5715 flags = augmentFlagsForUser(flags, userId); 5716 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5717 5718 // writer 5719 synchronized (mPackages) { 5720 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5721 boolean[] tmpBools = new boolean[permissions.length]; 5722 if (listUninstalled) { 5723 for (PackageSetting ps : mSettings.mPackages.values()) { 5724 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5725 } 5726 } else { 5727 for (PackageParser.Package pkg : mPackages.values()) { 5728 PackageSetting ps = (PackageSetting)pkg.mExtras; 5729 if (ps != null) { 5730 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5731 userId); 5732 } 5733 } 5734 } 5735 5736 return new ParceledListSlice<PackageInfo>(list); 5737 } 5738 } 5739 5740 @Override 5741 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5742 if (!sUserManager.exists(userId)) return null; 5743 flags = augmentFlagsForUser(flags, userId); 5744 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5745 5746 // writer 5747 synchronized (mPackages) { 5748 ArrayList<ApplicationInfo> list; 5749 if (listUninstalled) { 5750 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5751 for (PackageSetting ps : mSettings.mPackages.values()) { 5752 ApplicationInfo ai; 5753 if (ps.pkg != null) { 5754 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5755 ps.readUserState(userId), userId); 5756 } else { 5757 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5758 } 5759 if (ai != null) { 5760 list.add(ai); 5761 } 5762 } 5763 } else { 5764 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5765 for (PackageParser.Package p : mPackages.values()) { 5766 if (p.mExtras != null) { 5767 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5768 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5769 if (ai != null) { 5770 list.add(ai); 5771 } 5772 } 5773 } 5774 } 5775 5776 return new ParceledListSlice<ApplicationInfo>(list); 5777 } 5778 } 5779 5780 public List<ApplicationInfo> getPersistentApplications(int flags) { 5781 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5782 5783 // reader 5784 synchronized (mPackages) { 5785 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5786 final int userId = UserHandle.getCallingUserId(); 5787 while (i.hasNext()) { 5788 final PackageParser.Package p = i.next(); 5789 if (p.applicationInfo != null 5790 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5791 && (!mSafeMode || isSystemApp(p))) { 5792 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5793 if (ps != null) { 5794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5795 ps.readUserState(userId), userId); 5796 if (ai != null) { 5797 finalList.add(ai); 5798 } 5799 } 5800 } 5801 } 5802 } 5803 5804 return finalList; 5805 } 5806 5807 @Override 5808 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5809 if (!sUserManager.exists(userId)) return null; 5810 flags = augmentFlagsForUser(flags, userId); 5811 // reader 5812 synchronized (mPackages) { 5813 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5814 PackageSetting ps = provider != null 5815 ? mSettings.mPackages.get(provider.owner.packageName) 5816 : null; 5817 return ps != null 5818 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5819 && (!mSafeMode || (provider.info.applicationInfo.flags 5820 &ApplicationInfo.FLAG_SYSTEM) != 0) 5821 ? PackageParser.generateProviderInfo(provider, flags, 5822 ps.readUserState(userId), userId) 5823 : null; 5824 } 5825 } 5826 5827 /** 5828 * @deprecated 5829 */ 5830 @Deprecated 5831 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5832 // reader 5833 synchronized (mPackages) { 5834 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5835 .entrySet().iterator(); 5836 final int userId = UserHandle.getCallingUserId(); 5837 while (i.hasNext()) { 5838 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5839 PackageParser.Provider p = entry.getValue(); 5840 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5841 5842 if (ps != null && p.syncable 5843 && (!mSafeMode || (p.info.applicationInfo.flags 5844 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5845 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5846 ps.readUserState(userId), userId); 5847 if (info != null) { 5848 outNames.add(entry.getKey()); 5849 outInfo.add(info); 5850 } 5851 } 5852 } 5853 } 5854 } 5855 5856 @Override 5857 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5858 int uid, int flags) { 5859 final int userId = processName != null ? UserHandle.getUserId(uid) 5860 : UserHandle.getCallingUserId(); 5861 if (!sUserManager.exists(userId)) return null; 5862 flags = augmentFlagsForUser(flags, userId); 5863 5864 ArrayList<ProviderInfo> finalList = null; 5865 // reader 5866 synchronized (mPackages) { 5867 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5868 while (i.hasNext()) { 5869 final PackageParser.Provider p = i.next(); 5870 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5871 if (ps != null && p.info.authority != null 5872 && (processName == null 5873 || (p.info.processName.equals(processName) 5874 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5875 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5876 && (!mSafeMode 5877 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5878 if (finalList == null) { 5879 finalList = new ArrayList<ProviderInfo>(3); 5880 } 5881 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5882 ps.readUserState(userId), userId); 5883 if (info != null) { 5884 finalList.add(info); 5885 } 5886 } 5887 } 5888 } 5889 5890 if (finalList != null) { 5891 Collections.sort(finalList, mProviderInitOrderSorter); 5892 return new ParceledListSlice<ProviderInfo>(finalList); 5893 } 5894 5895 return null; 5896 } 5897 5898 @Override 5899 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5900 int flags) { 5901 // reader 5902 synchronized (mPackages) { 5903 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5904 return PackageParser.generateInstrumentationInfo(i, flags); 5905 } 5906 } 5907 5908 @Override 5909 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5910 int flags) { 5911 ArrayList<InstrumentationInfo> finalList = 5912 new ArrayList<InstrumentationInfo>(); 5913 5914 // reader 5915 synchronized (mPackages) { 5916 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5917 while (i.hasNext()) { 5918 final PackageParser.Instrumentation p = i.next(); 5919 if (targetPackage == null 5920 || targetPackage.equals(p.info.targetPackage)) { 5921 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5922 flags); 5923 if (ii != null) { 5924 finalList.add(ii); 5925 } 5926 } 5927 } 5928 } 5929 5930 return finalList; 5931 } 5932 5933 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5934 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5935 if (overlays == null) { 5936 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5937 return; 5938 } 5939 for (PackageParser.Package opkg : overlays.values()) { 5940 // Not much to do if idmap fails: we already logged the error 5941 // and we certainly don't want to abort installation of pkg simply 5942 // because an overlay didn't fit properly. For these reasons, 5943 // ignore the return value of createIdmapForPackagePairLI. 5944 createIdmapForPackagePairLI(pkg, opkg); 5945 } 5946 } 5947 5948 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5949 PackageParser.Package opkg) { 5950 if (!opkg.mTrustedOverlay) { 5951 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5952 opkg.baseCodePath + ": overlay not trusted"); 5953 return false; 5954 } 5955 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5956 if (overlaySet == null) { 5957 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5958 opkg.baseCodePath + " but target package has no known overlays"); 5959 return false; 5960 } 5961 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5962 // TODO: generate idmap for split APKs 5963 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5964 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5965 + opkg.baseCodePath); 5966 return false; 5967 } 5968 PackageParser.Package[] overlayArray = 5969 overlaySet.values().toArray(new PackageParser.Package[0]); 5970 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5971 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5972 return p1.mOverlayPriority - p2.mOverlayPriority; 5973 } 5974 }; 5975 Arrays.sort(overlayArray, cmp); 5976 5977 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5978 int i = 0; 5979 for (PackageParser.Package p : overlayArray) { 5980 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5981 } 5982 return true; 5983 } 5984 5985 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5986 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5987 try { 5988 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5989 } finally { 5990 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5991 } 5992 } 5993 5994 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5995 final File[] files = dir.listFiles(); 5996 if (ArrayUtils.isEmpty(files)) { 5997 Log.d(TAG, "No files in app dir " + dir); 5998 return; 5999 } 6000 6001 if (DEBUG_PACKAGE_SCANNING) { 6002 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6003 + " flags=0x" + Integer.toHexString(parseFlags)); 6004 } 6005 6006 for (File file : files) { 6007 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6008 && !PackageInstallerService.isStageName(file.getName()); 6009 if (!isPackage) { 6010 // Ignore entries which are not packages 6011 continue; 6012 } 6013 try { 6014 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6015 scanFlags, currentTime, null); 6016 } catch (PackageManagerException e) { 6017 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6018 6019 // Delete invalid userdata apps 6020 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6021 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6022 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6023 if (file.isDirectory()) { 6024 mInstaller.rmPackageDir(file.getAbsolutePath()); 6025 } else { 6026 file.delete(); 6027 } 6028 } 6029 } 6030 } 6031 } 6032 6033 private static File getSettingsProblemFile() { 6034 File dataDir = Environment.getDataDirectory(); 6035 File systemDir = new File(dataDir, "system"); 6036 File fname = new File(systemDir, "uiderrors.txt"); 6037 return fname; 6038 } 6039 6040 static void reportSettingsProblem(int priority, String msg) { 6041 logCriticalInfo(priority, msg); 6042 } 6043 6044 static void logCriticalInfo(int priority, String msg) { 6045 Slog.println(priority, TAG, msg); 6046 EventLogTags.writePmCriticalInfo(msg); 6047 try { 6048 File fname = getSettingsProblemFile(); 6049 FileOutputStream out = new FileOutputStream(fname, true); 6050 PrintWriter pw = new FastPrintWriter(out); 6051 SimpleDateFormat formatter = new SimpleDateFormat(); 6052 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6053 pw.println(dateString + ": " + msg); 6054 pw.close(); 6055 FileUtils.setPermissions( 6056 fname.toString(), 6057 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6058 -1, -1); 6059 } catch (java.io.IOException e) { 6060 } 6061 } 6062 6063 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6064 PackageParser.Package pkg, File srcFile, int parseFlags) 6065 throws PackageManagerException { 6066 if (ps != null 6067 && ps.codePath.equals(srcFile) 6068 && ps.timeStamp == srcFile.lastModified() 6069 && !isCompatSignatureUpdateNeeded(pkg) 6070 && !isRecoverSignatureUpdateNeeded(pkg)) { 6071 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6072 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6073 ArraySet<PublicKey> signingKs; 6074 synchronized (mPackages) { 6075 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6076 } 6077 if (ps.signatures.mSignatures != null 6078 && ps.signatures.mSignatures.length != 0 6079 && signingKs != null) { 6080 // Optimization: reuse the existing cached certificates 6081 // if the package appears to be unchanged. 6082 pkg.mSignatures = ps.signatures.mSignatures; 6083 pkg.mSigningKeys = signingKs; 6084 return; 6085 } 6086 6087 Slog.w(TAG, "PackageSetting for " + ps.name 6088 + " is missing signatures. Collecting certs again to recover them."); 6089 } else { 6090 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6091 } 6092 6093 try { 6094 pp.collectCertificates(pkg, parseFlags); 6095 pp.collectManifestDigest(pkg); 6096 } catch (PackageParserException e) { 6097 throw PackageManagerException.from(e); 6098 } 6099 } 6100 6101 /** 6102 * Traces a package scan. 6103 * @see #scanPackageLI(File, int, int, long, UserHandle) 6104 */ 6105 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6106 long currentTime, UserHandle user) throws PackageManagerException { 6107 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6108 try { 6109 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6110 } finally { 6111 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6112 } 6113 } 6114 6115 /** 6116 * Scans a package and returns the newly parsed package. 6117 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6118 */ 6119 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6120 long currentTime, UserHandle user) throws PackageManagerException { 6121 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6122 parseFlags |= mDefParseFlags; 6123 PackageParser pp = new PackageParser(); 6124 pp.setSeparateProcesses(mSeparateProcesses); 6125 pp.setOnlyCoreApps(mOnlyCore); 6126 pp.setDisplayMetrics(mMetrics); 6127 6128 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6129 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6130 } 6131 6132 final PackageParser.Package pkg; 6133 try { 6134 pkg = pp.parsePackage(scanFile, parseFlags); 6135 } catch (PackageParserException e) { 6136 throw PackageManagerException.from(e); 6137 } 6138 6139 PackageSetting ps = null; 6140 PackageSetting updatedPkg; 6141 // reader 6142 synchronized (mPackages) { 6143 // Look to see if we already know about this package. 6144 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6145 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6146 // This package has been renamed to its original name. Let's 6147 // use that. 6148 ps = mSettings.peekPackageLPr(oldName); 6149 } 6150 // If there was no original package, see one for the real package name. 6151 if (ps == null) { 6152 ps = mSettings.peekPackageLPr(pkg.packageName); 6153 } 6154 // Check to see if this package could be hiding/updating a system 6155 // package. Must look for it either under the original or real 6156 // package name depending on our state. 6157 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6158 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6159 } 6160 boolean updatedPkgBetter = false; 6161 // First check if this is a system package that may involve an update 6162 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6163 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6164 // it needs to drop FLAG_PRIVILEGED. 6165 if (locationIsPrivileged(scanFile)) { 6166 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6167 } else { 6168 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6169 } 6170 6171 if (ps != null && !ps.codePath.equals(scanFile)) { 6172 // The path has changed from what was last scanned... check the 6173 // version of the new path against what we have stored to determine 6174 // what to do. 6175 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6176 if (pkg.mVersionCode <= ps.versionCode) { 6177 // The system package has been updated and the code path does not match 6178 // Ignore entry. Skip it. 6179 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6180 + " ignored: updated version " + ps.versionCode 6181 + " better than this " + pkg.mVersionCode); 6182 if (!updatedPkg.codePath.equals(scanFile)) { 6183 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6184 + ps.name + " changing from " + updatedPkg.codePathString 6185 + " to " + scanFile); 6186 updatedPkg.codePath = scanFile; 6187 updatedPkg.codePathString = scanFile.toString(); 6188 updatedPkg.resourcePath = scanFile; 6189 updatedPkg.resourcePathString = scanFile.toString(); 6190 } 6191 updatedPkg.pkg = pkg; 6192 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6193 "Package " + ps.name + " at " + scanFile 6194 + " ignored: updated version " + ps.versionCode 6195 + " better than this " + pkg.mVersionCode); 6196 } else { 6197 // The current app on the system partition is better than 6198 // what we have updated to on the data partition; switch 6199 // back to the system partition version. 6200 // At this point, its safely assumed that package installation for 6201 // apps in system partition will go through. If not there won't be a working 6202 // version of the app 6203 // writer 6204 synchronized (mPackages) { 6205 // Just remove the loaded entries from package lists. 6206 mPackages.remove(ps.name); 6207 } 6208 6209 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6210 + " reverting from " + ps.codePathString 6211 + ": new version " + pkg.mVersionCode 6212 + " better than installed " + ps.versionCode); 6213 6214 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6215 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6216 synchronized (mInstallLock) { 6217 args.cleanUpResourcesLI(); 6218 } 6219 synchronized (mPackages) { 6220 mSettings.enableSystemPackageLPw(ps.name); 6221 } 6222 updatedPkgBetter = true; 6223 } 6224 } 6225 } 6226 6227 if (updatedPkg != null) { 6228 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6229 // initially 6230 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6231 6232 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6233 // flag set initially 6234 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6235 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6236 } 6237 } 6238 6239 // Verify certificates against what was last scanned 6240 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6241 6242 /* 6243 * A new system app appeared, but we already had a non-system one of the 6244 * same name installed earlier. 6245 */ 6246 boolean shouldHideSystemApp = false; 6247 if (updatedPkg == null && ps != null 6248 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6249 /* 6250 * Check to make sure the signatures match first. If they don't, 6251 * wipe the installed application and its data. 6252 */ 6253 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6254 != PackageManager.SIGNATURE_MATCH) { 6255 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6256 + " signatures don't match existing userdata copy; removing"); 6257 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6258 ps = null; 6259 } else { 6260 /* 6261 * If the newly-added system app is an older version than the 6262 * already installed version, hide it. It will be scanned later 6263 * and re-added like an update. 6264 */ 6265 if (pkg.mVersionCode <= ps.versionCode) { 6266 shouldHideSystemApp = true; 6267 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6268 + " but new version " + pkg.mVersionCode + " better than installed " 6269 + ps.versionCode + "; hiding system"); 6270 } else { 6271 /* 6272 * The newly found system app is a newer version that the 6273 * one previously installed. Simply remove the 6274 * already-installed application and replace it with our own 6275 * while keeping the application data. 6276 */ 6277 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6278 + " reverting from " + ps.codePathString + ": new version " 6279 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6280 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6281 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6282 synchronized (mInstallLock) { 6283 args.cleanUpResourcesLI(); 6284 } 6285 } 6286 } 6287 } 6288 6289 // The apk is forward locked (not public) if its code and resources 6290 // are kept in different files. (except for app in either system or 6291 // vendor path). 6292 // TODO grab this value from PackageSettings 6293 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6294 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6295 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6296 } 6297 } 6298 6299 // TODO: extend to support forward-locked splits 6300 String resourcePath = null; 6301 String baseResourcePath = null; 6302 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6303 if (ps != null && ps.resourcePathString != null) { 6304 resourcePath = ps.resourcePathString; 6305 baseResourcePath = ps.resourcePathString; 6306 } else { 6307 // Should not happen at all. Just log an error. 6308 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6309 } 6310 } else { 6311 resourcePath = pkg.codePath; 6312 baseResourcePath = pkg.baseCodePath; 6313 } 6314 6315 // Set application objects path explicitly. 6316 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6317 pkg.applicationInfo.setCodePath(pkg.codePath); 6318 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6319 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6320 pkg.applicationInfo.setResourcePath(resourcePath); 6321 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6322 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6323 6324 // Note that we invoke the following method only if we are about to unpack an application 6325 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6326 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6327 6328 /* 6329 * If the system app should be overridden by a previously installed 6330 * data, hide the system app now and let the /data/app scan pick it up 6331 * again. 6332 */ 6333 if (shouldHideSystemApp) { 6334 synchronized (mPackages) { 6335 mSettings.disableSystemPackageLPw(pkg.packageName); 6336 } 6337 } 6338 6339 return scannedPkg; 6340 } 6341 6342 private static String fixProcessName(String defProcessName, 6343 String processName, int uid) { 6344 if (processName == null) { 6345 return defProcessName; 6346 } 6347 return processName; 6348 } 6349 6350 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6351 throws PackageManagerException { 6352 if (pkgSetting.signatures.mSignatures != null) { 6353 // Already existing package. Make sure signatures match 6354 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6355 == PackageManager.SIGNATURE_MATCH; 6356 if (!match) { 6357 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6358 == PackageManager.SIGNATURE_MATCH; 6359 } 6360 if (!match) { 6361 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6362 == PackageManager.SIGNATURE_MATCH; 6363 } 6364 if (!match) { 6365 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6366 + pkg.packageName + " signatures do not match the " 6367 + "previously installed version; ignoring!"); 6368 } 6369 } 6370 6371 // Check for shared user signatures 6372 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6373 // Already existing package. Make sure signatures match 6374 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6375 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6376 if (!match) { 6377 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6378 == PackageManager.SIGNATURE_MATCH; 6379 } 6380 if (!match) { 6381 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6382 == PackageManager.SIGNATURE_MATCH; 6383 } 6384 if (!match) { 6385 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6386 "Package " + pkg.packageName 6387 + " has no signatures that match those in shared user " 6388 + pkgSetting.sharedUser.name + "; ignoring!"); 6389 } 6390 } 6391 } 6392 6393 /** 6394 * Enforces that only the system UID or root's UID can call a method exposed 6395 * via Binder. 6396 * 6397 * @param message used as message if SecurityException is thrown 6398 * @throws SecurityException if the caller is not system or root 6399 */ 6400 private static final void enforceSystemOrRoot(String message) { 6401 final int uid = Binder.getCallingUid(); 6402 if (uid != Process.SYSTEM_UID && uid != 0) { 6403 throw new SecurityException(message); 6404 } 6405 } 6406 6407 @Override 6408 public void performFstrimIfNeeded() { 6409 enforceSystemOrRoot("Only the system can request fstrim"); 6410 6411 // Before everything else, see whether we need to fstrim. 6412 try { 6413 IMountService ms = PackageHelper.getMountService(); 6414 if (ms != null) { 6415 final boolean isUpgrade = isUpgrade(); 6416 boolean doTrim = isUpgrade; 6417 if (doTrim) { 6418 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6419 } else { 6420 final long interval = android.provider.Settings.Global.getLong( 6421 mContext.getContentResolver(), 6422 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6423 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6424 if (interval > 0) { 6425 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6426 if (timeSinceLast > interval) { 6427 doTrim = true; 6428 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6429 + "; running immediately"); 6430 } 6431 } 6432 } 6433 if (doTrim) { 6434 if (!isFirstBoot()) { 6435 try { 6436 ActivityManagerNative.getDefault().showBootMessage( 6437 mContext.getResources().getString( 6438 R.string.android_upgrading_fstrim), true); 6439 } catch (RemoteException e) { 6440 } 6441 } 6442 ms.runMaintenance(); 6443 } 6444 } else { 6445 Slog.e(TAG, "Mount service unavailable!"); 6446 } 6447 } catch (RemoteException e) { 6448 // Can't happen; MountService is local 6449 } 6450 } 6451 6452 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6453 List<ResolveInfo> ris = null; 6454 try { 6455 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6456 intent, null, 0, userId); 6457 } catch (RemoteException e) { 6458 } 6459 ArraySet<String> pkgNames = new ArraySet<String>(); 6460 if (ris != null) { 6461 for (ResolveInfo ri : ris) { 6462 pkgNames.add(ri.activityInfo.packageName); 6463 } 6464 } 6465 return pkgNames; 6466 } 6467 6468 @Override 6469 public void notifyPackageUse(String packageName) { 6470 synchronized (mPackages) { 6471 PackageParser.Package p = mPackages.get(packageName); 6472 if (p == null) { 6473 return; 6474 } 6475 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6476 } 6477 } 6478 6479 @Override 6480 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6481 return performDexOptTraced(packageName, instructionSet); 6482 } 6483 6484 public boolean performDexOpt(String packageName, String instructionSet) { 6485 return performDexOptTraced(packageName, instructionSet); 6486 } 6487 6488 private boolean performDexOptTraced(String packageName, String instructionSet) { 6489 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6490 try { 6491 return performDexOptInternal(packageName, instructionSet); 6492 } finally { 6493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6494 } 6495 } 6496 6497 private boolean performDexOptInternal(String packageName, String instructionSet) { 6498 PackageParser.Package p; 6499 final String targetInstructionSet; 6500 synchronized (mPackages) { 6501 p = mPackages.get(packageName); 6502 if (p == null) { 6503 return false; 6504 } 6505 mPackageUsage.write(false); 6506 6507 targetInstructionSet = instructionSet != null ? instructionSet : 6508 getPrimaryInstructionSet(p.applicationInfo); 6509 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6510 return false; 6511 } 6512 } 6513 long callingId = Binder.clearCallingIdentity(); 6514 try { 6515 synchronized (mInstallLock) { 6516 final String[] instructionSets = new String[] { targetInstructionSet }; 6517 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6518 true /* inclDependencies */); 6519 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6520 } 6521 } finally { 6522 Binder.restoreCallingIdentity(callingId); 6523 } 6524 } 6525 6526 public ArraySet<String> getPackagesThatNeedDexOpt() { 6527 ArraySet<String> pkgs = null; 6528 synchronized (mPackages) { 6529 for (PackageParser.Package p : mPackages.values()) { 6530 if (DEBUG_DEXOPT) { 6531 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6532 } 6533 if (!p.mDexOptPerformed.isEmpty()) { 6534 continue; 6535 } 6536 if (pkgs == null) { 6537 pkgs = new ArraySet<String>(); 6538 } 6539 pkgs.add(p.packageName); 6540 } 6541 } 6542 return pkgs; 6543 } 6544 6545 public void shutdown() { 6546 mPackageUsage.write(true); 6547 } 6548 6549 @Override 6550 public void forceDexOpt(String packageName) { 6551 enforceSystemOrRoot("forceDexOpt"); 6552 6553 PackageParser.Package pkg; 6554 synchronized (mPackages) { 6555 pkg = mPackages.get(packageName); 6556 if (pkg == null) { 6557 throw new IllegalArgumentException("Missing package: " + packageName); 6558 } 6559 } 6560 6561 synchronized (mInstallLock) { 6562 final String[] instructionSets = new String[] { 6563 getPrimaryInstructionSet(pkg.applicationInfo) }; 6564 6565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6566 6567 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6568 true /* inclDependencies */); 6569 6570 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6571 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6572 throw new IllegalStateException("Failed to dexopt: " + res); 6573 } 6574 } 6575 } 6576 6577 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6578 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6579 Slog.w(TAG, "Unable to update from " + oldPkg.name 6580 + " to " + newPkg.packageName 6581 + ": old package not in system partition"); 6582 return false; 6583 } else if (mPackages.get(oldPkg.name) != null) { 6584 Slog.w(TAG, "Unable to update from " + oldPkg.name 6585 + " to " + newPkg.packageName 6586 + ": old package still exists"); 6587 return false; 6588 } 6589 return true; 6590 } 6591 6592 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6593 throws PackageManagerException { 6594 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6595 if (res != 0) { 6596 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6597 "Failed to install " + packageName + ": " + res); 6598 } 6599 6600 final int[] users = sUserManager.getUserIds(); 6601 for (int user : users) { 6602 if (user != 0) { 6603 res = mInstaller.createUserData(volumeUuid, packageName, 6604 UserHandle.getUid(user, uid), user, seinfo); 6605 if (res != 0) { 6606 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6607 "Failed to createUserData " + packageName + ": " + res); 6608 } 6609 } 6610 } 6611 } 6612 6613 private int removeDataDirsLI(String volumeUuid, String packageName) { 6614 int[] users = sUserManager.getUserIds(); 6615 int res = 0; 6616 for (int user : users) { 6617 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6618 if (resInner < 0) { 6619 res = resInner; 6620 } 6621 } 6622 6623 return res; 6624 } 6625 6626 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6627 int[] users = sUserManager.getUserIds(); 6628 int res = 0; 6629 for (int user : users) { 6630 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6631 if (resInner < 0) { 6632 res = resInner; 6633 } 6634 } 6635 return res; 6636 } 6637 6638 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6639 PackageParser.Package changingLib) { 6640 if (file.path != null) { 6641 usesLibraryFiles.add(file.path); 6642 return; 6643 } 6644 PackageParser.Package p = mPackages.get(file.apk); 6645 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6646 // If we are doing this while in the middle of updating a library apk, 6647 // then we need to make sure to use that new apk for determining the 6648 // dependencies here. (We haven't yet finished committing the new apk 6649 // to the package manager state.) 6650 if (p == null || p.packageName.equals(changingLib.packageName)) { 6651 p = changingLib; 6652 } 6653 } 6654 if (p != null) { 6655 usesLibraryFiles.addAll(p.getAllCodePaths()); 6656 } 6657 } 6658 6659 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6660 PackageParser.Package changingLib) throws PackageManagerException { 6661 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6662 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6663 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6664 for (int i=0; i<N; i++) { 6665 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6666 if (file == null) { 6667 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6668 "Package " + pkg.packageName + " requires unavailable shared library " 6669 + pkg.usesLibraries.get(i) + "; failing!"); 6670 } 6671 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6672 } 6673 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6674 for (int i=0; i<N; i++) { 6675 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6676 if (file == null) { 6677 Slog.w(TAG, "Package " + pkg.packageName 6678 + " desires unavailable shared library " 6679 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6680 } else { 6681 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6682 } 6683 } 6684 N = usesLibraryFiles.size(); 6685 if (N > 0) { 6686 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6687 } else { 6688 pkg.usesLibraryFiles = null; 6689 } 6690 } 6691 } 6692 6693 private static boolean hasString(List<String> list, List<String> which) { 6694 if (list == null) { 6695 return false; 6696 } 6697 for (int i=list.size()-1; i>=0; i--) { 6698 for (int j=which.size()-1; j>=0; j--) { 6699 if (which.get(j).equals(list.get(i))) { 6700 return true; 6701 } 6702 } 6703 } 6704 return false; 6705 } 6706 6707 private void updateAllSharedLibrariesLPw() { 6708 for (PackageParser.Package pkg : mPackages.values()) { 6709 try { 6710 updateSharedLibrariesLPw(pkg, null); 6711 } catch (PackageManagerException e) { 6712 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6713 } 6714 } 6715 } 6716 6717 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6718 PackageParser.Package changingPkg) { 6719 ArrayList<PackageParser.Package> res = null; 6720 for (PackageParser.Package pkg : mPackages.values()) { 6721 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6722 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6723 if (res == null) { 6724 res = new ArrayList<PackageParser.Package>(); 6725 } 6726 res.add(pkg); 6727 try { 6728 updateSharedLibrariesLPw(pkg, changingPkg); 6729 } catch (PackageManagerException e) { 6730 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6731 } 6732 } 6733 } 6734 return res; 6735 } 6736 6737 /** 6738 * Derive the value of the {@code cpuAbiOverride} based on the provided 6739 * value and an optional stored value from the package settings. 6740 */ 6741 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6742 String cpuAbiOverride = null; 6743 6744 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6745 cpuAbiOverride = null; 6746 } else if (abiOverride != null) { 6747 cpuAbiOverride = abiOverride; 6748 } else if (settings != null) { 6749 cpuAbiOverride = settings.cpuAbiOverrideString; 6750 } 6751 6752 return cpuAbiOverride; 6753 } 6754 6755 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6756 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6757 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6758 try { 6759 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6760 } finally { 6761 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6762 } 6763 } 6764 6765 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6766 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6767 boolean success = false; 6768 try { 6769 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6770 currentTime, user); 6771 success = true; 6772 return res; 6773 } finally { 6774 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6775 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6776 } 6777 } 6778 } 6779 6780 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6781 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6782 final File scanFile = new File(pkg.codePath); 6783 if (pkg.applicationInfo.getCodePath() == null || 6784 pkg.applicationInfo.getResourcePath() == null) { 6785 // Bail out. The resource and code paths haven't been set. 6786 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6787 "Code and resource paths haven't been set correctly"); 6788 } 6789 6790 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6791 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6792 } else { 6793 // Only allow system apps to be flagged as core apps. 6794 pkg.coreApp = false; 6795 } 6796 6797 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6798 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6799 } 6800 6801 if (mCustomResolverComponentName != null && 6802 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6803 setUpCustomResolverActivity(pkg); 6804 } 6805 6806 if (pkg.packageName.equals("android")) { 6807 synchronized (mPackages) { 6808 if (mAndroidApplication != null) { 6809 Slog.w(TAG, "*************************************************"); 6810 Slog.w(TAG, "Core android package being redefined. Skipping."); 6811 Slog.w(TAG, " file=" + scanFile); 6812 Slog.w(TAG, "*************************************************"); 6813 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6814 "Core android package being redefined. Skipping."); 6815 } 6816 6817 // Set up information for our fall-back user intent resolution activity. 6818 mPlatformPackage = pkg; 6819 pkg.mVersionCode = mSdkVersion; 6820 mAndroidApplication = pkg.applicationInfo; 6821 6822 if (!mResolverReplaced) { 6823 mResolveActivity.applicationInfo = mAndroidApplication; 6824 mResolveActivity.name = ResolverActivity.class.getName(); 6825 mResolveActivity.packageName = mAndroidApplication.packageName; 6826 mResolveActivity.processName = "system:ui"; 6827 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6828 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6829 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6830 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6831 mResolveActivity.exported = true; 6832 mResolveActivity.enabled = true; 6833 mResolveInfo.activityInfo = mResolveActivity; 6834 mResolveInfo.priority = 0; 6835 mResolveInfo.preferredOrder = 0; 6836 mResolveInfo.match = 0; 6837 mResolveComponentName = new ComponentName( 6838 mAndroidApplication.packageName, mResolveActivity.name); 6839 } 6840 } 6841 } 6842 6843 if (DEBUG_PACKAGE_SCANNING) { 6844 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6845 Log.d(TAG, "Scanning package " + pkg.packageName); 6846 } 6847 6848 if (mPackages.containsKey(pkg.packageName) 6849 || mSharedLibraries.containsKey(pkg.packageName)) { 6850 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6851 "Application package " + pkg.packageName 6852 + " already installed. Skipping duplicate."); 6853 } 6854 6855 // If we're only installing presumed-existing packages, require that the 6856 // scanned APK is both already known and at the path previously established 6857 // for it. Previously unknown packages we pick up normally, but if we have an 6858 // a priori expectation about this package's install presence, enforce it. 6859 // With a singular exception for new system packages. When an OTA contains 6860 // a new system package, we allow the codepath to change from a system location 6861 // to the user-installed location. If we don't allow this change, any newer, 6862 // user-installed version of the application will be ignored. 6863 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6864 if (mExpectingBetter.containsKey(pkg.packageName)) { 6865 logCriticalInfo(Log.WARN, 6866 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6867 } else { 6868 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6869 if (known != null) { 6870 if (DEBUG_PACKAGE_SCANNING) { 6871 Log.d(TAG, "Examining " + pkg.codePath 6872 + " and requiring known paths " + known.codePathString 6873 + " & " + known.resourcePathString); 6874 } 6875 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6876 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6877 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6878 "Application package " + pkg.packageName 6879 + " found at " + pkg.applicationInfo.getCodePath() 6880 + " but expected at " + known.codePathString + "; ignoring."); 6881 } 6882 } 6883 } 6884 } 6885 6886 // Initialize package source and resource directories 6887 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6888 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6889 6890 SharedUserSetting suid = null; 6891 PackageSetting pkgSetting = null; 6892 6893 if (!isSystemApp(pkg)) { 6894 // Only system apps can use these features. 6895 pkg.mOriginalPackages = null; 6896 pkg.mRealPackage = null; 6897 pkg.mAdoptPermissions = null; 6898 } 6899 6900 // writer 6901 synchronized (mPackages) { 6902 if (pkg.mSharedUserId != null) { 6903 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6904 if (suid == null) { 6905 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6906 "Creating application package " + pkg.packageName 6907 + " for shared user failed"); 6908 } 6909 if (DEBUG_PACKAGE_SCANNING) { 6910 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6911 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6912 + "): packages=" + suid.packages); 6913 } 6914 } 6915 6916 // Check if we are renaming from an original package name. 6917 PackageSetting origPackage = null; 6918 String realName = null; 6919 if (pkg.mOriginalPackages != null) { 6920 // This package may need to be renamed to a previously 6921 // installed name. Let's check on that... 6922 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6923 if (pkg.mOriginalPackages.contains(renamed)) { 6924 // This package had originally been installed as the 6925 // original name, and we have already taken care of 6926 // transitioning to the new one. Just update the new 6927 // one to continue using the old name. 6928 realName = pkg.mRealPackage; 6929 if (!pkg.packageName.equals(renamed)) { 6930 // Callers into this function may have already taken 6931 // care of renaming the package; only do it here if 6932 // it is not already done. 6933 pkg.setPackageName(renamed); 6934 } 6935 6936 } else { 6937 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6938 if ((origPackage = mSettings.peekPackageLPr( 6939 pkg.mOriginalPackages.get(i))) != null) { 6940 // We do have the package already installed under its 6941 // original name... should we use it? 6942 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6943 // New package is not compatible with original. 6944 origPackage = null; 6945 continue; 6946 } else if (origPackage.sharedUser != null) { 6947 // Make sure uid is compatible between packages. 6948 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6949 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6950 + " to " + pkg.packageName + ": old uid " 6951 + origPackage.sharedUser.name 6952 + " differs from " + pkg.mSharedUserId); 6953 origPackage = null; 6954 continue; 6955 } 6956 } else { 6957 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6958 + pkg.packageName + " to old name " + origPackage.name); 6959 } 6960 break; 6961 } 6962 } 6963 } 6964 } 6965 6966 if (mTransferedPackages.contains(pkg.packageName)) { 6967 Slog.w(TAG, "Package " + pkg.packageName 6968 + " was transferred to another, but its .apk remains"); 6969 } 6970 6971 // Just create the setting, don't add it yet. For already existing packages 6972 // the PkgSetting exists already and doesn't have to be created. 6973 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6974 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6975 pkg.applicationInfo.primaryCpuAbi, 6976 pkg.applicationInfo.secondaryCpuAbi, 6977 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6978 user, false); 6979 if (pkgSetting == null) { 6980 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6981 "Creating application package " + pkg.packageName + " failed"); 6982 } 6983 6984 if (pkgSetting.origPackage != null) { 6985 // If we are first transitioning from an original package, 6986 // fix up the new package's name now. We need to do this after 6987 // looking up the package under its new name, so getPackageLP 6988 // can take care of fiddling things correctly. 6989 pkg.setPackageName(origPackage.name); 6990 6991 // File a report about this. 6992 String msg = "New package " + pkgSetting.realName 6993 + " renamed to replace old package " + pkgSetting.name; 6994 reportSettingsProblem(Log.WARN, msg); 6995 6996 // Make a note of it. 6997 mTransferedPackages.add(origPackage.name); 6998 6999 // No longer need to retain this. 7000 pkgSetting.origPackage = null; 7001 } 7002 7003 if (realName != null) { 7004 // Make a note of it. 7005 mTransferedPackages.add(pkg.packageName); 7006 } 7007 7008 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7009 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7010 } 7011 7012 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7013 // Check all shared libraries and map to their actual file path. 7014 // We only do this here for apps not on a system dir, because those 7015 // are the only ones that can fail an install due to this. We 7016 // will take care of the system apps by updating all of their 7017 // library paths after the scan is done. 7018 updateSharedLibrariesLPw(pkg, null); 7019 } 7020 7021 if (mFoundPolicyFile) { 7022 SELinuxMMAC.assignSeinfoValue(pkg); 7023 } 7024 7025 pkg.applicationInfo.uid = pkgSetting.appId; 7026 pkg.mExtras = pkgSetting; 7027 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7028 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7029 // We just determined the app is signed correctly, so bring 7030 // over the latest parsed certs. 7031 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7032 } else { 7033 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7034 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7035 "Package " + pkg.packageName + " upgrade keys do not match the " 7036 + "previously installed version"); 7037 } else { 7038 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7039 String msg = "System package " + pkg.packageName 7040 + " signature changed; retaining data."; 7041 reportSettingsProblem(Log.WARN, msg); 7042 } 7043 } 7044 } else { 7045 try { 7046 verifySignaturesLP(pkgSetting, pkg); 7047 // We just determined the app is signed correctly, so bring 7048 // over the latest parsed certs. 7049 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7050 } catch (PackageManagerException e) { 7051 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7052 throw e; 7053 } 7054 // The signature has changed, but this package is in the system 7055 // image... let's recover! 7056 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7057 // However... if this package is part of a shared user, but it 7058 // doesn't match the signature of the shared user, let's fail. 7059 // What this means is that you can't change the signatures 7060 // associated with an overall shared user, which doesn't seem all 7061 // that unreasonable. 7062 if (pkgSetting.sharedUser != null) { 7063 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7064 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7065 throw new PackageManagerException( 7066 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7067 "Signature mismatch for shared user : " 7068 + pkgSetting.sharedUser); 7069 } 7070 } 7071 // File a report about this. 7072 String msg = "System package " + pkg.packageName 7073 + " signature changed; retaining data."; 7074 reportSettingsProblem(Log.WARN, msg); 7075 } 7076 } 7077 // Verify that this new package doesn't have any content providers 7078 // that conflict with existing packages. Only do this if the 7079 // package isn't already installed, since we don't want to break 7080 // things that are installed. 7081 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7082 final int N = pkg.providers.size(); 7083 int i; 7084 for (i=0; i<N; i++) { 7085 PackageParser.Provider p = pkg.providers.get(i); 7086 if (p.info.authority != null) { 7087 String names[] = p.info.authority.split(";"); 7088 for (int j = 0; j < names.length; j++) { 7089 if (mProvidersByAuthority.containsKey(names[j])) { 7090 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7091 final String otherPackageName = 7092 ((other != null && other.getComponentName() != null) ? 7093 other.getComponentName().getPackageName() : "?"); 7094 throw new PackageManagerException( 7095 INSTALL_FAILED_CONFLICTING_PROVIDER, 7096 "Can't install because provider name " + names[j] 7097 + " (in package " + pkg.applicationInfo.packageName 7098 + ") is already used by " + otherPackageName); 7099 } 7100 } 7101 } 7102 } 7103 } 7104 7105 if (pkg.mAdoptPermissions != null) { 7106 // This package wants to adopt ownership of permissions from 7107 // another package. 7108 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7109 final String origName = pkg.mAdoptPermissions.get(i); 7110 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7111 if (orig != null) { 7112 if (verifyPackageUpdateLPr(orig, pkg)) { 7113 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7114 + pkg.packageName); 7115 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7116 } 7117 } 7118 } 7119 } 7120 } 7121 7122 final String pkgName = pkg.packageName; 7123 7124 final long scanFileTime = scanFile.lastModified(); 7125 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7126 pkg.applicationInfo.processName = fixProcessName( 7127 pkg.applicationInfo.packageName, 7128 pkg.applicationInfo.processName, 7129 pkg.applicationInfo.uid); 7130 7131 if (pkg != mPlatformPackage) { 7132 // This is a normal package, need to make its data directory. 7133 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7134 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7135 7136 boolean uidError = false; 7137 if (dataPath.exists()) { 7138 int currentUid = 0; 7139 try { 7140 StructStat stat = Os.stat(dataPath.getPath()); 7141 currentUid = stat.st_uid; 7142 } catch (ErrnoException e) { 7143 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7144 } 7145 7146 // If we have mismatched owners for the data path, we have a problem. 7147 if (currentUid != pkg.applicationInfo.uid) { 7148 boolean recovered = false; 7149 if (currentUid == 0) { 7150 // The directory somehow became owned by root. Wow. 7151 // This is probably because the system was stopped while 7152 // installd was in the middle of messing with its libs 7153 // directory. Ask installd to fix that. 7154 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7155 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7156 if (ret >= 0) { 7157 recovered = true; 7158 String msg = "Package " + pkg.packageName 7159 + " unexpectedly changed to uid 0; recovered to " + 7160 + pkg.applicationInfo.uid; 7161 reportSettingsProblem(Log.WARN, msg); 7162 } 7163 } 7164 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7165 || (scanFlags&SCAN_BOOTING) != 0)) { 7166 // If this is a system app, we can at least delete its 7167 // current data so the application will still work. 7168 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7169 if (ret >= 0) { 7170 // TODO: Kill the processes first 7171 // Old data gone! 7172 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7173 ? "System package " : "Third party package "; 7174 String msg = prefix + pkg.packageName 7175 + " has changed from uid: " 7176 + currentUid + " to " 7177 + pkg.applicationInfo.uid + "; old data erased"; 7178 reportSettingsProblem(Log.WARN, msg); 7179 recovered = true; 7180 } 7181 if (!recovered) { 7182 mHasSystemUidErrors = true; 7183 } 7184 } else if (!recovered) { 7185 // If we allow this install to proceed, we will be broken. 7186 // Abort, abort! 7187 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7188 "scanPackageLI"); 7189 } 7190 if (!recovered) { 7191 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7192 + pkg.applicationInfo.uid + "/fs_" 7193 + currentUid; 7194 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7195 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7196 String msg = "Package " + pkg.packageName 7197 + " has mismatched uid: " 7198 + currentUid + " on disk, " 7199 + pkg.applicationInfo.uid + " in settings"; 7200 // writer 7201 synchronized (mPackages) { 7202 mSettings.mReadMessages.append(msg); 7203 mSettings.mReadMessages.append('\n'); 7204 uidError = true; 7205 if (!pkgSetting.uidError) { 7206 reportSettingsProblem(Log.ERROR, msg); 7207 } 7208 } 7209 } 7210 } 7211 7212 // Ensure that directories are prepared 7213 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7214 pkg.applicationInfo.seinfo); 7215 7216 if (mShouldRestoreconData) { 7217 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7218 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7219 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7220 } 7221 } else { 7222 if (DEBUG_PACKAGE_SCANNING) { 7223 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7224 Log.v(TAG, "Want this data dir: " + dataPath); 7225 } 7226 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7227 pkg.applicationInfo.seinfo); 7228 } 7229 7230 // Get all of our default paths setup 7231 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7232 7233 pkgSetting.uidError = uidError; 7234 } 7235 7236 final String path = scanFile.getPath(); 7237 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7238 7239 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7240 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7241 7242 // Some system apps still use directory structure for native libraries 7243 // in which case we might end up not detecting abi solely based on apk 7244 // structure. Try to detect abi based on directory structure. 7245 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7246 pkg.applicationInfo.primaryCpuAbi == null) { 7247 setBundledAppAbisAndRoots(pkg, pkgSetting); 7248 setNativeLibraryPaths(pkg); 7249 } 7250 7251 } else { 7252 if ((scanFlags & SCAN_MOVE) != 0) { 7253 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7254 // but we already have this packages package info in the PackageSetting. We just 7255 // use that and derive the native library path based on the new codepath. 7256 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7257 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7258 } 7259 7260 // Set native library paths again. For moves, the path will be updated based on the 7261 // ABIs we've determined above. For non-moves, the path will be updated based on the 7262 // ABIs we determined during compilation, but the path will depend on the final 7263 // package path (after the rename away from the stage path). 7264 setNativeLibraryPaths(pkg); 7265 } 7266 7267 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7268 final int[] userIds = sUserManager.getUserIds(); 7269 synchronized (mInstallLock) { 7270 // Make sure all user data directories are ready to roll; we're okay 7271 // if they already exist 7272 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7273 for (int userId : userIds) { 7274 if (userId != UserHandle.USER_SYSTEM) { 7275 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7276 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7277 pkg.applicationInfo.seinfo); 7278 } 7279 } 7280 } 7281 7282 // Create a native library symlink only if we have native libraries 7283 // and if the native libraries are 32 bit libraries. We do not provide 7284 // this symlink for 64 bit libraries. 7285 if (pkg.applicationInfo.primaryCpuAbi != null && 7286 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7287 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7288 try { 7289 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7290 for (int userId : userIds) { 7291 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7292 nativeLibPath, userId) < 0) { 7293 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7294 "Failed linking native library dir (user=" + userId + ")"); 7295 } 7296 } 7297 } finally { 7298 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7299 } 7300 } 7301 } 7302 7303 // This is a special case for the "system" package, where the ABI is 7304 // dictated by the zygote configuration (and init.rc). We should keep track 7305 // of this ABI so that we can deal with "normal" applications that run under 7306 // the same UID correctly. 7307 if (mPlatformPackage == pkg) { 7308 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7309 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7310 } 7311 7312 // If there's a mismatch between the abi-override in the package setting 7313 // and the abiOverride specified for the install. Warn about this because we 7314 // would've already compiled the app without taking the package setting into 7315 // account. 7316 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7317 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7318 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7319 " for package: " + pkg.packageName); 7320 } 7321 } 7322 7323 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7324 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7325 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7326 7327 // Copy the derived override back to the parsed package, so that we can 7328 // update the package settings accordingly. 7329 pkg.cpuAbiOverride = cpuAbiOverride; 7330 7331 if (DEBUG_ABI_SELECTION) { 7332 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7333 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7334 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7335 } 7336 7337 // Push the derived path down into PackageSettings so we know what to 7338 // clean up at uninstall time. 7339 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7340 7341 if (DEBUG_ABI_SELECTION) { 7342 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7343 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7344 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7345 } 7346 7347 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7348 // We don't do this here during boot because we can do it all 7349 // at once after scanning all existing packages. 7350 // 7351 // We also do this *before* we perform dexopt on this package, so that 7352 // we can avoid redundant dexopts, and also to make sure we've got the 7353 // code and package path correct. 7354 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7355 pkg, true /* boot complete */); 7356 } 7357 7358 if (mFactoryTest && pkg.requestedPermissions.contains( 7359 android.Manifest.permission.FACTORY_TEST)) { 7360 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7361 } 7362 7363 ArrayList<PackageParser.Package> clientLibPkgs = null; 7364 7365 // writer 7366 synchronized (mPackages) { 7367 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7368 // Only system apps can add new shared libraries. 7369 if (pkg.libraryNames != null) { 7370 for (int i=0; i<pkg.libraryNames.size(); i++) { 7371 String name = pkg.libraryNames.get(i); 7372 boolean allowed = false; 7373 if (pkg.isUpdatedSystemApp()) { 7374 // New library entries can only be added through the 7375 // system image. This is important to get rid of a lot 7376 // of nasty edge cases: for example if we allowed a non- 7377 // system update of the app to add a library, then uninstalling 7378 // the update would make the library go away, and assumptions 7379 // we made such as through app install filtering would now 7380 // have allowed apps on the device which aren't compatible 7381 // with it. Better to just have the restriction here, be 7382 // conservative, and create many fewer cases that can negatively 7383 // impact the user experience. 7384 final PackageSetting sysPs = mSettings 7385 .getDisabledSystemPkgLPr(pkg.packageName); 7386 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7387 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7388 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7389 allowed = true; 7390 break; 7391 } 7392 } 7393 } 7394 } else { 7395 allowed = true; 7396 } 7397 if (allowed) { 7398 if (!mSharedLibraries.containsKey(name)) { 7399 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7400 } else if (!name.equals(pkg.packageName)) { 7401 Slog.w(TAG, "Package " + pkg.packageName + " library " 7402 + name + " already exists; skipping"); 7403 } 7404 } else { 7405 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7406 + name + " that is not declared on system image; skipping"); 7407 } 7408 } 7409 if ((scanFlags & SCAN_BOOTING) == 0) { 7410 // If we are not booting, we need to update any applications 7411 // that are clients of our shared library. If we are booting, 7412 // this will all be done once the scan is complete. 7413 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7414 } 7415 } 7416 } 7417 } 7418 7419 // Request the ActivityManager to kill the process(only for existing packages) 7420 // so that we do not end up in a confused state while the user is still using the older 7421 // version of the application while the new one gets installed. 7422 if ((scanFlags & SCAN_REPLACING) != 0) { 7423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7424 7425 killApplication(pkg.applicationInfo.packageName, 7426 pkg.applicationInfo.uid, "replace pkg"); 7427 7428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7429 } 7430 7431 // Also need to kill any apps that are dependent on the library. 7432 if (clientLibPkgs != null) { 7433 for (int i=0; i<clientLibPkgs.size(); i++) { 7434 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7435 killApplication(clientPkg.applicationInfo.packageName, 7436 clientPkg.applicationInfo.uid, "update lib"); 7437 } 7438 } 7439 7440 // Make sure we're not adding any bogus keyset info 7441 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7442 ksms.assertScannedPackageValid(pkg); 7443 7444 // writer 7445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7446 7447 boolean createIdmapFailed = false; 7448 synchronized (mPackages) { 7449 // We don't expect installation to fail beyond this point 7450 7451 // Add the new setting to mSettings 7452 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7453 // Add the new setting to mPackages 7454 mPackages.put(pkg.applicationInfo.packageName, pkg); 7455 // Make sure we don't accidentally delete its data. 7456 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7457 while (iter.hasNext()) { 7458 PackageCleanItem item = iter.next(); 7459 if (pkgName.equals(item.packageName)) { 7460 iter.remove(); 7461 } 7462 } 7463 7464 // Take care of first install / last update times. 7465 if (currentTime != 0) { 7466 if (pkgSetting.firstInstallTime == 0) { 7467 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7468 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7469 pkgSetting.lastUpdateTime = currentTime; 7470 } 7471 } else if (pkgSetting.firstInstallTime == 0) { 7472 // We need *something*. Take time time stamp of the file. 7473 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7474 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7475 if (scanFileTime != pkgSetting.timeStamp) { 7476 // A package on the system image has changed; consider this 7477 // to be an update. 7478 pkgSetting.lastUpdateTime = scanFileTime; 7479 } 7480 } 7481 7482 // Add the package's KeySets to the global KeySetManagerService 7483 ksms.addScannedPackageLPw(pkg); 7484 7485 int N = pkg.providers.size(); 7486 StringBuilder r = null; 7487 int i; 7488 for (i=0; i<N; i++) { 7489 PackageParser.Provider p = pkg.providers.get(i); 7490 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7491 p.info.processName, pkg.applicationInfo.uid); 7492 mProviders.addProvider(p); 7493 p.syncable = p.info.isSyncable; 7494 if (p.info.authority != null) { 7495 String names[] = p.info.authority.split(";"); 7496 p.info.authority = null; 7497 for (int j = 0; j < names.length; j++) { 7498 if (j == 1 && p.syncable) { 7499 // We only want the first authority for a provider to possibly be 7500 // syncable, so if we already added this provider using a different 7501 // authority clear the syncable flag. We copy the provider before 7502 // changing it because the mProviders object contains a reference 7503 // to a provider that we don't want to change. 7504 // Only do this for the second authority since the resulting provider 7505 // object can be the same for all future authorities for this provider. 7506 p = new PackageParser.Provider(p); 7507 p.syncable = false; 7508 } 7509 if (!mProvidersByAuthority.containsKey(names[j])) { 7510 mProvidersByAuthority.put(names[j], p); 7511 if (p.info.authority == null) { 7512 p.info.authority = names[j]; 7513 } else { 7514 p.info.authority = p.info.authority + ";" + names[j]; 7515 } 7516 if (DEBUG_PACKAGE_SCANNING) { 7517 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7518 Log.d(TAG, "Registered content provider: " + names[j] 7519 + ", className = " + p.info.name + ", isSyncable = " 7520 + p.info.isSyncable); 7521 } 7522 } else { 7523 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7524 Slog.w(TAG, "Skipping provider name " + names[j] + 7525 " (in package " + pkg.applicationInfo.packageName + 7526 "): name already used by " 7527 + ((other != null && other.getComponentName() != null) 7528 ? other.getComponentName().getPackageName() : "?")); 7529 } 7530 } 7531 } 7532 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7533 if (r == null) { 7534 r = new StringBuilder(256); 7535 } else { 7536 r.append(' '); 7537 } 7538 r.append(p.info.name); 7539 } 7540 } 7541 if (r != null) { 7542 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7543 } 7544 7545 N = pkg.services.size(); 7546 r = null; 7547 for (i=0; i<N; i++) { 7548 PackageParser.Service s = pkg.services.get(i); 7549 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7550 s.info.processName, pkg.applicationInfo.uid); 7551 mServices.addService(s); 7552 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7553 if (r == null) { 7554 r = new StringBuilder(256); 7555 } else { 7556 r.append(' '); 7557 } 7558 r.append(s.info.name); 7559 } 7560 } 7561 if (r != null) { 7562 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7563 } 7564 7565 N = pkg.receivers.size(); 7566 r = null; 7567 for (i=0; i<N; i++) { 7568 PackageParser.Activity a = pkg.receivers.get(i); 7569 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7570 a.info.processName, pkg.applicationInfo.uid); 7571 mReceivers.addActivity(a, "receiver"); 7572 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7573 if (r == null) { 7574 r = new StringBuilder(256); 7575 } else { 7576 r.append(' '); 7577 } 7578 r.append(a.info.name); 7579 } 7580 } 7581 if (r != null) { 7582 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7583 } 7584 7585 N = pkg.activities.size(); 7586 r = null; 7587 for (i=0; i<N; i++) { 7588 PackageParser.Activity a = pkg.activities.get(i); 7589 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7590 a.info.processName, pkg.applicationInfo.uid); 7591 mActivities.addActivity(a, "activity"); 7592 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7593 if (r == null) { 7594 r = new StringBuilder(256); 7595 } else { 7596 r.append(' '); 7597 } 7598 r.append(a.info.name); 7599 } 7600 } 7601 if (r != null) { 7602 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7603 } 7604 7605 N = pkg.permissionGroups.size(); 7606 r = null; 7607 for (i=0; i<N; i++) { 7608 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7609 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7610 if (cur == null) { 7611 mPermissionGroups.put(pg.info.name, pg); 7612 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7613 if (r == null) { 7614 r = new StringBuilder(256); 7615 } else { 7616 r.append(' '); 7617 } 7618 r.append(pg.info.name); 7619 } 7620 } else { 7621 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7622 + pg.info.packageName + " ignored: original from " 7623 + cur.info.packageName); 7624 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7625 if (r == null) { 7626 r = new StringBuilder(256); 7627 } else { 7628 r.append(' '); 7629 } 7630 r.append("DUP:"); 7631 r.append(pg.info.name); 7632 } 7633 } 7634 } 7635 if (r != null) { 7636 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7637 } 7638 7639 N = pkg.permissions.size(); 7640 r = null; 7641 for (i=0; i<N; i++) { 7642 PackageParser.Permission p = pkg.permissions.get(i); 7643 7644 // Assume by default that we did not install this permission into the system. 7645 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7646 7647 // Now that permission groups have a special meaning, we ignore permission 7648 // groups for legacy apps to prevent unexpected behavior. In particular, 7649 // permissions for one app being granted to someone just becuase they happen 7650 // to be in a group defined by another app (before this had no implications). 7651 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7652 p.group = mPermissionGroups.get(p.info.group); 7653 // Warn for a permission in an unknown group. 7654 if (p.info.group != null && p.group == null) { 7655 Slog.w(TAG, "Permission " + p.info.name + " from package " 7656 + p.info.packageName + " in an unknown group " + p.info.group); 7657 } 7658 } 7659 7660 ArrayMap<String, BasePermission> permissionMap = 7661 p.tree ? mSettings.mPermissionTrees 7662 : mSettings.mPermissions; 7663 BasePermission bp = permissionMap.get(p.info.name); 7664 7665 // Allow system apps to redefine non-system permissions 7666 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7667 final boolean currentOwnerIsSystem = (bp.perm != null 7668 && isSystemApp(bp.perm.owner)); 7669 if (isSystemApp(p.owner)) { 7670 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7671 // It's a built-in permission and no owner, take ownership now 7672 bp.packageSetting = pkgSetting; 7673 bp.perm = p; 7674 bp.uid = pkg.applicationInfo.uid; 7675 bp.sourcePackage = p.info.packageName; 7676 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7677 } else if (!currentOwnerIsSystem) { 7678 String msg = "New decl " + p.owner + " of permission " 7679 + p.info.name + " is system; overriding " + bp.sourcePackage; 7680 reportSettingsProblem(Log.WARN, msg); 7681 bp = null; 7682 } 7683 } 7684 } 7685 7686 if (bp == null) { 7687 bp = new BasePermission(p.info.name, p.info.packageName, 7688 BasePermission.TYPE_NORMAL); 7689 permissionMap.put(p.info.name, bp); 7690 } 7691 7692 if (bp.perm == null) { 7693 if (bp.sourcePackage == null 7694 || bp.sourcePackage.equals(p.info.packageName)) { 7695 BasePermission tree = findPermissionTreeLP(p.info.name); 7696 if (tree == null 7697 || tree.sourcePackage.equals(p.info.packageName)) { 7698 bp.packageSetting = pkgSetting; 7699 bp.perm = p; 7700 bp.uid = pkg.applicationInfo.uid; 7701 bp.sourcePackage = p.info.packageName; 7702 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7703 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7704 if (r == null) { 7705 r = new StringBuilder(256); 7706 } else { 7707 r.append(' '); 7708 } 7709 r.append(p.info.name); 7710 } 7711 } else { 7712 Slog.w(TAG, "Permission " + p.info.name + " from package " 7713 + p.info.packageName + " ignored: base tree " 7714 + tree.name + " is from package " 7715 + tree.sourcePackage); 7716 } 7717 } else { 7718 Slog.w(TAG, "Permission " + p.info.name + " from package " 7719 + p.info.packageName + " ignored: original from " 7720 + bp.sourcePackage); 7721 } 7722 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7723 if (r == null) { 7724 r = new StringBuilder(256); 7725 } else { 7726 r.append(' '); 7727 } 7728 r.append("DUP:"); 7729 r.append(p.info.name); 7730 } 7731 if (bp.perm == p) { 7732 bp.protectionLevel = p.info.protectionLevel; 7733 } 7734 } 7735 7736 if (r != null) { 7737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7738 } 7739 7740 N = pkg.instrumentation.size(); 7741 r = null; 7742 for (i=0; i<N; i++) { 7743 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7744 a.info.packageName = pkg.applicationInfo.packageName; 7745 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7746 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7747 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7748 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7749 a.info.dataDir = pkg.applicationInfo.dataDir; 7750 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7751 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7752 7753 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7754 // need other information about the application, like the ABI and what not ? 7755 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7756 mInstrumentation.put(a.getComponentName(), a); 7757 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7758 if (r == null) { 7759 r = new StringBuilder(256); 7760 } else { 7761 r.append(' '); 7762 } 7763 r.append(a.info.name); 7764 } 7765 } 7766 if (r != null) { 7767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7768 } 7769 7770 if (pkg.protectedBroadcasts != null) { 7771 N = pkg.protectedBroadcasts.size(); 7772 for (i=0; i<N; i++) { 7773 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7774 } 7775 } 7776 7777 pkgSetting.setTimeStamp(scanFileTime); 7778 7779 // Create idmap files for pairs of (packages, overlay packages). 7780 // Note: "android", ie framework-res.apk, is handled by native layers. 7781 if (pkg.mOverlayTarget != null) { 7782 // This is an overlay package. 7783 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7784 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7785 mOverlays.put(pkg.mOverlayTarget, 7786 new ArrayMap<String, PackageParser.Package>()); 7787 } 7788 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7789 map.put(pkg.packageName, pkg); 7790 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7791 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7792 createIdmapFailed = true; 7793 } 7794 } 7795 } else if (mOverlays.containsKey(pkg.packageName) && 7796 !pkg.packageName.equals("android")) { 7797 // This is a regular package, with one or more known overlay packages. 7798 createIdmapsForPackageLI(pkg); 7799 } 7800 } 7801 7802 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7803 7804 if (createIdmapFailed) { 7805 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7806 "scanPackageLI failed to createIdmap"); 7807 } 7808 return pkg; 7809 } 7810 7811 /** 7812 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7813 * is derived purely on the basis of the contents of {@code scanFile} and 7814 * {@code cpuAbiOverride}. 7815 * 7816 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7817 */ 7818 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7819 String cpuAbiOverride, boolean extractLibs) 7820 throws PackageManagerException { 7821 // TODO: We can probably be smarter about this stuff. For installed apps, 7822 // we can calculate this information at install time once and for all. For 7823 // system apps, we can probably assume that this information doesn't change 7824 // after the first boot scan. As things stand, we do lots of unnecessary work. 7825 7826 // Give ourselves some initial paths; we'll come back for another 7827 // pass once we've determined ABI below. 7828 setNativeLibraryPaths(pkg); 7829 7830 // We would never need to extract libs for forward-locked and external packages, 7831 // since the container service will do it for us. We shouldn't attempt to 7832 // extract libs from system app when it was not updated. 7833 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7834 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7835 extractLibs = false; 7836 } 7837 7838 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7839 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7840 7841 NativeLibraryHelper.Handle handle = null; 7842 try { 7843 handle = NativeLibraryHelper.Handle.create(pkg); 7844 // TODO(multiArch): This can be null for apps that didn't go through the 7845 // usual installation process. We can calculate it again, like we 7846 // do during install time. 7847 // 7848 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7849 // unnecessary. 7850 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7851 7852 // Null out the abis so that they can be recalculated. 7853 pkg.applicationInfo.primaryCpuAbi = null; 7854 pkg.applicationInfo.secondaryCpuAbi = null; 7855 if (isMultiArch(pkg.applicationInfo)) { 7856 // Warn if we've set an abiOverride for multi-lib packages.. 7857 // By definition, we need to copy both 32 and 64 bit libraries for 7858 // such packages. 7859 if (pkg.cpuAbiOverride != null 7860 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7861 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7862 } 7863 7864 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7865 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7866 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7867 if (extractLibs) { 7868 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7869 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7870 useIsaSpecificSubdirs); 7871 } else { 7872 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7873 } 7874 } 7875 7876 maybeThrowExceptionForMultiArchCopy( 7877 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7878 7879 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7880 if (extractLibs) { 7881 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7882 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7883 useIsaSpecificSubdirs); 7884 } else { 7885 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7886 } 7887 } 7888 7889 maybeThrowExceptionForMultiArchCopy( 7890 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7891 7892 if (abi64 >= 0) { 7893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7894 } 7895 7896 if (abi32 >= 0) { 7897 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7898 if (abi64 >= 0) { 7899 pkg.applicationInfo.secondaryCpuAbi = abi; 7900 } else { 7901 pkg.applicationInfo.primaryCpuAbi = abi; 7902 } 7903 } 7904 } else { 7905 String[] abiList = (cpuAbiOverride != null) ? 7906 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7907 7908 // Enable gross and lame hacks for apps that are built with old 7909 // SDK tools. We must scan their APKs for renderscript bitcode and 7910 // not launch them if it's present. Don't bother checking on devices 7911 // that don't have 64 bit support. 7912 boolean needsRenderScriptOverride = false; 7913 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7914 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7915 abiList = Build.SUPPORTED_32_BIT_ABIS; 7916 needsRenderScriptOverride = true; 7917 } 7918 7919 final int copyRet; 7920 if (extractLibs) { 7921 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7922 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7923 } else { 7924 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7925 } 7926 7927 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7928 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7929 "Error unpackaging native libs for app, errorCode=" + copyRet); 7930 } 7931 7932 if (copyRet >= 0) { 7933 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7934 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7935 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7936 } else if (needsRenderScriptOverride) { 7937 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7938 } 7939 } 7940 } catch (IOException ioe) { 7941 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7942 } finally { 7943 IoUtils.closeQuietly(handle); 7944 } 7945 7946 // Now that we've calculated the ABIs and determined if it's an internal app, 7947 // we will go ahead and populate the nativeLibraryPath. 7948 setNativeLibraryPaths(pkg); 7949 } 7950 7951 /** 7952 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7953 * i.e, so that all packages can be run inside a single process if required. 7954 * 7955 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7956 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7957 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7958 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7959 * updating a package that belongs to a shared user. 7960 * 7961 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7962 * adds unnecessary complexity. 7963 */ 7964 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7965 PackageParser.Package scannedPackage, boolean bootComplete) { 7966 String requiredInstructionSet = null; 7967 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7968 requiredInstructionSet = VMRuntime.getInstructionSet( 7969 scannedPackage.applicationInfo.primaryCpuAbi); 7970 } 7971 7972 PackageSetting requirer = null; 7973 for (PackageSetting ps : packagesForUser) { 7974 // If packagesForUser contains scannedPackage, we skip it. This will happen 7975 // when scannedPackage is an update of an existing package. Without this check, 7976 // we will never be able to change the ABI of any package belonging to a shared 7977 // user, even if it's compatible with other packages. 7978 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7979 if (ps.primaryCpuAbiString == null) { 7980 continue; 7981 } 7982 7983 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7984 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7985 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7986 // this but there's not much we can do. 7987 String errorMessage = "Instruction set mismatch, " 7988 + ((requirer == null) ? "[caller]" : requirer) 7989 + " requires " + requiredInstructionSet + " whereas " + ps 7990 + " requires " + instructionSet; 7991 Slog.w(TAG, errorMessage); 7992 } 7993 7994 if (requiredInstructionSet == null) { 7995 requiredInstructionSet = instructionSet; 7996 requirer = ps; 7997 } 7998 } 7999 } 8000 8001 if (requiredInstructionSet != null) { 8002 String adjustedAbi; 8003 if (requirer != null) { 8004 // requirer != null implies that either scannedPackage was null or that scannedPackage 8005 // did not require an ABI, in which case we have to adjust scannedPackage to match 8006 // the ABI of the set (which is the same as requirer's ABI) 8007 adjustedAbi = requirer.primaryCpuAbiString; 8008 if (scannedPackage != null) { 8009 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8010 } 8011 } else { 8012 // requirer == null implies that we're updating all ABIs in the set to 8013 // match scannedPackage. 8014 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8015 } 8016 8017 for (PackageSetting ps : packagesForUser) { 8018 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8019 if (ps.primaryCpuAbiString != null) { 8020 continue; 8021 } 8022 8023 ps.primaryCpuAbiString = adjustedAbi; 8024 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8025 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8026 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8027 mInstaller.rmdex(ps.codePathString, 8028 getDexCodeInstructionSet(getPreferredInstructionSet())); 8029 } 8030 } 8031 } 8032 } 8033 } 8034 8035 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8036 synchronized (mPackages) { 8037 mResolverReplaced = true; 8038 // Set up information for custom user intent resolution activity. 8039 mResolveActivity.applicationInfo = pkg.applicationInfo; 8040 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8041 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8042 mResolveActivity.processName = pkg.applicationInfo.packageName; 8043 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8044 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8045 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8046 mResolveActivity.theme = 0; 8047 mResolveActivity.exported = true; 8048 mResolveActivity.enabled = true; 8049 mResolveInfo.activityInfo = mResolveActivity; 8050 mResolveInfo.priority = 0; 8051 mResolveInfo.preferredOrder = 0; 8052 mResolveInfo.match = 0; 8053 mResolveComponentName = mCustomResolverComponentName; 8054 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8055 mResolveComponentName); 8056 } 8057 } 8058 8059 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8060 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8061 8062 // Set up information for ephemeral installer activity 8063 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8064 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8065 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8066 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8067 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8068 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8069 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8070 mEphemeralInstallerActivity.theme = 0; 8071 mEphemeralInstallerActivity.exported = true; 8072 mEphemeralInstallerActivity.enabled = true; 8073 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8074 mEphemeralInstallerInfo.priority = 0; 8075 mEphemeralInstallerInfo.preferredOrder = 0; 8076 mEphemeralInstallerInfo.match = 0; 8077 8078 if (DEBUG_EPHEMERAL) { 8079 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8080 } 8081 } 8082 8083 private static String calculateBundledApkRoot(final String codePathString) { 8084 final File codePath = new File(codePathString); 8085 final File codeRoot; 8086 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8087 codeRoot = Environment.getRootDirectory(); 8088 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8089 codeRoot = Environment.getOemDirectory(); 8090 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8091 codeRoot = Environment.getVendorDirectory(); 8092 } else { 8093 // Unrecognized code path; take its top real segment as the apk root: 8094 // e.g. /something/app/blah.apk => /something 8095 try { 8096 File f = codePath.getCanonicalFile(); 8097 File parent = f.getParentFile(); // non-null because codePath is a file 8098 File tmp; 8099 while ((tmp = parent.getParentFile()) != null) { 8100 f = parent; 8101 parent = tmp; 8102 } 8103 codeRoot = f; 8104 Slog.w(TAG, "Unrecognized code path " 8105 + codePath + " - using " + codeRoot); 8106 } catch (IOException e) { 8107 // Can't canonicalize the code path -- shenanigans? 8108 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8109 return Environment.getRootDirectory().getPath(); 8110 } 8111 } 8112 return codeRoot.getPath(); 8113 } 8114 8115 /** 8116 * Derive and set the location of native libraries for the given package, 8117 * which varies depending on where and how the package was installed. 8118 */ 8119 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8120 final ApplicationInfo info = pkg.applicationInfo; 8121 final String codePath = pkg.codePath; 8122 final File codeFile = new File(codePath); 8123 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8124 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8125 8126 info.nativeLibraryRootDir = null; 8127 info.nativeLibraryRootRequiresIsa = false; 8128 info.nativeLibraryDir = null; 8129 info.secondaryNativeLibraryDir = null; 8130 8131 if (isApkFile(codeFile)) { 8132 // Monolithic install 8133 if (bundledApp) { 8134 // If "/system/lib64/apkname" exists, assume that is the per-package 8135 // native library directory to use; otherwise use "/system/lib/apkname". 8136 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8137 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8138 getPrimaryInstructionSet(info)); 8139 8140 // This is a bundled system app so choose the path based on the ABI. 8141 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8142 // is just the default path. 8143 final String apkName = deriveCodePathName(codePath); 8144 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8145 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8146 apkName).getAbsolutePath(); 8147 8148 if (info.secondaryCpuAbi != null) { 8149 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8150 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8151 secondaryLibDir, apkName).getAbsolutePath(); 8152 } 8153 } else if (asecApp) { 8154 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8155 .getAbsolutePath(); 8156 } else { 8157 final String apkName = deriveCodePathName(codePath); 8158 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8159 .getAbsolutePath(); 8160 } 8161 8162 info.nativeLibraryRootRequiresIsa = false; 8163 info.nativeLibraryDir = info.nativeLibraryRootDir; 8164 } else { 8165 // Cluster install 8166 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8167 info.nativeLibraryRootRequiresIsa = true; 8168 8169 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8170 getPrimaryInstructionSet(info)).getAbsolutePath(); 8171 8172 if (info.secondaryCpuAbi != null) { 8173 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8174 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8175 } 8176 } 8177 } 8178 8179 /** 8180 * Calculate the abis and roots for a bundled app. These can uniquely 8181 * be determined from the contents of the system partition, i.e whether 8182 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8183 * of this information, and instead assume that the system was built 8184 * sensibly. 8185 */ 8186 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8187 PackageSetting pkgSetting) { 8188 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8189 8190 // If "/system/lib64/apkname" exists, assume that is the per-package 8191 // native library directory to use; otherwise use "/system/lib/apkname". 8192 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8193 setBundledAppAbi(pkg, apkRoot, apkName); 8194 // pkgSetting might be null during rescan following uninstall of updates 8195 // to a bundled app, so accommodate that possibility. The settings in 8196 // that case will be established later from the parsed package. 8197 // 8198 // If the settings aren't null, sync them up with what we've just derived. 8199 // note that apkRoot isn't stored in the package settings. 8200 if (pkgSetting != null) { 8201 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8202 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8203 } 8204 } 8205 8206 /** 8207 * Deduces the ABI of a bundled app and sets the relevant fields on the 8208 * parsed pkg object. 8209 * 8210 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8211 * under which system libraries are installed. 8212 * @param apkName the name of the installed package. 8213 */ 8214 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8215 final File codeFile = new File(pkg.codePath); 8216 8217 final boolean has64BitLibs; 8218 final boolean has32BitLibs; 8219 if (isApkFile(codeFile)) { 8220 // Monolithic install 8221 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8222 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8223 } else { 8224 // Cluster install 8225 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8226 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8227 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8228 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8229 has64BitLibs = (new File(rootDir, isa)).exists(); 8230 } else { 8231 has64BitLibs = false; 8232 } 8233 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8234 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8235 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8236 has32BitLibs = (new File(rootDir, isa)).exists(); 8237 } else { 8238 has32BitLibs = false; 8239 } 8240 } 8241 8242 if (has64BitLibs && !has32BitLibs) { 8243 // The package has 64 bit libs, but not 32 bit libs. Its primary 8244 // ABI should be 64 bit. We can safely assume here that the bundled 8245 // native libraries correspond to the most preferred ABI in the list. 8246 8247 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8248 pkg.applicationInfo.secondaryCpuAbi = null; 8249 } else if (has32BitLibs && !has64BitLibs) { 8250 // The package has 32 bit libs but not 64 bit libs. Its primary 8251 // ABI should be 32 bit. 8252 8253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8254 pkg.applicationInfo.secondaryCpuAbi = null; 8255 } else if (has32BitLibs && has64BitLibs) { 8256 // The application has both 64 and 32 bit bundled libraries. We check 8257 // here that the app declares multiArch support, and warn if it doesn't. 8258 // 8259 // We will be lenient here and record both ABIs. The primary will be the 8260 // ABI that's higher on the list, i.e, a device that's configured to prefer 8261 // 64 bit apps will see a 64 bit primary ABI, 8262 8263 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8264 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8265 } 8266 8267 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8268 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8269 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8270 } else { 8271 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8272 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8273 } 8274 } else { 8275 pkg.applicationInfo.primaryCpuAbi = null; 8276 pkg.applicationInfo.secondaryCpuAbi = null; 8277 } 8278 } 8279 8280 private void killApplication(String pkgName, int appId, String reason) { 8281 // Request the ActivityManager to kill the process(only for existing packages) 8282 // so that we do not end up in a confused state while the user is still using the older 8283 // version of the application while the new one gets installed. 8284 IActivityManager am = ActivityManagerNative.getDefault(); 8285 if (am != null) { 8286 try { 8287 am.killApplicationWithAppId(pkgName, appId, reason); 8288 } catch (RemoteException e) { 8289 } 8290 } 8291 } 8292 8293 void removePackageLI(PackageSetting ps, boolean chatty) { 8294 if (DEBUG_INSTALL) { 8295 if (chatty) 8296 Log.d(TAG, "Removing package " + ps.name); 8297 } 8298 8299 // writer 8300 synchronized (mPackages) { 8301 mPackages.remove(ps.name); 8302 final PackageParser.Package pkg = ps.pkg; 8303 if (pkg != null) { 8304 cleanPackageDataStructuresLILPw(pkg, chatty); 8305 } 8306 } 8307 } 8308 8309 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8310 if (DEBUG_INSTALL) { 8311 if (chatty) 8312 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8313 } 8314 8315 // writer 8316 synchronized (mPackages) { 8317 mPackages.remove(pkg.applicationInfo.packageName); 8318 cleanPackageDataStructuresLILPw(pkg, chatty); 8319 } 8320 } 8321 8322 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8323 int N = pkg.providers.size(); 8324 StringBuilder r = null; 8325 int i; 8326 for (i=0; i<N; i++) { 8327 PackageParser.Provider p = pkg.providers.get(i); 8328 mProviders.removeProvider(p); 8329 if (p.info.authority == null) { 8330 8331 /* There was another ContentProvider with this authority when 8332 * this app was installed so this authority is null, 8333 * Ignore it as we don't have to unregister the provider. 8334 */ 8335 continue; 8336 } 8337 String names[] = p.info.authority.split(";"); 8338 for (int j = 0; j < names.length; j++) { 8339 if (mProvidersByAuthority.get(names[j]) == p) { 8340 mProvidersByAuthority.remove(names[j]); 8341 if (DEBUG_REMOVE) { 8342 if (chatty) 8343 Log.d(TAG, "Unregistered content provider: " + names[j] 8344 + ", className = " + p.info.name + ", isSyncable = " 8345 + p.info.isSyncable); 8346 } 8347 } 8348 } 8349 if (DEBUG_REMOVE && chatty) { 8350 if (r == null) { 8351 r = new StringBuilder(256); 8352 } else { 8353 r.append(' '); 8354 } 8355 r.append(p.info.name); 8356 } 8357 } 8358 if (r != null) { 8359 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8360 } 8361 8362 N = pkg.services.size(); 8363 r = null; 8364 for (i=0; i<N; i++) { 8365 PackageParser.Service s = pkg.services.get(i); 8366 mServices.removeService(s); 8367 if (chatty) { 8368 if (r == null) { 8369 r = new StringBuilder(256); 8370 } else { 8371 r.append(' '); 8372 } 8373 r.append(s.info.name); 8374 } 8375 } 8376 if (r != null) { 8377 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8378 } 8379 8380 N = pkg.receivers.size(); 8381 r = null; 8382 for (i=0; i<N; i++) { 8383 PackageParser.Activity a = pkg.receivers.get(i); 8384 mReceivers.removeActivity(a, "receiver"); 8385 if (DEBUG_REMOVE && chatty) { 8386 if (r == null) { 8387 r = new StringBuilder(256); 8388 } else { 8389 r.append(' '); 8390 } 8391 r.append(a.info.name); 8392 } 8393 } 8394 if (r != null) { 8395 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8396 } 8397 8398 N = pkg.activities.size(); 8399 r = null; 8400 for (i=0; i<N; i++) { 8401 PackageParser.Activity a = pkg.activities.get(i); 8402 mActivities.removeActivity(a, "activity"); 8403 if (DEBUG_REMOVE && chatty) { 8404 if (r == null) { 8405 r = new StringBuilder(256); 8406 } else { 8407 r.append(' '); 8408 } 8409 r.append(a.info.name); 8410 } 8411 } 8412 if (r != null) { 8413 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8414 } 8415 8416 N = pkg.permissions.size(); 8417 r = null; 8418 for (i=0; i<N; i++) { 8419 PackageParser.Permission p = pkg.permissions.get(i); 8420 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8421 if (bp == null) { 8422 bp = mSettings.mPermissionTrees.get(p.info.name); 8423 } 8424 if (bp != null && bp.perm == p) { 8425 bp.perm = null; 8426 if (DEBUG_REMOVE && chatty) { 8427 if (r == null) { 8428 r = new StringBuilder(256); 8429 } else { 8430 r.append(' '); 8431 } 8432 r.append(p.info.name); 8433 } 8434 } 8435 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8436 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8437 if (appOpPkgs != null) { 8438 appOpPkgs.remove(pkg.packageName); 8439 } 8440 } 8441 } 8442 if (r != null) { 8443 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8444 } 8445 8446 N = pkg.requestedPermissions.size(); 8447 r = null; 8448 for (i=0; i<N; i++) { 8449 String perm = pkg.requestedPermissions.get(i); 8450 BasePermission bp = mSettings.mPermissions.get(perm); 8451 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8452 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8453 if (appOpPkgs != null) { 8454 appOpPkgs.remove(pkg.packageName); 8455 if (appOpPkgs.isEmpty()) { 8456 mAppOpPermissionPackages.remove(perm); 8457 } 8458 } 8459 } 8460 } 8461 if (r != null) { 8462 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8463 } 8464 8465 N = pkg.instrumentation.size(); 8466 r = null; 8467 for (i=0; i<N; i++) { 8468 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8469 mInstrumentation.remove(a.getComponentName()); 8470 if (DEBUG_REMOVE && chatty) { 8471 if (r == null) { 8472 r = new StringBuilder(256); 8473 } else { 8474 r.append(' '); 8475 } 8476 r.append(a.info.name); 8477 } 8478 } 8479 if (r != null) { 8480 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8481 } 8482 8483 r = null; 8484 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8485 // Only system apps can hold shared libraries. 8486 if (pkg.libraryNames != null) { 8487 for (i=0; i<pkg.libraryNames.size(); i++) { 8488 String name = pkg.libraryNames.get(i); 8489 SharedLibraryEntry cur = mSharedLibraries.get(name); 8490 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8491 mSharedLibraries.remove(name); 8492 if (DEBUG_REMOVE && chatty) { 8493 if (r == null) { 8494 r = new StringBuilder(256); 8495 } else { 8496 r.append(' '); 8497 } 8498 r.append(name); 8499 } 8500 } 8501 } 8502 } 8503 } 8504 if (r != null) { 8505 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8506 } 8507 } 8508 8509 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8510 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8511 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8512 return true; 8513 } 8514 } 8515 return false; 8516 } 8517 8518 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8519 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8520 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8521 8522 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8523 int flags) { 8524 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8525 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8526 } 8527 8528 private void updatePermissionsLPw(String changingPkg, 8529 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8530 // Make sure there are no dangling permission trees. 8531 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8532 while (it.hasNext()) { 8533 final BasePermission bp = it.next(); 8534 if (bp.packageSetting == null) { 8535 // We may not yet have parsed the package, so just see if 8536 // we still know about its settings. 8537 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8538 } 8539 if (bp.packageSetting == null) { 8540 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8541 + " from package " + bp.sourcePackage); 8542 it.remove(); 8543 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8544 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8545 Slog.i(TAG, "Removing old permission tree: " + bp.name 8546 + " from package " + bp.sourcePackage); 8547 flags |= UPDATE_PERMISSIONS_ALL; 8548 it.remove(); 8549 } 8550 } 8551 } 8552 8553 // Make sure all dynamic permissions have been assigned to a package, 8554 // and make sure there are no dangling permissions. 8555 it = mSettings.mPermissions.values().iterator(); 8556 while (it.hasNext()) { 8557 final BasePermission bp = it.next(); 8558 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8559 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8560 + bp.name + " pkg=" + bp.sourcePackage 8561 + " info=" + bp.pendingInfo); 8562 if (bp.packageSetting == null && bp.pendingInfo != null) { 8563 final BasePermission tree = findPermissionTreeLP(bp.name); 8564 if (tree != null && tree.perm != null) { 8565 bp.packageSetting = tree.packageSetting; 8566 bp.perm = new PackageParser.Permission(tree.perm.owner, 8567 new PermissionInfo(bp.pendingInfo)); 8568 bp.perm.info.packageName = tree.perm.info.packageName; 8569 bp.perm.info.name = bp.name; 8570 bp.uid = tree.uid; 8571 } 8572 } 8573 } 8574 if (bp.packageSetting == null) { 8575 // We may not yet have parsed the package, so just see if 8576 // we still know about its settings. 8577 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8578 } 8579 if (bp.packageSetting == null) { 8580 Slog.w(TAG, "Removing dangling permission: " + bp.name 8581 + " from package " + bp.sourcePackage); 8582 it.remove(); 8583 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8584 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8585 Slog.i(TAG, "Removing old permission: " + bp.name 8586 + " from package " + bp.sourcePackage); 8587 flags |= UPDATE_PERMISSIONS_ALL; 8588 it.remove(); 8589 } 8590 } 8591 } 8592 8593 // Now update the permissions for all packages, in particular 8594 // replace the granted permissions of the system packages. 8595 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8596 for (PackageParser.Package pkg : mPackages.values()) { 8597 if (pkg != pkgInfo) { 8598 // Only replace for packages on requested volume 8599 final String volumeUuid = getVolumeUuidForPackage(pkg); 8600 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8601 && Objects.equals(replaceVolumeUuid, volumeUuid); 8602 grantPermissionsLPw(pkg, replace, changingPkg); 8603 } 8604 } 8605 } 8606 8607 if (pkgInfo != null) { 8608 // Only replace for packages on requested volume 8609 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8610 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8611 && Objects.equals(replaceVolumeUuid, volumeUuid); 8612 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8613 } 8614 } 8615 8616 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8617 String packageOfInterest) { 8618 // IMPORTANT: There are two types of permissions: install and runtime. 8619 // Install time permissions are granted when the app is installed to 8620 // all device users and users added in the future. Runtime permissions 8621 // are granted at runtime explicitly to specific users. Normal and signature 8622 // protected permissions are install time permissions. Dangerous permissions 8623 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8624 // otherwise they are runtime permissions. This function does not manage 8625 // runtime permissions except for the case an app targeting Lollipop MR1 8626 // being upgraded to target a newer SDK, in which case dangerous permissions 8627 // are transformed from install time to runtime ones. 8628 8629 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8630 if (ps == null) { 8631 return; 8632 } 8633 8634 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8635 8636 PermissionsState permissionsState = ps.getPermissionsState(); 8637 PermissionsState origPermissions = permissionsState; 8638 8639 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8640 8641 boolean runtimePermissionsRevoked = false; 8642 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8643 8644 boolean changedInstallPermission = false; 8645 8646 if (replace) { 8647 ps.installPermissionsFixed = false; 8648 if (!ps.isSharedUser()) { 8649 origPermissions = new PermissionsState(permissionsState); 8650 permissionsState.reset(); 8651 } else { 8652 // We need to know only about runtime permission changes since the 8653 // calling code always writes the install permissions state but 8654 // the runtime ones are written only if changed. The only cases of 8655 // changed runtime permissions here are promotion of an install to 8656 // runtime and revocation of a runtime from a shared user. 8657 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8658 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8659 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8660 runtimePermissionsRevoked = true; 8661 } 8662 } 8663 } 8664 8665 permissionsState.setGlobalGids(mGlobalGids); 8666 8667 final int N = pkg.requestedPermissions.size(); 8668 for (int i=0; i<N; i++) { 8669 final String name = pkg.requestedPermissions.get(i); 8670 final BasePermission bp = mSettings.mPermissions.get(name); 8671 8672 if (DEBUG_INSTALL) { 8673 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8674 } 8675 8676 if (bp == null || bp.packageSetting == null) { 8677 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8678 Slog.w(TAG, "Unknown permission " + name 8679 + " in package " + pkg.packageName); 8680 } 8681 continue; 8682 } 8683 8684 final String perm = bp.name; 8685 boolean allowedSig = false; 8686 int grant = GRANT_DENIED; 8687 8688 // Keep track of app op permissions. 8689 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8690 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8691 if (pkgs == null) { 8692 pkgs = new ArraySet<>(); 8693 mAppOpPermissionPackages.put(bp.name, pkgs); 8694 } 8695 pkgs.add(pkg.packageName); 8696 } 8697 8698 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8699 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8700 >= Build.VERSION_CODES.M; 8701 switch (level) { 8702 case PermissionInfo.PROTECTION_NORMAL: { 8703 // For all apps normal permissions are install time ones. 8704 grant = GRANT_INSTALL; 8705 } break; 8706 8707 case PermissionInfo.PROTECTION_DANGEROUS: { 8708 // If a permission review is required for legacy apps we represent 8709 // their permissions as always granted runtime ones since we need 8710 // to keep the review required permission flag per user while an 8711 // install permission's state is shared across all users. 8712 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8713 // For legacy apps dangerous permissions are install time ones. 8714 grant = GRANT_INSTALL; 8715 } else if (origPermissions.hasInstallPermission(bp.name)) { 8716 // For legacy apps that became modern, install becomes runtime. 8717 grant = GRANT_UPGRADE; 8718 } else if (mPromoteSystemApps 8719 && isSystemApp(ps) 8720 && mExistingSystemPackages.contains(ps.name)) { 8721 // For legacy system apps, install becomes runtime. 8722 // We cannot check hasInstallPermission() for system apps since those 8723 // permissions were granted implicitly and not persisted pre-M. 8724 grant = GRANT_UPGRADE; 8725 } else { 8726 // For modern apps keep runtime permissions unchanged. 8727 grant = GRANT_RUNTIME; 8728 } 8729 } break; 8730 8731 case PermissionInfo.PROTECTION_SIGNATURE: { 8732 // For all apps signature permissions are install time ones. 8733 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8734 if (allowedSig) { 8735 grant = GRANT_INSTALL; 8736 } 8737 } break; 8738 } 8739 8740 if (DEBUG_INSTALL) { 8741 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8742 } 8743 8744 if (grant != GRANT_DENIED) { 8745 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8746 // If this is an existing, non-system package, then 8747 // we can't add any new permissions to it. 8748 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8749 // Except... if this is a permission that was added 8750 // to the platform (note: need to only do this when 8751 // updating the platform). 8752 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8753 grant = GRANT_DENIED; 8754 } 8755 } 8756 } 8757 8758 switch (grant) { 8759 case GRANT_INSTALL: { 8760 // Revoke this as runtime permission to handle the case of 8761 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8762 for (int userId : UserManagerService.getInstance().getUserIds()) { 8763 if (origPermissions.getRuntimePermissionState( 8764 bp.name, userId) != null) { 8765 // Revoke the runtime permission and clear the flags. 8766 origPermissions.revokeRuntimePermission(bp, userId); 8767 origPermissions.updatePermissionFlags(bp, userId, 8768 PackageManager.MASK_PERMISSION_FLAGS, 0); 8769 // If we revoked a permission permission, we have to write. 8770 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8771 changedRuntimePermissionUserIds, userId); 8772 } 8773 } 8774 // Grant an install permission. 8775 if (permissionsState.grantInstallPermission(bp) != 8776 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8777 changedInstallPermission = true; 8778 } 8779 } break; 8780 8781 case GRANT_RUNTIME: { 8782 // Grant previously granted runtime permissions. 8783 for (int userId : UserManagerService.getInstance().getUserIds()) { 8784 PermissionState permissionState = origPermissions 8785 .getRuntimePermissionState(bp.name, userId); 8786 int flags = permissionState != null 8787 ? permissionState.getFlags() : 0; 8788 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8789 if (permissionsState.grantRuntimePermission(bp, userId) == 8790 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8791 // If we cannot put the permission as it was, we have to write. 8792 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8793 changedRuntimePermissionUserIds, userId); 8794 } 8795 // If the app supports runtime permissions no need for a review. 8796 if (Build.PERMISSIONS_REVIEW_REQUIRED 8797 && appSupportsRuntimePermissions 8798 && (flags & PackageManager 8799 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8800 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8801 // Since we changed the flags, we have to write. 8802 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8803 changedRuntimePermissionUserIds, userId); 8804 } 8805 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8806 && !appSupportsRuntimePermissions) { 8807 // For legacy apps that need a permission review, every new 8808 // runtime permission is granted but it is pending a review. 8809 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8810 permissionsState.grantRuntimePermission(bp, userId); 8811 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8812 // We changed the permission and flags, hence have to write. 8813 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8814 changedRuntimePermissionUserIds, userId); 8815 } 8816 } 8817 // Propagate the permission flags. 8818 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8819 } 8820 } break; 8821 8822 case GRANT_UPGRADE: { 8823 // Grant runtime permissions for a previously held install permission. 8824 PermissionState permissionState = origPermissions 8825 .getInstallPermissionState(bp.name); 8826 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8827 8828 if (origPermissions.revokeInstallPermission(bp) 8829 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8830 // We will be transferring the permission flags, so clear them. 8831 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8832 PackageManager.MASK_PERMISSION_FLAGS, 0); 8833 changedInstallPermission = true; 8834 } 8835 8836 // If the permission is not to be promoted to runtime we ignore it and 8837 // also its other flags as they are not applicable to install permissions. 8838 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8839 for (int userId : currentUserIds) { 8840 if (permissionsState.grantRuntimePermission(bp, userId) != 8841 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8842 // Transfer the permission flags. 8843 permissionsState.updatePermissionFlags(bp, userId, 8844 flags, flags); 8845 // If we granted the permission, we have to write. 8846 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8847 changedRuntimePermissionUserIds, userId); 8848 } 8849 } 8850 } 8851 } break; 8852 8853 default: { 8854 if (packageOfInterest == null 8855 || packageOfInterest.equals(pkg.packageName)) { 8856 Slog.w(TAG, "Not granting permission " + perm 8857 + " to package " + pkg.packageName 8858 + " because it was previously installed without"); 8859 } 8860 } break; 8861 } 8862 } else { 8863 if (permissionsState.revokeInstallPermission(bp) != 8864 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8865 // Also drop the permission flags. 8866 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8867 PackageManager.MASK_PERMISSION_FLAGS, 0); 8868 changedInstallPermission = true; 8869 Slog.i(TAG, "Un-granting permission " + perm 8870 + " from package " + pkg.packageName 8871 + " (protectionLevel=" + bp.protectionLevel 8872 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8873 + ")"); 8874 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8875 // Don't print warning for app op permissions, since it is fine for them 8876 // not to be granted, there is a UI for the user to decide. 8877 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8878 Slog.w(TAG, "Not granting permission " + perm 8879 + " to package " + pkg.packageName 8880 + " (protectionLevel=" + bp.protectionLevel 8881 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8882 + ")"); 8883 } 8884 } 8885 } 8886 } 8887 8888 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8889 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8890 // This is the first that we have heard about this package, so the 8891 // permissions we have now selected are fixed until explicitly 8892 // changed. 8893 ps.installPermissionsFixed = true; 8894 } 8895 8896 // Persist the runtime permissions state for users with changes. If permissions 8897 // were revoked because no app in the shared user declares them we have to 8898 // write synchronously to avoid losing runtime permissions state. 8899 for (int userId : changedRuntimePermissionUserIds) { 8900 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8901 } 8902 8903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8904 } 8905 8906 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8907 boolean allowed = false; 8908 final int NP = PackageParser.NEW_PERMISSIONS.length; 8909 for (int ip=0; ip<NP; ip++) { 8910 final PackageParser.NewPermissionInfo npi 8911 = PackageParser.NEW_PERMISSIONS[ip]; 8912 if (npi.name.equals(perm) 8913 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8914 allowed = true; 8915 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8916 + pkg.packageName); 8917 break; 8918 } 8919 } 8920 return allowed; 8921 } 8922 8923 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8924 BasePermission bp, PermissionsState origPermissions) { 8925 boolean allowed; 8926 allowed = (compareSignatures( 8927 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8928 == PackageManager.SIGNATURE_MATCH) 8929 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8930 == PackageManager.SIGNATURE_MATCH); 8931 if (!allowed && (bp.protectionLevel 8932 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8933 if (isSystemApp(pkg)) { 8934 // For updated system applications, a system permission 8935 // is granted only if it had been defined by the original application. 8936 if (pkg.isUpdatedSystemApp()) { 8937 final PackageSetting sysPs = mSettings 8938 .getDisabledSystemPkgLPr(pkg.packageName); 8939 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8940 // If the original was granted this permission, we take 8941 // that grant decision as read and propagate it to the 8942 // update. 8943 if (sysPs.isPrivileged()) { 8944 allowed = true; 8945 } 8946 } else { 8947 // The system apk may have been updated with an older 8948 // version of the one on the data partition, but which 8949 // granted a new system permission that it didn't have 8950 // before. In this case we do want to allow the app to 8951 // now get the new permission if the ancestral apk is 8952 // privileged to get it. 8953 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8954 for (int j=0; 8955 j<sysPs.pkg.requestedPermissions.size(); j++) { 8956 if (perm.equals( 8957 sysPs.pkg.requestedPermissions.get(j))) { 8958 allowed = true; 8959 break; 8960 } 8961 } 8962 } 8963 } 8964 } else { 8965 allowed = isPrivilegedApp(pkg); 8966 } 8967 } 8968 } 8969 if (!allowed) { 8970 if (!allowed && (bp.protectionLevel 8971 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8972 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8973 // If this was a previously normal/dangerous permission that got moved 8974 // to a system permission as part of the runtime permission redesign, then 8975 // we still want to blindly grant it to old apps. 8976 allowed = true; 8977 } 8978 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8979 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8980 // If this permission is to be granted to the system installer and 8981 // this app is an installer, then it gets the permission. 8982 allowed = true; 8983 } 8984 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8985 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8986 // If this permission is to be granted to the system verifier and 8987 // this app is a verifier, then it gets the permission. 8988 allowed = true; 8989 } 8990 if (!allowed && (bp.protectionLevel 8991 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8992 && isSystemApp(pkg)) { 8993 // Any pre-installed system app is allowed to get this permission. 8994 allowed = true; 8995 } 8996 if (!allowed && (bp.protectionLevel 8997 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8998 // For development permissions, a development permission 8999 // is granted only if it was already granted. 9000 allowed = origPermissions.hasInstallPermission(perm); 9001 } 9002 } 9003 return allowed; 9004 } 9005 9006 final class ActivityIntentResolver 9007 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9008 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9009 boolean defaultOnly, int userId) { 9010 if (!sUserManager.exists(userId)) return null; 9011 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9012 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9013 } 9014 9015 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9016 int userId) { 9017 if (!sUserManager.exists(userId)) return null; 9018 mFlags = flags; 9019 return super.queryIntent(intent, resolvedType, 9020 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9021 } 9022 9023 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9024 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9025 if (!sUserManager.exists(userId)) return null; 9026 if (packageActivities == null) { 9027 return null; 9028 } 9029 mFlags = flags; 9030 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9031 final int N = packageActivities.size(); 9032 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9033 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9034 9035 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9036 for (int i = 0; i < N; ++i) { 9037 intentFilters = packageActivities.get(i).intents; 9038 if (intentFilters != null && intentFilters.size() > 0) { 9039 PackageParser.ActivityIntentInfo[] array = 9040 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9041 intentFilters.toArray(array); 9042 listCut.add(array); 9043 } 9044 } 9045 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9046 } 9047 9048 public final void addActivity(PackageParser.Activity a, String type) { 9049 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9050 mActivities.put(a.getComponentName(), a); 9051 if (DEBUG_SHOW_INFO) 9052 Log.v( 9053 TAG, " " + type + " " + 9054 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9055 if (DEBUG_SHOW_INFO) 9056 Log.v(TAG, " Class=" + a.info.name); 9057 final int NI = a.intents.size(); 9058 for (int j=0; j<NI; j++) { 9059 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9060 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9061 intent.setPriority(0); 9062 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9063 + a.className + " with priority > 0, forcing to 0"); 9064 } 9065 if (DEBUG_SHOW_INFO) { 9066 Log.v(TAG, " IntentFilter:"); 9067 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9068 } 9069 if (!intent.debugCheck()) { 9070 Log.w(TAG, "==> For Activity " + a.info.name); 9071 } 9072 addFilter(intent); 9073 } 9074 } 9075 9076 public final void removeActivity(PackageParser.Activity a, String type) { 9077 mActivities.remove(a.getComponentName()); 9078 if (DEBUG_SHOW_INFO) { 9079 Log.v(TAG, " " + type + " " 9080 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9081 : a.info.name) + ":"); 9082 Log.v(TAG, " Class=" + a.info.name); 9083 } 9084 final int NI = a.intents.size(); 9085 for (int j=0; j<NI; j++) { 9086 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9087 if (DEBUG_SHOW_INFO) { 9088 Log.v(TAG, " IntentFilter:"); 9089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9090 } 9091 removeFilter(intent); 9092 } 9093 } 9094 9095 @Override 9096 protected boolean allowFilterResult( 9097 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9098 ActivityInfo filterAi = filter.activity.info; 9099 for (int i=dest.size()-1; i>=0; i--) { 9100 ActivityInfo destAi = dest.get(i).activityInfo; 9101 if (destAi.name == filterAi.name 9102 && destAi.packageName == filterAi.packageName) { 9103 return false; 9104 } 9105 } 9106 return true; 9107 } 9108 9109 @Override 9110 protected ActivityIntentInfo[] newArray(int size) { 9111 return new ActivityIntentInfo[size]; 9112 } 9113 9114 @Override 9115 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9116 if (!sUserManager.exists(userId)) return true; 9117 PackageParser.Package p = filter.activity.owner; 9118 if (p != null) { 9119 PackageSetting ps = (PackageSetting)p.mExtras; 9120 if (ps != null) { 9121 // System apps are never considered stopped for purposes of 9122 // filtering, because there may be no way for the user to 9123 // actually re-launch them. 9124 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9125 && ps.getStopped(userId); 9126 } 9127 } 9128 return false; 9129 } 9130 9131 @Override 9132 protected boolean isPackageForFilter(String packageName, 9133 PackageParser.ActivityIntentInfo info) { 9134 return packageName.equals(info.activity.owner.packageName); 9135 } 9136 9137 @Override 9138 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9139 int match, int userId) { 9140 if (!sUserManager.exists(userId)) return null; 9141 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9142 return null; 9143 } 9144 final PackageParser.Activity activity = info.activity; 9145 if (mSafeMode && (activity.info.applicationInfo.flags 9146 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9147 return null; 9148 } 9149 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9150 if (ps == null) { 9151 return null; 9152 } 9153 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9154 ps.readUserState(userId), userId); 9155 if (ai == null) { 9156 return null; 9157 } 9158 final ResolveInfo res = new ResolveInfo(); 9159 res.activityInfo = ai; 9160 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9161 res.filter = info; 9162 } 9163 if (info != null) { 9164 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9165 } 9166 res.priority = info.getPriority(); 9167 res.preferredOrder = activity.owner.mPreferredOrder; 9168 //System.out.println("Result: " + res.activityInfo.className + 9169 // " = " + res.priority); 9170 res.match = match; 9171 res.isDefault = info.hasDefault; 9172 res.labelRes = info.labelRes; 9173 res.nonLocalizedLabel = info.nonLocalizedLabel; 9174 if (userNeedsBadging(userId)) { 9175 res.noResourceId = true; 9176 } else { 9177 res.icon = info.icon; 9178 } 9179 res.iconResourceId = info.icon; 9180 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9181 return res; 9182 } 9183 9184 @Override 9185 protected void sortResults(List<ResolveInfo> results) { 9186 Collections.sort(results, mResolvePrioritySorter); 9187 } 9188 9189 @Override 9190 protected void dumpFilter(PrintWriter out, String prefix, 9191 PackageParser.ActivityIntentInfo filter) { 9192 out.print(prefix); out.print( 9193 Integer.toHexString(System.identityHashCode(filter.activity))); 9194 out.print(' '); 9195 filter.activity.printComponentShortName(out); 9196 out.print(" filter "); 9197 out.println(Integer.toHexString(System.identityHashCode(filter))); 9198 } 9199 9200 @Override 9201 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9202 return filter.activity; 9203 } 9204 9205 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9206 PackageParser.Activity activity = (PackageParser.Activity)label; 9207 out.print(prefix); out.print( 9208 Integer.toHexString(System.identityHashCode(activity))); 9209 out.print(' '); 9210 activity.printComponentShortName(out); 9211 if (count > 1) { 9212 out.print(" ("); out.print(count); out.print(" filters)"); 9213 } 9214 out.println(); 9215 } 9216 9217// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9218// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9219// final List<ResolveInfo> retList = Lists.newArrayList(); 9220// while (i.hasNext()) { 9221// final ResolveInfo resolveInfo = i.next(); 9222// if (isEnabledLP(resolveInfo.activityInfo)) { 9223// retList.add(resolveInfo); 9224// } 9225// } 9226// return retList; 9227// } 9228 9229 // Keys are String (activity class name), values are Activity. 9230 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9231 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9232 private int mFlags; 9233 } 9234 9235 private final class ServiceIntentResolver 9236 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9237 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9238 boolean defaultOnly, int userId) { 9239 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9240 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9241 } 9242 9243 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9244 int userId) { 9245 if (!sUserManager.exists(userId)) return null; 9246 mFlags = flags; 9247 return super.queryIntent(intent, resolvedType, 9248 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9249 } 9250 9251 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9252 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9253 if (!sUserManager.exists(userId)) return null; 9254 if (packageServices == null) { 9255 return null; 9256 } 9257 mFlags = flags; 9258 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9259 final int N = packageServices.size(); 9260 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9261 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9262 9263 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9264 for (int i = 0; i < N; ++i) { 9265 intentFilters = packageServices.get(i).intents; 9266 if (intentFilters != null && intentFilters.size() > 0) { 9267 PackageParser.ServiceIntentInfo[] array = 9268 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9269 intentFilters.toArray(array); 9270 listCut.add(array); 9271 } 9272 } 9273 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9274 } 9275 9276 public final void addService(PackageParser.Service s) { 9277 mServices.put(s.getComponentName(), s); 9278 if (DEBUG_SHOW_INFO) { 9279 Log.v(TAG, " " 9280 + (s.info.nonLocalizedLabel != null 9281 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9282 Log.v(TAG, " Class=" + s.info.name); 9283 } 9284 final int NI = s.intents.size(); 9285 int j; 9286 for (j=0; j<NI; j++) { 9287 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9288 if (DEBUG_SHOW_INFO) { 9289 Log.v(TAG, " IntentFilter:"); 9290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9291 } 9292 if (!intent.debugCheck()) { 9293 Log.w(TAG, "==> For Service " + s.info.name); 9294 } 9295 addFilter(intent); 9296 } 9297 } 9298 9299 public final void removeService(PackageParser.Service s) { 9300 mServices.remove(s.getComponentName()); 9301 if (DEBUG_SHOW_INFO) { 9302 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9303 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9304 Log.v(TAG, " Class=" + s.info.name); 9305 } 9306 final int NI = s.intents.size(); 9307 int j; 9308 for (j=0; j<NI; j++) { 9309 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9310 if (DEBUG_SHOW_INFO) { 9311 Log.v(TAG, " IntentFilter:"); 9312 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9313 } 9314 removeFilter(intent); 9315 } 9316 } 9317 9318 @Override 9319 protected boolean allowFilterResult( 9320 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9321 ServiceInfo filterSi = filter.service.info; 9322 for (int i=dest.size()-1; i>=0; i--) { 9323 ServiceInfo destAi = dest.get(i).serviceInfo; 9324 if (destAi.name == filterSi.name 9325 && destAi.packageName == filterSi.packageName) { 9326 return false; 9327 } 9328 } 9329 return true; 9330 } 9331 9332 @Override 9333 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9334 return new PackageParser.ServiceIntentInfo[size]; 9335 } 9336 9337 @Override 9338 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9339 if (!sUserManager.exists(userId)) return true; 9340 PackageParser.Package p = filter.service.owner; 9341 if (p != null) { 9342 PackageSetting ps = (PackageSetting)p.mExtras; 9343 if (ps != null) { 9344 // System apps are never considered stopped for purposes of 9345 // filtering, because there may be no way for the user to 9346 // actually re-launch them. 9347 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9348 && ps.getStopped(userId); 9349 } 9350 } 9351 return false; 9352 } 9353 9354 @Override 9355 protected boolean isPackageForFilter(String packageName, 9356 PackageParser.ServiceIntentInfo info) { 9357 return packageName.equals(info.service.owner.packageName); 9358 } 9359 9360 @Override 9361 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9362 int match, int userId) { 9363 if (!sUserManager.exists(userId)) return null; 9364 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9365 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9366 return null; 9367 } 9368 final PackageParser.Service service = info.service; 9369 if (mSafeMode && (service.info.applicationInfo.flags 9370 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9371 return null; 9372 } 9373 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9374 if (ps == null) { 9375 return null; 9376 } 9377 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9378 ps.readUserState(userId), userId); 9379 if (si == null) { 9380 return null; 9381 } 9382 final ResolveInfo res = new ResolveInfo(); 9383 res.serviceInfo = si; 9384 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9385 res.filter = filter; 9386 } 9387 res.priority = info.getPriority(); 9388 res.preferredOrder = service.owner.mPreferredOrder; 9389 res.match = match; 9390 res.isDefault = info.hasDefault; 9391 res.labelRes = info.labelRes; 9392 res.nonLocalizedLabel = info.nonLocalizedLabel; 9393 res.icon = info.icon; 9394 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9395 return res; 9396 } 9397 9398 @Override 9399 protected void sortResults(List<ResolveInfo> results) { 9400 Collections.sort(results, mResolvePrioritySorter); 9401 } 9402 9403 @Override 9404 protected void dumpFilter(PrintWriter out, String prefix, 9405 PackageParser.ServiceIntentInfo filter) { 9406 out.print(prefix); out.print( 9407 Integer.toHexString(System.identityHashCode(filter.service))); 9408 out.print(' '); 9409 filter.service.printComponentShortName(out); 9410 out.print(" filter "); 9411 out.println(Integer.toHexString(System.identityHashCode(filter))); 9412 } 9413 9414 @Override 9415 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9416 return filter.service; 9417 } 9418 9419 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9420 PackageParser.Service service = (PackageParser.Service)label; 9421 out.print(prefix); out.print( 9422 Integer.toHexString(System.identityHashCode(service))); 9423 out.print(' '); 9424 service.printComponentShortName(out); 9425 if (count > 1) { 9426 out.print(" ("); out.print(count); out.print(" filters)"); 9427 } 9428 out.println(); 9429 } 9430 9431// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9432// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9433// final List<ResolveInfo> retList = Lists.newArrayList(); 9434// while (i.hasNext()) { 9435// final ResolveInfo resolveInfo = (ResolveInfo) i; 9436// if (isEnabledLP(resolveInfo.serviceInfo)) { 9437// retList.add(resolveInfo); 9438// } 9439// } 9440// return retList; 9441// } 9442 9443 // Keys are String (activity class name), values are Activity. 9444 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9445 = new ArrayMap<ComponentName, PackageParser.Service>(); 9446 private int mFlags; 9447 }; 9448 9449 private final class ProviderIntentResolver 9450 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9451 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9452 boolean defaultOnly, int userId) { 9453 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9454 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9455 } 9456 9457 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9458 int userId) { 9459 if (!sUserManager.exists(userId)) 9460 return null; 9461 mFlags = flags; 9462 return super.queryIntent(intent, resolvedType, 9463 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9464 } 9465 9466 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9467 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9468 if (!sUserManager.exists(userId)) 9469 return null; 9470 if (packageProviders == null) { 9471 return null; 9472 } 9473 mFlags = flags; 9474 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9475 final int N = packageProviders.size(); 9476 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9477 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9478 9479 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9480 for (int i = 0; i < N; ++i) { 9481 intentFilters = packageProviders.get(i).intents; 9482 if (intentFilters != null && intentFilters.size() > 0) { 9483 PackageParser.ProviderIntentInfo[] array = 9484 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9485 intentFilters.toArray(array); 9486 listCut.add(array); 9487 } 9488 } 9489 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9490 } 9491 9492 public final void addProvider(PackageParser.Provider p) { 9493 if (mProviders.containsKey(p.getComponentName())) { 9494 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9495 return; 9496 } 9497 9498 mProviders.put(p.getComponentName(), p); 9499 if (DEBUG_SHOW_INFO) { 9500 Log.v(TAG, " " 9501 + (p.info.nonLocalizedLabel != null 9502 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9503 Log.v(TAG, " Class=" + p.info.name); 9504 } 9505 final int NI = p.intents.size(); 9506 int j; 9507 for (j = 0; j < NI; j++) { 9508 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9509 if (DEBUG_SHOW_INFO) { 9510 Log.v(TAG, " IntentFilter:"); 9511 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9512 } 9513 if (!intent.debugCheck()) { 9514 Log.w(TAG, "==> For Provider " + p.info.name); 9515 } 9516 addFilter(intent); 9517 } 9518 } 9519 9520 public final void removeProvider(PackageParser.Provider p) { 9521 mProviders.remove(p.getComponentName()); 9522 if (DEBUG_SHOW_INFO) { 9523 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9524 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9525 Log.v(TAG, " Class=" + p.info.name); 9526 } 9527 final int NI = p.intents.size(); 9528 int j; 9529 for (j = 0; j < NI; j++) { 9530 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9531 if (DEBUG_SHOW_INFO) { 9532 Log.v(TAG, " IntentFilter:"); 9533 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9534 } 9535 removeFilter(intent); 9536 } 9537 } 9538 9539 @Override 9540 protected boolean allowFilterResult( 9541 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9542 ProviderInfo filterPi = filter.provider.info; 9543 for (int i = dest.size() - 1; i >= 0; i--) { 9544 ProviderInfo destPi = dest.get(i).providerInfo; 9545 if (destPi.name == filterPi.name 9546 && destPi.packageName == filterPi.packageName) { 9547 return false; 9548 } 9549 } 9550 return true; 9551 } 9552 9553 @Override 9554 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9555 return new PackageParser.ProviderIntentInfo[size]; 9556 } 9557 9558 @Override 9559 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9560 if (!sUserManager.exists(userId)) 9561 return true; 9562 PackageParser.Package p = filter.provider.owner; 9563 if (p != null) { 9564 PackageSetting ps = (PackageSetting) p.mExtras; 9565 if (ps != null) { 9566 // System apps are never considered stopped for purposes of 9567 // filtering, because there may be no way for the user to 9568 // actually re-launch them. 9569 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9570 && ps.getStopped(userId); 9571 } 9572 } 9573 return false; 9574 } 9575 9576 @Override 9577 protected boolean isPackageForFilter(String packageName, 9578 PackageParser.ProviderIntentInfo info) { 9579 return packageName.equals(info.provider.owner.packageName); 9580 } 9581 9582 @Override 9583 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9584 int match, int userId) { 9585 if (!sUserManager.exists(userId)) 9586 return null; 9587 final PackageParser.ProviderIntentInfo info = filter; 9588 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9589 return null; 9590 } 9591 final PackageParser.Provider provider = info.provider; 9592 if (mSafeMode && (provider.info.applicationInfo.flags 9593 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9594 return null; 9595 } 9596 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9597 if (ps == null) { 9598 return null; 9599 } 9600 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9601 ps.readUserState(userId), userId); 9602 if (pi == null) { 9603 return null; 9604 } 9605 final ResolveInfo res = new ResolveInfo(); 9606 res.providerInfo = pi; 9607 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9608 res.filter = filter; 9609 } 9610 res.priority = info.getPriority(); 9611 res.preferredOrder = provider.owner.mPreferredOrder; 9612 res.match = match; 9613 res.isDefault = info.hasDefault; 9614 res.labelRes = info.labelRes; 9615 res.nonLocalizedLabel = info.nonLocalizedLabel; 9616 res.icon = info.icon; 9617 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9618 return res; 9619 } 9620 9621 @Override 9622 protected void sortResults(List<ResolveInfo> results) { 9623 Collections.sort(results, mResolvePrioritySorter); 9624 } 9625 9626 @Override 9627 protected void dumpFilter(PrintWriter out, String prefix, 9628 PackageParser.ProviderIntentInfo filter) { 9629 out.print(prefix); 9630 out.print( 9631 Integer.toHexString(System.identityHashCode(filter.provider))); 9632 out.print(' '); 9633 filter.provider.printComponentShortName(out); 9634 out.print(" filter "); 9635 out.println(Integer.toHexString(System.identityHashCode(filter))); 9636 } 9637 9638 @Override 9639 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9640 return filter.provider; 9641 } 9642 9643 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9644 PackageParser.Provider provider = (PackageParser.Provider)label; 9645 out.print(prefix); out.print( 9646 Integer.toHexString(System.identityHashCode(provider))); 9647 out.print(' '); 9648 provider.printComponentShortName(out); 9649 if (count > 1) { 9650 out.print(" ("); out.print(count); out.print(" filters)"); 9651 } 9652 out.println(); 9653 } 9654 9655 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9656 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9657 private int mFlags; 9658 } 9659 9660 private static final class EphemeralIntentResolver 9661 extends IntentResolver<IntentFilter, ResolveInfo> { 9662 @Override 9663 protected IntentFilter[] newArray(int size) { 9664 return new IntentFilter[size]; 9665 } 9666 9667 @Override 9668 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9669 return true; 9670 } 9671 9672 @Override 9673 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9674 if (!sUserManager.exists(userId)) return null; 9675 final ResolveInfo res = new ResolveInfo(); 9676 res.filter = info; 9677 return res; 9678 } 9679 } 9680 9681 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9682 new Comparator<ResolveInfo>() { 9683 public int compare(ResolveInfo r1, ResolveInfo r2) { 9684 int v1 = r1.priority; 9685 int v2 = r2.priority; 9686 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9687 if (v1 != v2) { 9688 return (v1 > v2) ? -1 : 1; 9689 } 9690 v1 = r1.preferredOrder; 9691 v2 = r2.preferredOrder; 9692 if (v1 != v2) { 9693 return (v1 > v2) ? -1 : 1; 9694 } 9695 if (r1.isDefault != r2.isDefault) { 9696 return r1.isDefault ? -1 : 1; 9697 } 9698 v1 = r1.match; 9699 v2 = r2.match; 9700 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9701 if (v1 != v2) { 9702 return (v1 > v2) ? -1 : 1; 9703 } 9704 if (r1.system != r2.system) { 9705 return r1.system ? -1 : 1; 9706 } 9707 return 0; 9708 } 9709 }; 9710 9711 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9712 new Comparator<ProviderInfo>() { 9713 public int compare(ProviderInfo p1, ProviderInfo p2) { 9714 final int v1 = p1.initOrder; 9715 final int v2 = p2.initOrder; 9716 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9717 } 9718 }; 9719 9720 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9721 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9722 final int[] userIds) { 9723 mHandler.post(new Runnable() { 9724 @Override 9725 public void run() { 9726 try { 9727 final IActivityManager am = ActivityManagerNative.getDefault(); 9728 if (am == null) return; 9729 final int[] resolvedUserIds; 9730 if (userIds == null) { 9731 resolvedUserIds = am.getRunningUserIds(); 9732 } else { 9733 resolvedUserIds = userIds; 9734 } 9735 for (int id : resolvedUserIds) { 9736 final Intent intent = new Intent(action, 9737 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9738 if (extras != null) { 9739 intent.putExtras(extras); 9740 } 9741 if (targetPkg != null) { 9742 intent.setPackage(targetPkg); 9743 } 9744 // Modify the UID when posting to other users 9745 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9746 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9747 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9748 intent.putExtra(Intent.EXTRA_UID, uid); 9749 } 9750 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9751 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9752 if (DEBUG_BROADCASTS) { 9753 RuntimeException here = new RuntimeException("here"); 9754 here.fillInStackTrace(); 9755 Slog.d(TAG, "Sending to user " + id + ": " 9756 + intent.toShortString(false, true, false, false) 9757 + " " + intent.getExtras(), here); 9758 } 9759 am.broadcastIntent(null, intent, null, finishedReceiver, 9760 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9761 null, finishedReceiver != null, false, id); 9762 } 9763 } catch (RemoteException ex) { 9764 } 9765 } 9766 }); 9767 } 9768 9769 /** 9770 * Check if the external storage media is available. This is true if there 9771 * is a mounted external storage medium or if the external storage is 9772 * emulated. 9773 */ 9774 private boolean isExternalMediaAvailable() { 9775 return mMediaMounted || Environment.isExternalStorageEmulated(); 9776 } 9777 9778 @Override 9779 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9780 // writer 9781 synchronized (mPackages) { 9782 if (!isExternalMediaAvailable()) { 9783 // If the external storage is no longer mounted at this point, 9784 // the caller may not have been able to delete all of this 9785 // packages files and can not delete any more. Bail. 9786 return null; 9787 } 9788 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9789 if (lastPackage != null) { 9790 pkgs.remove(lastPackage); 9791 } 9792 if (pkgs.size() > 0) { 9793 return pkgs.get(0); 9794 } 9795 } 9796 return null; 9797 } 9798 9799 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9800 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9801 userId, andCode ? 1 : 0, packageName); 9802 if (mSystemReady) { 9803 msg.sendToTarget(); 9804 } else { 9805 if (mPostSystemReadyMessages == null) { 9806 mPostSystemReadyMessages = new ArrayList<>(); 9807 } 9808 mPostSystemReadyMessages.add(msg); 9809 } 9810 } 9811 9812 void startCleaningPackages() { 9813 // reader 9814 synchronized (mPackages) { 9815 if (!isExternalMediaAvailable()) { 9816 return; 9817 } 9818 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9819 return; 9820 } 9821 } 9822 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9823 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9824 IActivityManager am = ActivityManagerNative.getDefault(); 9825 if (am != null) { 9826 try { 9827 am.startService(null, intent, null, mContext.getOpPackageName(), 9828 UserHandle.USER_SYSTEM); 9829 } catch (RemoteException e) { 9830 } 9831 } 9832 } 9833 9834 @Override 9835 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9836 int installFlags, String installerPackageName, VerificationParams verificationParams, 9837 String packageAbiOverride) { 9838 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9839 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9840 } 9841 9842 @Override 9843 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9844 int installFlags, String installerPackageName, VerificationParams verificationParams, 9845 String packageAbiOverride, int userId) { 9846 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9847 9848 final int callingUid = Binder.getCallingUid(); 9849 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9850 9851 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9852 try { 9853 if (observer != null) { 9854 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9855 } 9856 } catch (RemoteException re) { 9857 } 9858 return; 9859 } 9860 9861 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9862 installFlags |= PackageManager.INSTALL_FROM_ADB; 9863 9864 } else { 9865 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9866 // about installerPackageName. 9867 9868 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9869 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9870 } 9871 9872 UserHandle user; 9873 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9874 user = UserHandle.ALL; 9875 } else { 9876 user = new UserHandle(userId); 9877 } 9878 9879 // Only system components can circumvent runtime permissions when installing. 9880 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9881 && mContext.checkCallingOrSelfPermission(Manifest.permission 9882 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9883 throw new SecurityException("You need the " 9884 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9885 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9886 } 9887 9888 verificationParams.setInstallerUid(callingUid); 9889 9890 final File originFile = new File(originPath); 9891 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9892 9893 final Message msg = mHandler.obtainMessage(INIT_COPY); 9894 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9895 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9896 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9897 msg.obj = params; 9898 9899 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9900 System.identityHashCode(msg.obj)); 9901 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9902 System.identityHashCode(msg.obj)); 9903 9904 mHandler.sendMessage(msg); 9905 } 9906 9907 void installStage(String packageName, File stagedDir, String stagedCid, 9908 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9909 String installerPackageName, int installerUid, UserHandle user) { 9910 if (DEBUG_EPHEMERAL) { 9911 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9912 Slog.d(TAG, "Ephemeral install of " + packageName); 9913 } 9914 } 9915 final VerificationParams verifParams = new VerificationParams( 9916 null, sessionParams.originatingUri, sessionParams.referrerUri, 9917 sessionParams.originatingUid, null); 9918 verifParams.setInstallerUid(installerUid); 9919 9920 final OriginInfo origin; 9921 if (stagedDir != null) { 9922 origin = OriginInfo.fromStagedFile(stagedDir); 9923 } else { 9924 origin = OriginInfo.fromStagedContainer(stagedCid); 9925 } 9926 9927 final Message msg = mHandler.obtainMessage(INIT_COPY); 9928 final InstallParams params = new InstallParams(origin, null, observer, 9929 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9930 verifParams, user, sessionParams.abiOverride, 9931 sessionParams.grantedRuntimePermissions); 9932 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9933 msg.obj = params; 9934 9935 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9936 System.identityHashCode(msg.obj)); 9937 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9938 System.identityHashCode(msg.obj)); 9939 9940 mHandler.sendMessage(msg); 9941 } 9942 9943 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9944 Bundle extras = new Bundle(1); 9945 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9946 9947 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9948 packageName, extras, 0, null, null, new int[] {userId}); 9949 try { 9950 IActivityManager am = ActivityManagerNative.getDefault(); 9951 final boolean isSystem = 9952 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9953 if (isSystem && am.isUserRunning(userId, 0)) { 9954 // The just-installed/enabled app is bundled on the system, so presumed 9955 // to be able to run automatically without needing an explicit launch. 9956 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9957 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9958 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9959 .setPackage(packageName); 9960 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9961 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9962 } 9963 } catch (RemoteException e) { 9964 // shouldn't happen 9965 Slog.w(TAG, "Unable to bootstrap installed package", e); 9966 } 9967 } 9968 9969 @Override 9970 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9971 int userId) { 9972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9973 PackageSetting pkgSetting; 9974 final int uid = Binder.getCallingUid(); 9975 enforceCrossUserPermission(uid, userId, true, true, 9976 "setApplicationHiddenSetting for user " + userId); 9977 9978 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9979 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9980 return false; 9981 } 9982 9983 long callingId = Binder.clearCallingIdentity(); 9984 try { 9985 boolean sendAdded = false; 9986 boolean sendRemoved = false; 9987 // writer 9988 synchronized (mPackages) { 9989 pkgSetting = mSettings.mPackages.get(packageName); 9990 if (pkgSetting == null) { 9991 return false; 9992 } 9993 if (pkgSetting.getHidden(userId) != hidden) { 9994 pkgSetting.setHidden(hidden, userId); 9995 mSettings.writePackageRestrictionsLPr(userId); 9996 if (hidden) { 9997 sendRemoved = true; 9998 } else { 9999 sendAdded = true; 10000 } 10001 } 10002 } 10003 if (sendAdded) { 10004 sendPackageAddedForUser(packageName, pkgSetting, userId); 10005 return true; 10006 } 10007 if (sendRemoved) { 10008 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10009 "hiding pkg"); 10010 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10011 return true; 10012 } 10013 } finally { 10014 Binder.restoreCallingIdentity(callingId); 10015 } 10016 return false; 10017 } 10018 10019 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10020 int userId) { 10021 final PackageRemovedInfo info = new PackageRemovedInfo(); 10022 info.removedPackage = packageName; 10023 info.removedUsers = new int[] {userId}; 10024 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10025 info.sendBroadcast(false, false, false); 10026 } 10027 10028 /** 10029 * Returns true if application is not found or there was an error. Otherwise it returns 10030 * the hidden state of the package for the given user. 10031 */ 10032 @Override 10033 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10035 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10036 false, "getApplicationHidden for user " + userId); 10037 PackageSetting pkgSetting; 10038 long callingId = Binder.clearCallingIdentity(); 10039 try { 10040 // writer 10041 synchronized (mPackages) { 10042 pkgSetting = mSettings.mPackages.get(packageName); 10043 if (pkgSetting == null) { 10044 return true; 10045 } 10046 return pkgSetting.getHidden(userId); 10047 } 10048 } finally { 10049 Binder.restoreCallingIdentity(callingId); 10050 } 10051 } 10052 10053 /** 10054 * @hide 10055 */ 10056 @Override 10057 public int installExistingPackageAsUser(String packageName, int userId) { 10058 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10059 null); 10060 PackageSetting pkgSetting; 10061 final int uid = Binder.getCallingUid(); 10062 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10063 + userId); 10064 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10065 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10066 } 10067 10068 long callingId = Binder.clearCallingIdentity(); 10069 try { 10070 boolean sendAdded = false; 10071 10072 // writer 10073 synchronized (mPackages) { 10074 pkgSetting = mSettings.mPackages.get(packageName); 10075 if (pkgSetting == null) { 10076 return PackageManager.INSTALL_FAILED_INVALID_URI; 10077 } 10078 if (!pkgSetting.getInstalled(userId)) { 10079 pkgSetting.setInstalled(true, userId); 10080 pkgSetting.setHidden(false, userId); 10081 mSettings.writePackageRestrictionsLPr(userId); 10082 sendAdded = true; 10083 } 10084 } 10085 10086 if (sendAdded) { 10087 sendPackageAddedForUser(packageName, pkgSetting, userId); 10088 } 10089 } finally { 10090 Binder.restoreCallingIdentity(callingId); 10091 } 10092 10093 return PackageManager.INSTALL_SUCCEEDED; 10094 } 10095 10096 boolean isUserRestricted(int userId, String restrictionKey) { 10097 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10098 if (restrictions.getBoolean(restrictionKey, false)) { 10099 Log.w(TAG, "User is restricted: " + restrictionKey); 10100 return true; 10101 } 10102 return false; 10103 } 10104 10105 @Override 10106 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10107 mContext.enforceCallingOrSelfPermission( 10108 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10109 "Only package verification agents can verify applications"); 10110 10111 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10112 final PackageVerificationResponse response = new PackageVerificationResponse( 10113 verificationCode, Binder.getCallingUid()); 10114 msg.arg1 = id; 10115 msg.obj = response; 10116 mHandler.sendMessage(msg); 10117 } 10118 10119 @Override 10120 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10121 long millisecondsToDelay) { 10122 mContext.enforceCallingOrSelfPermission( 10123 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10124 "Only package verification agents can extend verification timeouts"); 10125 10126 final PackageVerificationState state = mPendingVerification.get(id); 10127 final PackageVerificationResponse response = new PackageVerificationResponse( 10128 verificationCodeAtTimeout, Binder.getCallingUid()); 10129 10130 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10131 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10132 } 10133 if (millisecondsToDelay < 0) { 10134 millisecondsToDelay = 0; 10135 } 10136 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10137 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10138 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10139 } 10140 10141 if ((state != null) && !state.timeoutExtended()) { 10142 state.extendTimeout(); 10143 10144 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10145 msg.arg1 = id; 10146 msg.obj = response; 10147 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10148 } 10149 } 10150 10151 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10152 int verificationCode, UserHandle user) { 10153 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10154 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10155 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10156 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10157 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10158 10159 mContext.sendBroadcastAsUser(intent, user, 10160 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10161 } 10162 10163 private ComponentName matchComponentForVerifier(String packageName, 10164 List<ResolveInfo> receivers) { 10165 ActivityInfo targetReceiver = null; 10166 10167 final int NR = receivers.size(); 10168 for (int i = 0; i < NR; i++) { 10169 final ResolveInfo info = receivers.get(i); 10170 if (info.activityInfo == null) { 10171 continue; 10172 } 10173 10174 if (packageName.equals(info.activityInfo.packageName)) { 10175 targetReceiver = info.activityInfo; 10176 break; 10177 } 10178 } 10179 10180 if (targetReceiver == null) { 10181 return null; 10182 } 10183 10184 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10185 } 10186 10187 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10188 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10189 if (pkgInfo.verifiers.length == 0) { 10190 return null; 10191 } 10192 10193 final int N = pkgInfo.verifiers.length; 10194 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10195 for (int i = 0; i < N; i++) { 10196 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10197 10198 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10199 receivers); 10200 if (comp == null) { 10201 continue; 10202 } 10203 10204 final int verifierUid = getUidForVerifier(verifierInfo); 10205 if (verifierUid == -1) { 10206 continue; 10207 } 10208 10209 if (DEBUG_VERIFY) { 10210 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10211 + " with the correct signature"); 10212 } 10213 sufficientVerifiers.add(comp); 10214 verificationState.addSufficientVerifier(verifierUid); 10215 } 10216 10217 return sufficientVerifiers; 10218 } 10219 10220 private int getUidForVerifier(VerifierInfo verifierInfo) { 10221 synchronized (mPackages) { 10222 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10223 if (pkg == null) { 10224 return -1; 10225 } else if (pkg.mSignatures.length != 1) { 10226 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10227 + " has more than one signature; ignoring"); 10228 return -1; 10229 } 10230 10231 /* 10232 * If the public key of the package's signature does not match 10233 * our expected public key, then this is a different package and 10234 * we should skip. 10235 */ 10236 10237 final byte[] expectedPublicKey; 10238 try { 10239 final Signature verifierSig = pkg.mSignatures[0]; 10240 final PublicKey publicKey = verifierSig.getPublicKey(); 10241 expectedPublicKey = publicKey.getEncoded(); 10242 } catch (CertificateException e) { 10243 return -1; 10244 } 10245 10246 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10247 10248 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10249 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10250 + " does not have the expected public key; ignoring"); 10251 return -1; 10252 } 10253 10254 return pkg.applicationInfo.uid; 10255 } 10256 } 10257 10258 @Override 10259 public void finishPackageInstall(int token) { 10260 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10261 10262 if (DEBUG_INSTALL) { 10263 Slog.v(TAG, "BM finishing package install for " + token); 10264 } 10265 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10266 10267 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10268 mHandler.sendMessage(msg); 10269 } 10270 10271 /** 10272 * Get the verification agent timeout. 10273 * 10274 * @return verification timeout in milliseconds 10275 */ 10276 private long getVerificationTimeout() { 10277 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10278 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10279 DEFAULT_VERIFICATION_TIMEOUT); 10280 } 10281 10282 /** 10283 * Get the default verification agent response code. 10284 * 10285 * @return default verification response code 10286 */ 10287 private int getDefaultVerificationResponse() { 10288 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10289 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10290 DEFAULT_VERIFICATION_RESPONSE); 10291 } 10292 10293 /** 10294 * Check whether or not package verification has been enabled. 10295 * 10296 * @return true if verification should be performed 10297 */ 10298 private boolean isVerificationEnabled(int userId, int installFlags) { 10299 if (!DEFAULT_VERIFY_ENABLE) { 10300 return false; 10301 } 10302 // TODO: fix b/25118622; don't bypass verification 10303 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10304 return false; 10305 } 10306 // Ephemeral apps don't get the full verification treatment 10307 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10308 if (DEBUG_EPHEMERAL) { 10309 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10310 } 10311 return false; 10312 } 10313 10314 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10315 10316 // Check if installing from ADB 10317 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10318 // Do not run verification in a test harness environment 10319 if (ActivityManager.isRunningInTestHarness()) { 10320 return false; 10321 } 10322 if (ensureVerifyAppsEnabled) { 10323 return true; 10324 } 10325 // Check if the developer does not want package verification for ADB installs 10326 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10327 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10328 return false; 10329 } 10330 } 10331 10332 if (ensureVerifyAppsEnabled) { 10333 return true; 10334 } 10335 10336 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10337 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10338 } 10339 10340 @Override 10341 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10342 throws RemoteException { 10343 mContext.enforceCallingOrSelfPermission( 10344 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10345 "Only intentfilter verification agents can verify applications"); 10346 10347 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10348 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10349 Binder.getCallingUid(), verificationCode, failedDomains); 10350 msg.arg1 = id; 10351 msg.obj = response; 10352 mHandler.sendMessage(msg); 10353 } 10354 10355 @Override 10356 public int getIntentVerificationStatus(String packageName, int userId) { 10357 synchronized (mPackages) { 10358 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10359 } 10360 } 10361 10362 @Override 10363 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10364 mContext.enforceCallingOrSelfPermission( 10365 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10366 10367 boolean result = false; 10368 synchronized (mPackages) { 10369 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10370 } 10371 if (result) { 10372 scheduleWritePackageRestrictionsLocked(userId); 10373 } 10374 return result; 10375 } 10376 10377 @Override 10378 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10379 synchronized (mPackages) { 10380 return mSettings.getIntentFilterVerificationsLPr(packageName); 10381 } 10382 } 10383 10384 @Override 10385 public List<IntentFilter> getAllIntentFilters(String packageName) { 10386 if (TextUtils.isEmpty(packageName)) { 10387 return Collections.<IntentFilter>emptyList(); 10388 } 10389 synchronized (mPackages) { 10390 PackageParser.Package pkg = mPackages.get(packageName); 10391 if (pkg == null || pkg.activities == null) { 10392 return Collections.<IntentFilter>emptyList(); 10393 } 10394 final int count = pkg.activities.size(); 10395 ArrayList<IntentFilter> result = new ArrayList<>(); 10396 for (int n=0; n<count; n++) { 10397 PackageParser.Activity activity = pkg.activities.get(n); 10398 if (activity.intents != null || activity.intents.size() > 0) { 10399 result.addAll(activity.intents); 10400 } 10401 } 10402 return result; 10403 } 10404 } 10405 10406 @Override 10407 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10408 mContext.enforceCallingOrSelfPermission( 10409 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10410 10411 synchronized (mPackages) { 10412 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10413 if (packageName != null) { 10414 result |= updateIntentVerificationStatus(packageName, 10415 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10416 userId); 10417 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10418 packageName, userId); 10419 } 10420 return result; 10421 } 10422 } 10423 10424 @Override 10425 public String getDefaultBrowserPackageName(int userId) { 10426 synchronized (mPackages) { 10427 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10428 } 10429 } 10430 10431 /** 10432 * Get the "allow unknown sources" setting. 10433 * 10434 * @return the current "allow unknown sources" setting 10435 */ 10436 private int getUnknownSourcesSettings() { 10437 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10438 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10439 -1); 10440 } 10441 10442 @Override 10443 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10444 final int uid = Binder.getCallingUid(); 10445 // writer 10446 synchronized (mPackages) { 10447 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10448 if (targetPackageSetting == null) { 10449 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10450 } 10451 10452 PackageSetting installerPackageSetting; 10453 if (installerPackageName != null) { 10454 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10455 if (installerPackageSetting == null) { 10456 throw new IllegalArgumentException("Unknown installer package: " 10457 + installerPackageName); 10458 } 10459 } else { 10460 installerPackageSetting = null; 10461 } 10462 10463 Signature[] callerSignature; 10464 Object obj = mSettings.getUserIdLPr(uid); 10465 if (obj != null) { 10466 if (obj instanceof SharedUserSetting) { 10467 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10468 } else if (obj instanceof PackageSetting) { 10469 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10470 } else { 10471 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10472 } 10473 } else { 10474 throw new SecurityException("Unknown calling uid " + uid); 10475 } 10476 10477 // Verify: can't set installerPackageName to a package that is 10478 // not signed with the same cert as the caller. 10479 if (installerPackageSetting != null) { 10480 if (compareSignatures(callerSignature, 10481 installerPackageSetting.signatures.mSignatures) 10482 != PackageManager.SIGNATURE_MATCH) { 10483 throw new SecurityException( 10484 "Caller does not have same cert as new installer package " 10485 + installerPackageName); 10486 } 10487 } 10488 10489 // Verify: if target already has an installer package, it must 10490 // be signed with the same cert as the caller. 10491 if (targetPackageSetting.installerPackageName != null) { 10492 PackageSetting setting = mSettings.mPackages.get( 10493 targetPackageSetting.installerPackageName); 10494 // If the currently set package isn't valid, then it's always 10495 // okay to change it. 10496 if (setting != null) { 10497 if (compareSignatures(callerSignature, 10498 setting.signatures.mSignatures) 10499 != PackageManager.SIGNATURE_MATCH) { 10500 throw new SecurityException( 10501 "Caller does not have same cert as old installer package " 10502 + targetPackageSetting.installerPackageName); 10503 } 10504 } 10505 } 10506 10507 // Okay! 10508 targetPackageSetting.installerPackageName = installerPackageName; 10509 scheduleWriteSettingsLocked(); 10510 } 10511 } 10512 10513 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10514 // Queue up an async operation since the package installation may take a little while. 10515 mHandler.post(new Runnable() { 10516 public void run() { 10517 mHandler.removeCallbacks(this); 10518 // Result object to be returned 10519 PackageInstalledInfo res = new PackageInstalledInfo(); 10520 res.returnCode = currentStatus; 10521 res.uid = -1; 10522 res.pkg = null; 10523 res.removedInfo = new PackageRemovedInfo(); 10524 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10525 args.doPreInstall(res.returnCode); 10526 synchronized (mInstallLock) { 10527 installPackageTracedLI(args, res); 10528 } 10529 args.doPostInstall(res.returnCode, res.uid); 10530 } 10531 10532 // A restore should be performed at this point if (a) the install 10533 // succeeded, (b) the operation is not an update, and (c) the new 10534 // package has not opted out of backup participation. 10535 final boolean update = res.removedInfo.removedPackage != null; 10536 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10537 boolean doRestore = !update 10538 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10539 10540 // Set up the post-install work request bookkeeping. This will be used 10541 // and cleaned up by the post-install event handling regardless of whether 10542 // there's a restore pass performed. Token values are >= 1. 10543 int token; 10544 if (mNextInstallToken < 0) mNextInstallToken = 1; 10545 token = mNextInstallToken++; 10546 10547 PostInstallData data = new PostInstallData(args, res); 10548 mRunningInstalls.put(token, data); 10549 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10550 10551 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10552 // Pass responsibility to the Backup Manager. It will perform a 10553 // restore if appropriate, then pass responsibility back to the 10554 // Package Manager to run the post-install observer callbacks 10555 // and broadcasts. 10556 IBackupManager bm = IBackupManager.Stub.asInterface( 10557 ServiceManager.getService(Context.BACKUP_SERVICE)); 10558 if (bm != null) { 10559 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10560 + " to BM for possible restore"); 10561 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10562 try { 10563 // TODO: http://b/22388012 10564 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10565 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10566 } else { 10567 doRestore = false; 10568 } 10569 } catch (RemoteException e) { 10570 // can't happen; the backup manager is local 10571 } catch (Exception e) { 10572 Slog.e(TAG, "Exception trying to enqueue restore", e); 10573 doRestore = false; 10574 } 10575 } else { 10576 Slog.e(TAG, "Backup Manager not found!"); 10577 doRestore = false; 10578 } 10579 } 10580 10581 if (!doRestore) { 10582 // No restore possible, or the Backup Manager was mysteriously not 10583 // available -- just fire the post-install work request directly. 10584 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10585 10586 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10587 10588 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10589 mHandler.sendMessage(msg); 10590 } 10591 } 10592 }); 10593 } 10594 10595 private abstract class HandlerParams { 10596 private static final int MAX_RETRIES = 4; 10597 10598 /** 10599 * Number of times startCopy() has been attempted and had a non-fatal 10600 * error. 10601 */ 10602 private int mRetries = 0; 10603 10604 /** User handle for the user requesting the information or installation. */ 10605 private final UserHandle mUser; 10606 String traceMethod; 10607 int traceCookie; 10608 10609 HandlerParams(UserHandle user) { 10610 mUser = user; 10611 } 10612 10613 UserHandle getUser() { 10614 return mUser; 10615 } 10616 10617 HandlerParams setTraceMethod(String traceMethod) { 10618 this.traceMethod = traceMethod; 10619 return this; 10620 } 10621 10622 HandlerParams setTraceCookie(int traceCookie) { 10623 this.traceCookie = traceCookie; 10624 return this; 10625 } 10626 10627 final boolean startCopy() { 10628 boolean res; 10629 try { 10630 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10631 10632 if (++mRetries > MAX_RETRIES) { 10633 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10634 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10635 handleServiceError(); 10636 return false; 10637 } else { 10638 handleStartCopy(); 10639 res = true; 10640 } 10641 } catch (RemoteException e) { 10642 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10643 mHandler.sendEmptyMessage(MCS_RECONNECT); 10644 res = false; 10645 } 10646 handleReturnCode(); 10647 return res; 10648 } 10649 10650 final void serviceError() { 10651 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10652 handleServiceError(); 10653 handleReturnCode(); 10654 } 10655 10656 abstract void handleStartCopy() throws RemoteException; 10657 abstract void handleServiceError(); 10658 abstract void handleReturnCode(); 10659 } 10660 10661 class MeasureParams extends HandlerParams { 10662 private final PackageStats mStats; 10663 private boolean mSuccess; 10664 10665 private final IPackageStatsObserver mObserver; 10666 10667 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10668 super(new UserHandle(stats.userHandle)); 10669 mObserver = observer; 10670 mStats = stats; 10671 } 10672 10673 @Override 10674 public String toString() { 10675 return "MeasureParams{" 10676 + Integer.toHexString(System.identityHashCode(this)) 10677 + " " + mStats.packageName + "}"; 10678 } 10679 10680 @Override 10681 void handleStartCopy() throws RemoteException { 10682 synchronized (mInstallLock) { 10683 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10684 } 10685 10686 if (mSuccess) { 10687 final boolean mounted; 10688 if (Environment.isExternalStorageEmulated()) { 10689 mounted = true; 10690 } else { 10691 final String status = Environment.getExternalStorageState(); 10692 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10693 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10694 } 10695 10696 if (mounted) { 10697 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10698 10699 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10700 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10701 10702 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10703 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10704 10705 // Always subtract cache size, since it's a subdirectory 10706 mStats.externalDataSize -= mStats.externalCacheSize; 10707 10708 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10709 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10710 10711 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10712 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10713 } 10714 } 10715 } 10716 10717 @Override 10718 void handleReturnCode() { 10719 if (mObserver != null) { 10720 try { 10721 mObserver.onGetStatsCompleted(mStats, mSuccess); 10722 } catch (RemoteException e) { 10723 Slog.i(TAG, "Observer no longer exists."); 10724 } 10725 } 10726 } 10727 10728 @Override 10729 void handleServiceError() { 10730 Slog.e(TAG, "Could not measure application " + mStats.packageName 10731 + " external storage"); 10732 } 10733 } 10734 10735 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10736 throws RemoteException { 10737 long result = 0; 10738 for (File path : paths) { 10739 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10740 } 10741 return result; 10742 } 10743 10744 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10745 for (File path : paths) { 10746 try { 10747 mcs.clearDirectory(path.getAbsolutePath()); 10748 } catch (RemoteException e) { 10749 } 10750 } 10751 } 10752 10753 static class OriginInfo { 10754 /** 10755 * Location where install is coming from, before it has been 10756 * copied/renamed into place. This could be a single monolithic APK 10757 * file, or a cluster directory. This location may be untrusted. 10758 */ 10759 final File file; 10760 final String cid; 10761 10762 /** 10763 * Flag indicating that {@link #file} or {@link #cid} has already been 10764 * staged, meaning downstream users don't need to defensively copy the 10765 * contents. 10766 */ 10767 final boolean staged; 10768 10769 /** 10770 * Flag indicating that {@link #file} or {@link #cid} is an already 10771 * installed app that is being moved. 10772 */ 10773 final boolean existing; 10774 10775 final String resolvedPath; 10776 final File resolvedFile; 10777 10778 static OriginInfo fromNothing() { 10779 return new OriginInfo(null, null, false, false); 10780 } 10781 10782 static OriginInfo fromUntrustedFile(File file) { 10783 return new OriginInfo(file, null, false, false); 10784 } 10785 10786 static OriginInfo fromExistingFile(File file) { 10787 return new OriginInfo(file, null, false, true); 10788 } 10789 10790 static OriginInfo fromStagedFile(File file) { 10791 return new OriginInfo(file, null, true, false); 10792 } 10793 10794 static OriginInfo fromStagedContainer(String cid) { 10795 return new OriginInfo(null, cid, true, false); 10796 } 10797 10798 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10799 this.file = file; 10800 this.cid = cid; 10801 this.staged = staged; 10802 this.existing = existing; 10803 10804 if (cid != null) { 10805 resolvedPath = PackageHelper.getSdDir(cid); 10806 resolvedFile = new File(resolvedPath); 10807 } else if (file != null) { 10808 resolvedPath = file.getAbsolutePath(); 10809 resolvedFile = file; 10810 } else { 10811 resolvedPath = null; 10812 resolvedFile = null; 10813 } 10814 } 10815 } 10816 10817 class MoveInfo { 10818 final int moveId; 10819 final String fromUuid; 10820 final String toUuid; 10821 final String packageName; 10822 final String dataAppName; 10823 final int appId; 10824 final String seinfo; 10825 10826 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10827 String dataAppName, int appId, String seinfo) { 10828 this.moveId = moveId; 10829 this.fromUuid = fromUuid; 10830 this.toUuid = toUuid; 10831 this.packageName = packageName; 10832 this.dataAppName = dataAppName; 10833 this.appId = appId; 10834 this.seinfo = seinfo; 10835 } 10836 } 10837 10838 class InstallParams extends HandlerParams { 10839 final OriginInfo origin; 10840 final MoveInfo move; 10841 final IPackageInstallObserver2 observer; 10842 int installFlags; 10843 final String installerPackageName; 10844 final String volumeUuid; 10845 final VerificationParams verificationParams; 10846 private InstallArgs mArgs; 10847 private int mRet; 10848 final String packageAbiOverride; 10849 final String[] grantedRuntimePermissions; 10850 10851 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10852 int installFlags, String installerPackageName, String volumeUuid, 10853 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10854 String[] grantedPermissions) { 10855 super(user); 10856 this.origin = origin; 10857 this.move = move; 10858 this.observer = observer; 10859 this.installFlags = installFlags; 10860 this.installerPackageName = installerPackageName; 10861 this.volumeUuid = volumeUuid; 10862 this.verificationParams = verificationParams; 10863 this.packageAbiOverride = packageAbiOverride; 10864 this.grantedRuntimePermissions = grantedPermissions; 10865 } 10866 10867 @Override 10868 public String toString() { 10869 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10870 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10871 } 10872 10873 public ManifestDigest getManifestDigest() { 10874 if (verificationParams == null) { 10875 return null; 10876 } 10877 return verificationParams.getManifestDigest(); 10878 } 10879 10880 private int installLocationPolicy(PackageInfoLite pkgLite) { 10881 String packageName = pkgLite.packageName; 10882 int installLocation = pkgLite.installLocation; 10883 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10884 // reader 10885 synchronized (mPackages) { 10886 PackageParser.Package pkg = mPackages.get(packageName); 10887 if (pkg != null) { 10888 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10889 // Check for downgrading. 10890 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10891 try { 10892 checkDowngrade(pkg, pkgLite); 10893 } catch (PackageManagerException e) { 10894 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10895 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10896 } 10897 } 10898 // Check for updated system application. 10899 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10900 if (onSd) { 10901 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10902 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10903 } 10904 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10905 } else { 10906 if (onSd) { 10907 // Install flag overrides everything. 10908 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10909 } 10910 // If current upgrade specifies particular preference 10911 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10912 // Application explicitly specified internal. 10913 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10914 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10915 // App explictly prefers external. Let policy decide 10916 } else { 10917 // Prefer previous location 10918 if (isExternal(pkg)) { 10919 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10920 } 10921 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10922 } 10923 } 10924 } else { 10925 // Invalid install. Return error code 10926 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10927 } 10928 } 10929 } 10930 // All the special cases have been taken care of. 10931 // Return result based on recommended install location. 10932 if (onSd) { 10933 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10934 } 10935 return pkgLite.recommendedInstallLocation; 10936 } 10937 10938 /* 10939 * Invoke remote method to get package information and install 10940 * location values. Override install location based on default 10941 * policy if needed and then create install arguments based 10942 * on the install location. 10943 */ 10944 public void handleStartCopy() throws RemoteException { 10945 int ret = PackageManager.INSTALL_SUCCEEDED; 10946 10947 // If we're already staged, we've firmly committed to an install location 10948 if (origin.staged) { 10949 if (origin.file != null) { 10950 installFlags |= PackageManager.INSTALL_INTERNAL; 10951 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10952 } else if (origin.cid != null) { 10953 installFlags |= PackageManager.INSTALL_EXTERNAL; 10954 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10955 } else { 10956 throw new IllegalStateException("Invalid stage location"); 10957 } 10958 } 10959 10960 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10961 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10962 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 10963 PackageInfoLite pkgLite = null; 10964 10965 if (onInt && onSd) { 10966 // Check if both bits are set. 10967 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10968 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10969 } else if (onSd && ephemeral) { 10970 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 10971 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10972 } else { 10973 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10974 packageAbiOverride); 10975 10976 if (DEBUG_EPHEMERAL && ephemeral) { 10977 Slog.v(TAG, "pkgLite for install: " + pkgLite); 10978 } 10979 10980 /* 10981 * If we have too little free space, try to free cache 10982 * before giving up. 10983 */ 10984 if (!origin.staged && pkgLite.recommendedInstallLocation 10985 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10986 // TODO: focus freeing disk space on the target device 10987 final StorageManager storage = StorageManager.from(mContext); 10988 final long lowThreshold = storage.getStorageLowBytes( 10989 Environment.getDataDirectory()); 10990 10991 final long sizeBytes = mContainerService.calculateInstalledSize( 10992 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10993 10994 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10995 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10996 installFlags, packageAbiOverride); 10997 } 10998 10999 /* 11000 * The cache free must have deleted the file we 11001 * downloaded to install. 11002 * 11003 * TODO: fix the "freeCache" call to not delete 11004 * the file we care about. 11005 */ 11006 if (pkgLite.recommendedInstallLocation 11007 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11008 pkgLite.recommendedInstallLocation 11009 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11010 } 11011 } 11012 } 11013 11014 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11015 int loc = pkgLite.recommendedInstallLocation; 11016 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11017 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11018 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11019 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11020 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11021 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11022 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11023 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11024 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11025 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11026 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11027 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11028 } else { 11029 // Override with defaults if needed. 11030 loc = installLocationPolicy(pkgLite); 11031 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11032 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11033 } else if (!onSd && !onInt) { 11034 // Override install location with flags 11035 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11036 // Set the flag to install on external media. 11037 installFlags |= PackageManager.INSTALL_EXTERNAL; 11038 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11039 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11040 if (DEBUG_EPHEMERAL) { 11041 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11042 } 11043 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11044 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11045 |PackageManager.INSTALL_INTERNAL); 11046 } else { 11047 // Make sure the flag for installing on external 11048 // media is unset 11049 installFlags |= PackageManager.INSTALL_INTERNAL; 11050 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11051 } 11052 } 11053 } 11054 } 11055 11056 final InstallArgs args = createInstallArgs(this); 11057 mArgs = args; 11058 11059 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11060 // TODO: http://b/22976637 11061 // Apps installed for "all" users use the device owner to verify the app 11062 UserHandle verifierUser = getUser(); 11063 if (verifierUser == UserHandle.ALL) { 11064 verifierUser = UserHandle.SYSTEM; 11065 } 11066 11067 /* 11068 * Determine if we have any installed package verifiers. If we 11069 * do, then we'll defer to them to verify the packages. 11070 */ 11071 final int requiredUid = mRequiredVerifierPackage == null ? -1 11072 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11073 if (!origin.existing && requiredUid != -1 11074 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11075 final Intent verification = new Intent( 11076 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11077 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11078 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11079 PACKAGE_MIME_TYPE); 11080 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11081 11082 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11083 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11084 verifierUser.getIdentifier()); 11085 11086 if (DEBUG_VERIFY) { 11087 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11088 + verification.toString() + " with " + pkgLite.verifiers.length 11089 + " optional verifiers"); 11090 } 11091 11092 final int verificationId = mPendingVerificationToken++; 11093 11094 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11095 11096 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11097 installerPackageName); 11098 11099 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11100 installFlags); 11101 11102 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11103 pkgLite.packageName); 11104 11105 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11106 pkgLite.versionCode); 11107 11108 if (verificationParams != null) { 11109 if (verificationParams.getVerificationURI() != null) { 11110 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11111 verificationParams.getVerificationURI()); 11112 } 11113 if (verificationParams.getOriginatingURI() != null) { 11114 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11115 verificationParams.getOriginatingURI()); 11116 } 11117 if (verificationParams.getReferrer() != null) { 11118 verification.putExtra(Intent.EXTRA_REFERRER, 11119 verificationParams.getReferrer()); 11120 } 11121 if (verificationParams.getOriginatingUid() >= 0) { 11122 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11123 verificationParams.getOriginatingUid()); 11124 } 11125 if (verificationParams.getInstallerUid() >= 0) { 11126 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11127 verificationParams.getInstallerUid()); 11128 } 11129 } 11130 11131 final PackageVerificationState verificationState = new PackageVerificationState( 11132 requiredUid, args); 11133 11134 mPendingVerification.append(verificationId, verificationState); 11135 11136 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11137 receivers, verificationState); 11138 11139 /* 11140 * If any sufficient verifiers were listed in the package 11141 * manifest, attempt to ask them. 11142 */ 11143 if (sufficientVerifiers != null) { 11144 final int N = sufficientVerifiers.size(); 11145 if (N == 0) { 11146 Slog.i(TAG, "Additional verifiers required, but none installed."); 11147 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11148 } else { 11149 for (int i = 0; i < N; i++) { 11150 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11151 11152 final Intent sufficientIntent = new Intent(verification); 11153 sufficientIntent.setComponent(verifierComponent); 11154 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11155 } 11156 } 11157 } 11158 11159 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11160 mRequiredVerifierPackage, receivers); 11161 if (ret == PackageManager.INSTALL_SUCCEEDED 11162 && mRequiredVerifierPackage != null) { 11163 Trace.asyncTraceBegin( 11164 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11165 /* 11166 * Send the intent to the required verification agent, 11167 * but only start the verification timeout after the 11168 * target BroadcastReceivers have run. 11169 */ 11170 verification.setComponent(requiredVerifierComponent); 11171 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11172 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11173 new BroadcastReceiver() { 11174 @Override 11175 public void onReceive(Context context, Intent intent) { 11176 final Message msg = mHandler 11177 .obtainMessage(CHECK_PENDING_VERIFICATION); 11178 msg.arg1 = verificationId; 11179 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11180 } 11181 }, null, 0, null, null); 11182 11183 /* 11184 * We don't want the copy to proceed until verification 11185 * succeeds, so null out this field. 11186 */ 11187 mArgs = null; 11188 } 11189 } else { 11190 /* 11191 * No package verification is enabled, so immediately start 11192 * the remote call to initiate copy using temporary file. 11193 */ 11194 ret = args.copyApk(mContainerService, true); 11195 } 11196 } 11197 11198 mRet = ret; 11199 } 11200 11201 @Override 11202 void handleReturnCode() { 11203 // If mArgs is null, then MCS couldn't be reached. When it 11204 // reconnects, it will try again to install. At that point, this 11205 // will succeed. 11206 if (mArgs != null) { 11207 processPendingInstall(mArgs, mRet); 11208 } 11209 } 11210 11211 @Override 11212 void handleServiceError() { 11213 mArgs = createInstallArgs(this); 11214 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11215 } 11216 11217 public boolean isForwardLocked() { 11218 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11219 } 11220 } 11221 11222 /** 11223 * Used during creation of InstallArgs 11224 * 11225 * @param installFlags package installation flags 11226 * @return true if should be installed on external storage 11227 */ 11228 private static boolean installOnExternalAsec(int installFlags) { 11229 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11230 return false; 11231 } 11232 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11233 return true; 11234 } 11235 return false; 11236 } 11237 11238 /** 11239 * Used during creation of InstallArgs 11240 * 11241 * @param installFlags package installation flags 11242 * @return true if should be installed as forward locked 11243 */ 11244 private static boolean installForwardLocked(int installFlags) { 11245 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11246 } 11247 11248 private InstallArgs createInstallArgs(InstallParams params) { 11249 if (params.move != null) { 11250 return new MoveInstallArgs(params); 11251 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11252 return new AsecInstallArgs(params); 11253 } else { 11254 return new FileInstallArgs(params); 11255 } 11256 } 11257 11258 /** 11259 * Create args that describe an existing installed package. Typically used 11260 * when cleaning up old installs, or used as a move source. 11261 */ 11262 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11263 String resourcePath, String[] instructionSets) { 11264 final boolean isInAsec; 11265 if (installOnExternalAsec(installFlags)) { 11266 /* Apps on SD card are always in ASEC containers. */ 11267 isInAsec = true; 11268 } else if (installForwardLocked(installFlags) 11269 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11270 /* 11271 * Forward-locked apps are only in ASEC containers if they're the 11272 * new style 11273 */ 11274 isInAsec = true; 11275 } else { 11276 isInAsec = false; 11277 } 11278 11279 if (isInAsec) { 11280 return new AsecInstallArgs(codePath, instructionSets, 11281 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11282 } else { 11283 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11284 } 11285 } 11286 11287 static abstract class InstallArgs { 11288 /** @see InstallParams#origin */ 11289 final OriginInfo origin; 11290 /** @see InstallParams#move */ 11291 final MoveInfo move; 11292 11293 final IPackageInstallObserver2 observer; 11294 // Always refers to PackageManager flags only 11295 final int installFlags; 11296 final String installerPackageName; 11297 final String volumeUuid; 11298 final ManifestDigest manifestDigest; 11299 final UserHandle user; 11300 final String abiOverride; 11301 final String[] installGrantPermissions; 11302 /** If non-null, drop an async trace when the install completes */ 11303 final String traceMethod; 11304 final int traceCookie; 11305 11306 // The list of instruction sets supported by this app. This is currently 11307 // only used during the rmdex() phase to clean up resources. We can get rid of this 11308 // if we move dex files under the common app path. 11309 /* nullable */ String[] instructionSets; 11310 11311 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11312 int installFlags, String installerPackageName, String volumeUuid, 11313 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11314 String abiOverride, String[] installGrantPermissions, 11315 String traceMethod, int traceCookie) { 11316 this.origin = origin; 11317 this.move = move; 11318 this.installFlags = installFlags; 11319 this.observer = observer; 11320 this.installerPackageName = installerPackageName; 11321 this.volumeUuid = volumeUuid; 11322 this.manifestDigest = manifestDigest; 11323 this.user = user; 11324 this.instructionSets = instructionSets; 11325 this.abiOverride = abiOverride; 11326 this.installGrantPermissions = installGrantPermissions; 11327 this.traceMethod = traceMethod; 11328 this.traceCookie = traceCookie; 11329 } 11330 11331 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11332 abstract int doPreInstall(int status); 11333 11334 /** 11335 * Rename package into final resting place. All paths on the given 11336 * scanned package should be updated to reflect the rename. 11337 */ 11338 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11339 abstract int doPostInstall(int status, int uid); 11340 11341 /** @see PackageSettingBase#codePathString */ 11342 abstract String getCodePath(); 11343 /** @see PackageSettingBase#resourcePathString */ 11344 abstract String getResourcePath(); 11345 11346 // Need installer lock especially for dex file removal. 11347 abstract void cleanUpResourcesLI(); 11348 abstract boolean doPostDeleteLI(boolean delete); 11349 11350 /** 11351 * Called before the source arguments are copied. This is used mostly 11352 * for MoveParams when it needs to read the source file to put it in the 11353 * destination. 11354 */ 11355 int doPreCopy() { 11356 return PackageManager.INSTALL_SUCCEEDED; 11357 } 11358 11359 /** 11360 * Called after the source arguments are copied. This is used mostly for 11361 * MoveParams when it needs to read the source file to put it in the 11362 * destination. 11363 * 11364 * @return 11365 */ 11366 int doPostCopy(int uid) { 11367 return PackageManager.INSTALL_SUCCEEDED; 11368 } 11369 11370 protected boolean isFwdLocked() { 11371 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11372 } 11373 11374 protected boolean isExternalAsec() { 11375 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11376 } 11377 11378 protected boolean isEphemeral() { 11379 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11380 } 11381 11382 UserHandle getUser() { 11383 return user; 11384 } 11385 } 11386 11387 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11388 if (!allCodePaths.isEmpty()) { 11389 if (instructionSets == null) { 11390 throw new IllegalStateException("instructionSet == null"); 11391 } 11392 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11393 for (String codePath : allCodePaths) { 11394 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11395 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11396 if (retCode < 0) { 11397 Slog.w(TAG, "Couldn't remove dex file for package: " 11398 + " at location " + codePath + ", retcode=" + retCode); 11399 // we don't consider this to be a failure of the core package deletion 11400 } 11401 } 11402 } 11403 } 11404 } 11405 11406 /** 11407 * Logic to handle installation of non-ASEC applications, including copying 11408 * and renaming logic. 11409 */ 11410 class FileInstallArgs extends InstallArgs { 11411 private File codeFile; 11412 private File resourceFile; 11413 11414 // Example topology: 11415 // /data/app/com.example/base.apk 11416 // /data/app/com.example/split_foo.apk 11417 // /data/app/com.example/lib/arm/libfoo.so 11418 // /data/app/com.example/lib/arm64/libfoo.so 11419 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11420 11421 /** New install */ 11422 FileInstallArgs(InstallParams params) { 11423 super(params.origin, params.move, params.observer, params.installFlags, 11424 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11425 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11426 params.grantedRuntimePermissions, 11427 params.traceMethod, params.traceCookie); 11428 if (isFwdLocked()) { 11429 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11430 } 11431 } 11432 11433 /** Existing install */ 11434 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11435 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11436 null, null, null, 0); 11437 this.codeFile = (codePath != null) ? new File(codePath) : null; 11438 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11439 } 11440 11441 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11443 try { 11444 return doCopyApk(imcs, temp); 11445 } finally { 11446 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11447 } 11448 } 11449 11450 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11451 if (origin.staged) { 11452 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11453 codeFile = origin.file; 11454 resourceFile = origin.file; 11455 return PackageManager.INSTALL_SUCCEEDED; 11456 } 11457 11458 try { 11459 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11460 final File tempDir = 11461 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11462 codeFile = tempDir; 11463 resourceFile = tempDir; 11464 } catch (IOException e) { 11465 Slog.w(TAG, "Failed to create copy file: " + e); 11466 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11467 } 11468 11469 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11470 @Override 11471 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11472 if (!FileUtils.isValidExtFilename(name)) { 11473 throw new IllegalArgumentException("Invalid filename: " + name); 11474 } 11475 try { 11476 final File file = new File(codeFile, name); 11477 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11478 O_RDWR | O_CREAT, 0644); 11479 Os.chmod(file.getAbsolutePath(), 0644); 11480 return new ParcelFileDescriptor(fd); 11481 } catch (ErrnoException e) { 11482 throw new RemoteException("Failed to open: " + e.getMessage()); 11483 } 11484 } 11485 }; 11486 11487 int ret = PackageManager.INSTALL_SUCCEEDED; 11488 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11489 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11490 Slog.e(TAG, "Failed to copy package"); 11491 return ret; 11492 } 11493 11494 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11495 NativeLibraryHelper.Handle handle = null; 11496 try { 11497 handle = NativeLibraryHelper.Handle.create(codeFile); 11498 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11499 abiOverride); 11500 } catch (IOException e) { 11501 Slog.e(TAG, "Copying native libraries failed", e); 11502 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11503 } finally { 11504 IoUtils.closeQuietly(handle); 11505 } 11506 11507 return ret; 11508 } 11509 11510 int doPreInstall(int status) { 11511 if (status != PackageManager.INSTALL_SUCCEEDED) { 11512 cleanUp(); 11513 } 11514 return status; 11515 } 11516 11517 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11518 if (status != PackageManager.INSTALL_SUCCEEDED) { 11519 cleanUp(); 11520 return false; 11521 } 11522 11523 final File targetDir = codeFile.getParentFile(); 11524 final File beforeCodeFile = codeFile; 11525 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11526 11527 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11528 try { 11529 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11530 } catch (ErrnoException e) { 11531 Slog.w(TAG, "Failed to rename", e); 11532 return false; 11533 } 11534 11535 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11536 Slog.w(TAG, "Failed to restorecon"); 11537 return false; 11538 } 11539 11540 // Reflect the rename internally 11541 codeFile = afterCodeFile; 11542 resourceFile = afterCodeFile; 11543 11544 // Reflect the rename in scanned details 11545 pkg.codePath = afterCodeFile.getAbsolutePath(); 11546 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11547 pkg.baseCodePath); 11548 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11549 pkg.splitCodePaths); 11550 11551 // Reflect the rename in app info 11552 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11553 pkg.applicationInfo.setCodePath(pkg.codePath); 11554 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11555 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11556 pkg.applicationInfo.setResourcePath(pkg.codePath); 11557 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11558 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11559 11560 return true; 11561 } 11562 11563 int doPostInstall(int status, int uid) { 11564 if (status != PackageManager.INSTALL_SUCCEEDED) { 11565 cleanUp(); 11566 } 11567 return status; 11568 } 11569 11570 @Override 11571 String getCodePath() { 11572 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11573 } 11574 11575 @Override 11576 String getResourcePath() { 11577 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11578 } 11579 11580 private boolean cleanUp() { 11581 if (codeFile == null || !codeFile.exists()) { 11582 return false; 11583 } 11584 11585 if (codeFile.isDirectory()) { 11586 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11587 } else { 11588 codeFile.delete(); 11589 } 11590 11591 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11592 resourceFile.delete(); 11593 } 11594 11595 return true; 11596 } 11597 11598 void cleanUpResourcesLI() { 11599 // Try enumerating all code paths before deleting 11600 List<String> allCodePaths = Collections.EMPTY_LIST; 11601 if (codeFile != null && codeFile.exists()) { 11602 try { 11603 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11604 allCodePaths = pkg.getAllCodePaths(); 11605 } catch (PackageParserException e) { 11606 // Ignored; we tried our best 11607 } 11608 } 11609 11610 cleanUp(); 11611 removeDexFiles(allCodePaths, instructionSets); 11612 } 11613 11614 boolean doPostDeleteLI(boolean delete) { 11615 // XXX err, shouldn't we respect the delete flag? 11616 cleanUpResourcesLI(); 11617 return true; 11618 } 11619 } 11620 11621 private boolean isAsecExternal(String cid) { 11622 final String asecPath = PackageHelper.getSdFilesystem(cid); 11623 return !asecPath.startsWith(mAsecInternalPath); 11624 } 11625 11626 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11627 PackageManagerException { 11628 if (copyRet < 0) { 11629 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11630 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11631 throw new PackageManagerException(copyRet, message); 11632 } 11633 } 11634 } 11635 11636 /** 11637 * Extract the MountService "container ID" from the full code path of an 11638 * .apk. 11639 */ 11640 static String cidFromCodePath(String fullCodePath) { 11641 int eidx = fullCodePath.lastIndexOf("/"); 11642 String subStr1 = fullCodePath.substring(0, eidx); 11643 int sidx = subStr1.lastIndexOf("/"); 11644 return subStr1.substring(sidx+1, eidx); 11645 } 11646 11647 /** 11648 * Logic to handle installation of ASEC applications, including copying and 11649 * renaming logic. 11650 */ 11651 class AsecInstallArgs extends InstallArgs { 11652 static final String RES_FILE_NAME = "pkg.apk"; 11653 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11654 11655 String cid; 11656 String packagePath; 11657 String resourcePath; 11658 11659 /** New install */ 11660 AsecInstallArgs(InstallParams params) { 11661 super(params.origin, params.move, params.observer, params.installFlags, 11662 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11663 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11664 params.grantedRuntimePermissions, 11665 params.traceMethod, params.traceCookie); 11666 } 11667 11668 /** Existing install */ 11669 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11670 boolean isExternal, boolean isForwardLocked) { 11671 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11672 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11673 instructionSets, null, null, null, 0); 11674 // Hackily pretend we're still looking at a full code path 11675 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11676 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11677 } 11678 11679 // Extract cid from fullCodePath 11680 int eidx = fullCodePath.lastIndexOf("/"); 11681 String subStr1 = fullCodePath.substring(0, eidx); 11682 int sidx = subStr1.lastIndexOf("/"); 11683 cid = subStr1.substring(sidx+1, eidx); 11684 setMountPath(subStr1); 11685 } 11686 11687 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11688 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11689 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11690 instructionSets, null, null, null, 0); 11691 this.cid = cid; 11692 setMountPath(PackageHelper.getSdDir(cid)); 11693 } 11694 11695 void createCopyFile() { 11696 cid = mInstallerService.allocateExternalStageCidLegacy(); 11697 } 11698 11699 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11700 if (origin.staged && origin.cid != null) { 11701 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11702 cid = origin.cid; 11703 setMountPath(PackageHelper.getSdDir(cid)); 11704 return PackageManager.INSTALL_SUCCEEDED; 11705 } 11706 11707 if (temp) { 11708 createCopyFile(); 11709 } else { 11710 /* 11711 * Pre-emptively destroy the container since it's destroyed if 11712 * copying fails due to it existing anyway. 11713 */ 11714 PackageHelper.destroySdDir(cid); 11715 } 11716 11717 final String newMountPath = imcs.copyPackageToContainer( 11718 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11719 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11720 11721 if (newMountPath != null) { 11722 setMountPath(newMountPath); 11723 return PackageManager.INSTALL_SUCCEEDED; 11724 } else { 11725 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11726 } 11727 } 11728 11729 @Override 11730 String getCodePath() { 11731 return packagePath; 11732 } 11733 11734 @Override 11735 String getResourcePath() { 11736 return resourcePath; 11737 } 11738 11739 int doPreInstall(int status) { 11740 if (status != PackageManager.INSTALL_SUCCEEDED) { 11741 // Destroy container 11742 PackageHelper.destroySdDir(cid); 11743 } else { 11744 boolean mounted = PackageHelper.isContainerMounted(cid); 11745 if (!mounted) { 11746 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11747 Process.SYSTEM_UID); 11748 if (newMountPath != null) { 11749 setMountPath(newMountPath); 11750 } else { 11751 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11752 } 11753 } 11754 } 11755 return status; 11756 } 11757 11758 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11759 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11760 String newMountPath = null; 11761 if (PackageHelper.isContainerMounted(cid)) { 11762 // Unmount the container 11763 if (!PackageHelper.unMountSdDir(cid)) { 11764 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11765 return false; 11766 } 11767 } 11768 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11769 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11770 " which might be stale. Will try to clean up."); 11771 // Clean up the stale container and proceed to recreate. 11772 if (!PackageHelper.destroySdDir(newCacheId)) { 11773 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11774 return false; 11775 } 11776 // Successfully cleaned up stale container. Try to rename again. 11777 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11778 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11779 + " inspite of cleaning it up."); 11780 return false; 11781 } 11782 } 11783 if (!PackageHelper.isContainerMounted(newCacheId)) { 11784 Slog.w(TAG, "Mounting container " + newCacheId); 11785 newMountPath = PackageHelper.mountSdDir(newCacheId, 11786 getEncryptKey(), Process.SYSTEM_UID); 11787 } else { 11788 newMountPath = PackageHelper.getSdDir(newCacheId); 11789 } 11790 if (newMountPath == null) { 11791 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11792 return false; 11793 } 11794 Log.i(TAG, "Succesfully renamed " + cid + 11795 " to " + newCacheId + 11796 " at new path: " + newMountPath); 11797 cid = newCacheId; 11798 11799 final File beforeCodeFile = new File(packagePath); 11800 setMountPath(newMountPath); 11801 final File afterCodeFile = new File(packagePath); 11802 11803 // Reflect the rename in scanned details 11804 pkg.codePath = afterCodeFile.getAbsolutePath(); 11805 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11806 pkg.baseCodePath); 11807 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11808 pkg.splitCodePaths); 11809 11810 // Reflect the rename in app info 11811 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11812 pkg.applicationInfo.setCodePath(pkg.codePath); 11813 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11814 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11815 pkg.applicationInfo.setResourcePath(pkg.codePath); 11816 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11817 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11818 11819 return true; 11820 } 11821 11822 private void setMountPath(String mountPath) { 11823 final File mountFile = new File(mountPath); 11824 11825 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11826 if (monolithicFile.exists()) { 11827 packagePath = monolithicFile.getAbsolutePath(); 11828 if (isFwdLocked()) { 11829 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11830 } else { 11831 resourcePath = packagePath; 11832 } 11833 } else { 11834 packagePath = mountFile.getAbsolutePath(); 11835 resourcePath = packagePath; 11836 } 11837 } 11838 11839 int doPostInstall(int status, int uid) { 11840 if (status != PackageManager.INSTALL_SUCCEEDED) { 11841 cleanUp(); 11842 } else { 11843 final int groupOwner; 11844 final String protectedFile; 11845 if (isFwdLocked()) { 11846 groupOwner = UserHandle.getSharedAppGid(uid); 11847 protectedFile = RES_FILE_NAME; 11848 } else { 11849 groupOwner = -1; 11850 protectedFile = null; 11851 } 11852 11853 if (uid < Process.FIRST_APPLICATION_UID 11854 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11855 Slog.e(TAG, "Failed to finalize " + cid); 11856 PackageHelper.destroySdDir(cid); 11857 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11858 } 11859 11860 boolean mounted = PackageHelper.isContainerMounted(cid); 11861 if (!mounted) { 11862 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11863 } 11864 } 11865 return status; 11866 } 11867 11868 private void cleanUp() { 11869 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11870 11871 // Destroy secure container 11872 PackageHelper.destroySdDir(cid); 11873 } 11874 11875 private List<String> getAllCodePaths() { 11876 final File codeFile = new File(getCodePath()); 11877 if (codeFile != null && codeFile.exists()) { 11878 try { 11879 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11880 return pkg.getAllCodePaths(); 11881 } catch (PackageParserException e) { 11882 // Ignored; we tried our best 11883 } 11884 } 11885 return Collections.EMPTY_LIST; 11886 } 11887 11888 void cleanUpResourcesLI() { 11889 // Enumerate all code paths before deleting 11890 cleanUpResourcesLI(getAllCodePaths()); 11891 } 11892 11893 private void cleanUpResourcesLI(List<String> allCodePaths) { 11894 cleanUp(); 11895 removeDexFiles(allCodePaths, instructionSets); 11896 } 11897 11898 String getPackageName() { 11899 return getAsecPackageName(cid); 11900 } 11901 11902 boolean doPostDeleteLI(boolean delete) { 11903 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11904 final List<String> allCodePaths = getAllCodePaths(); 11905 boolean mounted = PackageHelper.isContainerMounted(cid); 11906 if (mounted) { 11907 // Unmount first 11908 if (PackageHelper.unMountSdDir(cid)) { 11909 mounted = false; 11910 } 11911 } 11912 if (!mounted && delete) { 11913 cleanUpResourcesLI(allCodePaths); 11914 } 11915 return !mounted; 11916 } 11917 11918 @Override 11919 int doPreCopy() { 11920 if (isFwdLocked()) { 11921 if (!PackageHelper.fixSdPermissions(cid, 11922 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11923 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11924 } 11925 } 11926 11927 return PackageManager.INSTALL_SUCCEEDED; 11928 } 11929 11930 @Override 11931 int doPostCopy(int uid) { 11932 if (isFwdLocked()) { 11933 if (uid < Process.FIRST_APPLICATION_UID 11934 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11935 RES_FILE_NAME)) { 11936 Slog.e(TAG, "Failed to finalize " + cid); 11937 PackageHelper.destroySdDir(cid); 11938 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11939 } 11940 } 11941 11942 return PackageManager.INSTALL_SUCCEEDED; 11943 } 11944 } 11945 11946 /** 11947 * Logic to handle movement of existing installed applications. 11948 */ 11949 class MoveInstallArgs extends InstallArgs { 11950 private File codeFile; 11951 private File resourceFile; 11952 11953 /** New install */ 11954 MoveInstallArgs(InstallParams params) { 11955 super(params.origin, params.move, params.observer, params.installFlags, 11956 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11957 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11958 params.grantedRuntimePermissions, 11959 params.traceMethod, params.traceCookie); 11960 } 11961 11962 int copyApk(IMediaContainerService imcs, boolean temp) { 11963 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11964 + move.fromUuid + " to " + move.toUuid); 11965 synchronized (mInstaller) { 11966 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11967 move.dataAppName, move.appId, move.seinfo) != 0) { 11968 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11969 } 11970 } 11971 11972 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11973 resourceFile = codeFile; 11974 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11975 11976 return PackageManager.INSTALL_SUCCEEDED; 11977 } 11978 11979 int doPreInstall(int status) { 11980 if (status != PackageManager.INSTALL_SUCCEEDED) { 11981 cleanUp(move.toUuid); 11982 } 11983 return status; 11984 } 11985 11986 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11987 if (status != PackageManager.INSTALL_SUCCEEDED) { 11988 cleanUp(move.toUuid); 11989 return false; 11990 } 11991 11992 // Reflect the move in app info 11993 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11994 pkg.applicationInfo.setCodePath(pkg.codePath); 11995 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11996 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11997 pkg.applicationInfo.setResourcePath(pkg.codePath); 11998 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11999 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12000 12001 return true; 12002 } 12003 12004 int doPostInstall(int status, int uid) { 12005 if (status == PackageManager.INSTALL_SUCCEEDED) { 12006 cleanUp(move.fromUuid); 12007 } else { 12008 cleanUp(move.toUuid); 12009 } 12010 return status; 12011 } 12012 12013 @Override 12014 String getCodePath() { 12015 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12016 } 12017 12018 @Override 12019 String getResourcePath() { 12020 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12021 } 12022 12023 private boolean cleanUp(String volumeUuid) { 12024 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12025 move.dataAppName); 12026 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12027 synchronized (mInstallLock) { 12028 // Clean up both app data and code 12029 removeDataDirsLI(volumeUuid, move.packageName); 12030 if (codeFile.isDirectory()) { 12031 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12032 } else { 12033 codeFile.delete(); 12034 } 12035 } 12036 return true; 12037 } 12038 12039 void cleanUpResourcesLI() { 12040 throw new UnsupportedOperationException(); 12041 } 12042 12043 boolean doPostDeleteLI(boolean delete) { 12044 throw new UnsupportedOperationException(); 12045 } 12046 } 12047 12048 static String getAsecPackageName(String packageCid) { 12049 int idx = packageCid.lastIndexOf("-"); 12050 if (idx == -1) { 12051 return packageCid; 12052 } 12053 return packageCid.substring(0, idx); 12054 } 12055 12056 // Utility method used to create code paths based on package name and available index. 12057 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12058 String idxStr = ""; 12059 int idx = 1; 12060 // Fall back to default value of idx=1 if prefix is not 12061 // part of oldCodePath 12062 if (oldCodePath != null) { 12063 String subStr = oldCodePath; 12064 // Drop the suffix right away 12065 if (suffix != null && subStr.endsWith(suffix)) { 12066 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12067 } 12068 // If oldCodePath already contains prefix find out the 12069 // ending index to either increment or decrement. 12070 int sidx = subStr.lastIndexOf(prefix); 12071 if (sidx != -1) { 12072 subStr = subStr.substring(sidx + prefix.length()); 12073 if (subStr != null) { 12074 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12075 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12076 } 12077 try { 12078 idx = Integer.parseInt(subStr); 12079 if (idx <= 1) { 12080 idx++; 12081 } else { 12082 idx--; 12083 } 12084 } catch(NumberFormatException e) { 12085 } 12086 } 12087 } 12088 } 12089 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12090 return prefix + idxStr; 12091 } 12092 12093 private File getNextCodePath(File targetDir, String packageName) { 12094 int suffix = 1; 12095 File result; 12096 do { 12097 result = new File(targetDir, packageName + "-" + suffix); 12098 suffix++; 12099 } while (result.exists()); 12100 return result; 12101 } 12102 12103 // Utility method that returns the relative package path with respect 12104 // to the installation directory. Like say for /data/data/com.test-1.apk 12105 // string com.test-1 is returned. 12106 static String deriveCodePathName(String codePath) { 12107 if (codePath == null) { 12108 return null; 12109 } 12110 final File codeFile = new File(codePath); 12111 final String name = codeFile.getName(); 12112 if (codeFile.isDirectory()) { 12113 return name; 12114 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12115 final int lastDot = name.lastIndexOf('.'); 12116 return name.substring(0, lastDot); 12117 } else { 12118 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12119 return null; 12120 } 12121 } 12122 12123 class PackageInstalledInfo { 12124 String name; 12125 int uid; 12126 // The set of users that originally had this package installed. 12127 int[] origUsers; 12128 // The set of users that now have this package installed. 12129 int[] newUsers; 12130 PackageParser.Package pkg; 12131 int returnCode; 12132 String returnMsg; 12133 PackageRemovedInfo removedInfo; 12134 12135 public void setError(int code, String msg) { 12136 returnCode = code; 12137 returnMsg = msg; 12138 Slog.w(TAG, msg); 12139 } 12140 12141 public void setError(String msg, PackageParserException e) { 12142 returnCode = e.error; 12143 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12144 Slog.w(TAG, msg, e); 12145 } 12146 12147 public void setError(String msg, PackageManagerException e) { 12148 returnCode = e.error; 12149 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12150 Slog.w(TAG, msg, e); 12151 } 12152 12153 // In some error cases we want to convey more info back to the observer 12154 String origPackage; 12155 String origPermission; 12156 } 12157 12158 /* 12159 * Install a non-existing package. 12160 */ 12161 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12162 UserHandle user, String installerPackageName, String volumeUuid, 12163 PackageInstalledInfo res) { 12164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12165 12166 // Remember this for later, in case we need to rollback this install 12167 String pkgName = pkg.packageName; 12168 12169 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12170 // TODO: b/23350563 12171 final boolean dataDirExists = Environment 12172 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12173 12174 synchronized(mPackages) { 12175 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12176 // A package with the same name is already installed, though 12177 // it has been renamed to an older name. The package we 12178 // are trying to install should be installed as an update to 12179 // the existing one, but that has not been requested, so bail. 12180 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12181 + " without first uninstalling package running as " 12182 + mSettings.mRenamedPackages.get(pkgName)); 12183 return; 12184 } 12185 if (mPackages.containsKey(pkgName)) { 12186 // Don't allow installation over an existing package with the same name. 12187 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12188 + " without first uninstalling."); 12189 return; 12190 } 12191 } 12192 12193 try { 12194 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12195 System.currentTimeMillis(), user); 12196 12197 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12198 // delete the partially installed application. the data directory will have to be 12199 // restored if it was already existing 12200 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12201 // remove package from internal structures. Note that we want deletePackageX to 12202 // delete the package data and cache directories that it created in 12203 // scanPackageLocked, unless those directories existed before we even tried to 12204 // install. 12205 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12206 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12207 res.removedInfo, true); 12208 } 12209 12210 } catch (PackageManagerException e) { 12211 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12212 } 12213 12214 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12215 } 12216 12217 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12218 // Can't rotate keys during boot or if sharedUser. 12219 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12220 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12221 return false; 12222 } 12223 // app is using upgradeKeySets; make sure all are valid 12224 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12225 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12226 for (int i = 0; i < upgradeKeySets.length; i++) { 12227 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12228 Slog.wtf(TAG, "Package " 12229 + (oldPs.name != null ? oldPs.name : "<null>") 12230 + " contains upgrade-key-set reference to unknown key-set: " 12231 + upgradeKeySets[i] 12232 + " reverting to signatures check."); 12233 return false; 12234 } 12235 } 12236 return true; 12237 } 12238 12239 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12240 // Upgrade keysets are being used. Determine if new package has a superset of the 12241 // required keys. 12242 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12243 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12244 for (int i = 0; i < upgradeKeySets.length; i++) { 12245 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12246 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12247 return true; 12248 } 12249 } 12250 return false; 12251 } 12252 12253 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12254 UserHandle user, String installerPackageName, String volumeUuid, 12255 PackageInstalledInfo res) { 12256 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12257 12258 final PackageParser.Package oldPackage; 12259 final String pkgName = pkg.packageName; 12260 final int[] allUsers; 12261 final boolean[] perUserInstalled; 12262 12263 // First find the old package info and check signatures 12264 synchronized(mPackages) { 12265 oldPackage = mPackages.get(pkgName); 12266 final boolean oldIsEphemeral 12267 = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0); 12268 if (isEphemeral && !oldIsEphemeral) { 12269 // can't downgrade from full to ephemeral 12270 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12271 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12272 return; 12273 } 12274 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12275 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12276 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12277 if(!checkUpgradeKeySetLP(ps, pkg)) { 12278 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12279 "New package not signed by keys specified by upgrade-keysets: " 12280 + pkgName); 12281 return; 12282 } 12283 } else { 12284 // default to original signature matching 12285 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12286 != PackageManager.SIGNATURE_MATCH) { 12287 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12288 "New package has a different signature: " + pkgName); 12289 return; 12290 } 12291 } 12292 12293 // In case of rollback, remember per-user/profile install state 12294 allUsers = sUserManager.getUserIds(); 12295 perUserInstalled = new boolean[allUsers.length]; 12296 for (int i = 0; i < allUsers.length; i++) { 12297 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12298 } 12299 } 12300 12301 boolean sysPkg = (isSystemApp(oldPackage)); 12302 if (sysPkg) { 12303 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12304 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12305 } else { 12306 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12307 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12308 } 12309 } 12310 12311 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12312 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12313 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12314 String volumeUuid, PackageInstalledInfo res) { 12315 String pkgName = deletedPackage.packageName; 12316 boolean deletedPkg = true; 12317 boolean updatedSettings = false; 12318 12319 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12320 + deletedPackage); 12321 long origUpdateTime; 12322 if (pkg.mExtras != null) { 12323 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12324 } else { 12325 origUpdateTime = 0; 12326 } 12327 12328 // First delete the existing package while retaining the data directory 12329 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12330 res.removedInfo, true)) { 12331 // If the existing package wasn't successfully deleted 12332 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12333 deletedPkg = false; 12334 } else { 12335 // Successfully deleted the old package; proceed with replace. 12336 12337 // If deleted package lived in a container, give users a chance to 12338 // relinquish resources before killing. 12339 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12340 if (DEBUG_INSTALL) { 12341 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12342 } 12343 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12344 final ArrayList<String> pkgList = new ArrayList<String>(1); 12345 pkgList.add(deletedPackage.applicationInfo.packageName); 12346 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12347 } 12348 12349 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12350 try { 12351 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12352 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12353 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12354 perUserInstalled, res, user); 12355 updatedSettings = true; 12356 } catch (PackageManagerException e) { 12357 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12358 } 12359 } 12360 12361 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12362 // remove package from internal structures. Note that we want deletePackageX to 12363 // delete the package data and cache directories that it created in 12364 // scanPackageLocked, unless those directories existed before we even tried to 12365 // install. 12366 if(updatedSettings) { 12367 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12368 deletePackageLI( 12369 pkgName, null, true, allUsers, perUserInstalled, 12370 PackageManager.DELETE_KEEP_DATA, 12371 res.removedInfo, true); 12372 } 12373 // Since we failed to install the new package we need to restore the old 12374 // package that we deleted. 12375 if (deletedPkg) { 12376 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12377 File restoreFile = new File(deletedPackage.codePath); 12378 // Parse old package 12379 boolean oldExternal = isExternal(deletedPackage); 12380 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12381 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12382 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12383 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12384 try { 12385 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12386 null); 12387 } catch (PackageManagerException e) { 12388 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12389 + e.getMessage()); 12390 return; 12391 } 12392 // Restore of old package succeeded. Update permissions. 12393 // writer 12394 synchronized (mPackages) { 12395 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12396 UPDATE_PERMISSIONS_ALL); 12397 // can downgrade to reader 12398 mSettings.writeLPr(); 12399 } 12400 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12401 } 12402 } 12403 } 12404 12405 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12406 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12407 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12408 String volumeUuid, PackageInstalledInfo res) { 12409 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12410 + ", old=" + deletedPackage); 12411 boolean disabledSystem = false; 12412 boolean updatedSettings = false; 12413 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12414 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12415 != 0) { 12416 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12417 } 12418 String packageName = deletedPackage.packageName; 12419 if (packageName == null) { 12420 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12421 "Attempt to delete null packageName."); 12422 return; 12423 } 12424 PackageParser.Package oldPkg; 12425 PackageSetting oldPkgSetting; 12426 // reader 12427 synchronized (mPackages) { 12428 oldPkg = mPackages.get(packageName); 12429 oldPkgSetting = mSettings.mPackages.get(packageName); 12430 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12431 (oldPkgSetting == null)) { 12432 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12433 "Couldn't find package:" + packageName + " information"); 12434 return; 12435 } 12436 } 12437 12438 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12439 12440 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12441 res.removedInfo.removedPackage = packageName; 12442 // Remove existing system package 12443 removePackageLI(oldPkgSetting, true); 12444 // writer 12445 synchronized (mPackages) { 12446 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12447 if (!disabledSystem && deletedPackage != null) { 12448 // We didn't need to disable the .apk as a current system package, 12449 // which means we are replacing another update that is already 12450 // installed. We need to make sure to delete the older one's .apk. 12451 res.removedInfo.args = createInstallArgsForExisting(0, 12452 deletedPackage.applicationInfo.getCodePath(), 12453 deletedPackage.applicationInfo.getResourcePath(), 12454 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12455 } else { 12456 res.removedInfo.args = null; 12457 } 12458 } 12459 12460 // Successfully disabled the old package. Now proceed with re-installation 12461 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12462 12463 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12464 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12465 12466 PackageParser.Package newPackage = null; 12467 try { 12468 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12469 if (newPackage.mExtras != null) { 12470 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12471 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12472 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12473 12474 // is the update attempting to change shared user? that isn't going to work... 12475 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12476 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12477 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12478 + " to " + newPkgSetting.sharedUser); 12479 updatedSettings = true; 12480 } 12481 } 12482 12483 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12484 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12485 perUserInstalled, res, user); 12486 updatedSettings = true; 12487 } 12488 12489 } catch (PackageManagerException e) { 12490 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12491 } 12492 12493 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12494 // Re installation failed. Restore old information 12495 // Remove new pkg information 12496 if (newPackage != null) { 12497 removeInstalledPackageLI(newPackage, true); 12498 } 12499 // Add back the old system package 12500 try { 12501 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12502 } catch (PackageManagerException e) { 12503 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12504 } 12505 // Restore the old system information in Settings 12506 synchronized (mPackages) { 12507 if (disabledSystem) { 12508 mSettings.enableSystemPackageLPw(packageName); 12509 } 12510 if (updatedSettings) { 12511 mSettings.setInstallerPackageName(packageName, 12512 oldPkgSetting.installerPackageName); 12513 } 12514 mSettings.writeLPr(); 12515 } 12516 } 12517 } 12518 12519 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12520 // Collect all used permissions in the UID 12521 ArraySet<String> usedPermissions = new ArraySet<>(); 12522 final int packageCount = su.packages.size(); 12523 for (int i = 0; i < packageCount; i++) { 12524 PackageSetting ps = su.packages.valueAt(i); 12525 if (ps.pkg == null) { 12526 continue; 12527 } 12528 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12529 for (int j = 0; j < requestedPermCount; j++) { 12530 String permission = ps.pkg.requestedPermissions.get(j); 12531 BasePermission bp = mSettings.mPermissions.get(permission); 12532 if (bp != null) { 12533 usedPermissions.add(permission); 12534 } 12535 } 12536 } 12537 12538 PermissionsState permissionsState = su.getPermissionsState(); 12539 // Prune install permissions 12540 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12541 final int installPermCount = installPermStates.size(); 12542 for (int i = installPermCount - 1; i >= 0; i--) { 12543 PermissionState permissionState = installPermStates.get(i); 12544 if (!usedPermissions.contains(permissionState.getName())) { 12545 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12546 if (bp != null) { 12547 permissionsState.revokeInstallPermission(bp); 12548 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12549 PackageManager.MASK_PERMISSION_FLAGS, 0); 12550 } 12551 } 12552 } 12553 12554 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12555 12556 // Prune runtime permissions 12557 for (int userId : allUserIds) { 12558 List<PermissionState> runtimePermStates = permissionsState 12559 .getRuntimePermissionStates(userId); 12560 final int runtimePermCount = runtimePermStates.size(); 12561 for (int i = runtimePermCount - 1; i >= 0; i--) { 12562 PermissionState permissionState = runtimePermStates.get(i); 12563 if (!usedPermissions.contains(permissionState.getName())) { 12564 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12565 if (bp != null) { 12566 permissionsState.revokeRuntimePermission(bp, userId); 12567 permissionsState.updatePermissionFlags(bp, userId, 12568 PackageManager.MASK_PERMISSION_FLAGS, 0); 12569 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12570 runtimePermissionChangedUserIds, userId); 12571 } 12572 } 12573 } 12574 } 12575 12576 return runtimePermissionChangedUserIds; 12577 } 12578 12579 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12580 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12581 UserHandle user) { 12582 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12583 12584 String pkgName = newPackage.packageName; 12585 synchronized (mPackages) { 12586 //write settings. the installStatus will be incomplete at this stage. 12587 //note that the new package setting would have already been 12588 //added to mPackages. It hasn't been persisted yet. 12589 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12591 mSettings.writeLPr(); 12592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12593 } 12594 12595 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12596 synchronized (mPackages) { 12597 updatePermissionsLPw(newPackage.packageName, newPackage, 12598 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12599 ? UPDATE_PERMISSIONS_ALL : 0)); 12600 // For system-bundled packages, we assume that installing an upgraded version 12601 // of the package implies that the user actually wants to run that new code, 12602 // so we enable the package. 12603 PackageSetting ps = mSettings.mPackages.get(pkgName); 12604 if (ps != null) { 12605 if (isSystemApp(newPackage)) { 12606 // NB: implicit assumption that system package upgrades apply to all users 12607 if (DEBUG_INSTALL) { 12608 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12609 } 12610 if (res.origUsers != null) { 12611 for (int userHandle : res.origUsers) { 12612 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12613 userHandle, installerPackageName); 12614 } 12615 } 12616 // Also convey the prior install/uninstall state 12617 if (allUsers != null && perUserInstalled != null) { 12618 for (int i = 0; i < allUsers.length; i++) { 12619 if (DEBUG_INSTALL) { 12620 Slog.d(TAG, " user " + allUsers[i] 12621 + " => " + perUserInstalled[i]); 12622 } 12623 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12624 } 12625 // these install state changes will be persisted in the 12626 // upcoming call to mSettings.writeLPr(). 12627 } 12628 } 12629 // It's implied that when a user requests installation, they want the app to be 12630 // installed and enabled. 12631 int userId = user.getIdentifier(); 12632 if (userId != UserHandle.USER_ALL) { 12633 ps.setInstalled(true, userId); 12634 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12635 } 12636 } 12637 res.name = pkgName; 12638 res.uid = newPackage.applicationInfo.uid; 12639 res.pkg = newPackage; 12640 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12641 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12642 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12643 //to update install status 12644 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12645 mSettings.writeLPr(); 12646 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12647 } 12648 12649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12650 } 12651 12652 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12653 try { 12654 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12655 installPackageLI(args, res); 12656 } finally { 12657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12658 } 12659 } 12660 12661 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12662 final int installFlags = args.installFlags; 12663 final String installerPackageName = args.installerPackageName; 12664 final String volumeUuid = args.volumeUuid; 12665 final File tmpPackageFile = new File(args.getCodePath()); 12666 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12667 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12668 || (args.volumeUuid != null)); 12669 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12670 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12671 boolean replace = false; 12672 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12673 if (args.move != null) { 12674 // moving a complete application; perfom an initial scan on the new install location 12675 scanFlags |= SCAN_INITIAL; 12676 } 12677 // Result object to be returned 12678 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12679 12680 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12681 12682 // Sanity check 12683 if (ephemeral && (forwardLocked || onExternal)) { 12684 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12685 + " external=" + onExternal); 12686 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12687 return; 12688 } 12689 12690 // Retrieve PackageSettings and parse package 12691 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12692 | PackageParser.PARSE_ENFORCE_CODE 12693 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12694 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12695 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0) 12696 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12697 PackageParser pp = new PackageParser(); 12698 pp.setSeparateProcesses(mSeparateProcesses); 12699 pp.setDisplayMetrics(mMetrics); 12700 12701 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12702 final PackageParser.Package pkg; 12703 try { 12704 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12705 } catch (PackageParserException e) { 12706 res.setError("Failed parse during installPackageLI", e); 12707 return; 12708 } finally { 12709 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12710 } 12711 12712 // Mark that we have an install time CPU ABI override. 12713 pkg.cpuAbiOverride = args.abiOverride; 12714 12715 String pkgName = res.name = pkg.packageName; 12716 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12717 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12718 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12719 return; 12720 } 12721 } 12722 12723 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12724 try { 12725 pp.collectCertificates(pkg, parseFlags); 12726 } catch (PackageParserException e) { 12727 res.setError("Failed collect during installPackageLI", e); 12728 return; 12729 } finally { 12730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12731 } 12732 12733 /* If the installer passed in a manifest digest, compare it now. */ 12734 if (args.manifestDigest != null) { 12735 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12736 try { 12737 pp.collectManifestDigest(pkg); 12738 } catch (PackageParserException e) { 12739 res.setError("Failed collect during installPackageLI", e); 12740 return; 12741 } finally { 12742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12743 } 12744 12745 if (DEBUG_INSTALL) { 12746 final String parsedManifest = pkg.manifestDigest == null ? "null" 12747 : pkg.manifestDigest.toString(); 12748 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12749 + parsedManifest); 12750 } 12751 12752 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12753 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12754 return; 12755 } 12756 } else if (DEBUG_INSTALL) { 12757 final String parsedManifest = pkg.manifestDigest == null 12758 ? "null" : pkg.manifestDigest.toString(); 12759 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12760 } 12761 12762 // Get rid of all references to package scan path via parser. 12763 pp = null; 12764 String oldCodePath = null; 12765 boolean systemApp = false; 12766 synchronized (mPackages) { 12767 // Check if installing already existing package 12768 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12769 String oldName = mSettings.mRenamedPackages.get(pkgName); 12770 if (pkg.mOriginalPackages != null 12771 && pkg.mOriginalPackages.contains(oldName) 12772 && mPackages.containsKey(oldName)) { 12773 // This package is derived from an original package, 12774 // and this device has been updating from that original 12775 // name. We must continue using the original name, so 12776 // rename the new package here. 12777 pkg.setPackageName(oldName); 12778 pkgName = pkg.packageName; 12779 replace = true; 12780 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12781 + oldName + " pkgName=" + pkgName); 12782 } else if (mPackages.containsKey(pkgName)) { 12783 // This package, under its official name, already exists 12784 // on the device; we should replace it. 12785 replace = true; 12786 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12787 } 12788 12789 // Prevent apps opting out from runtime permissions 12790 if (replace) { 12791 PackageParser.Package oldPackage = mPackages.get(pkgName); 12792 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12793 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12794 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12795 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12796 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12797 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12798 + " doesn't support runtime permissions but the old" 12799 + " target SDK " + oldTargetSdk + " does."); 12800 return; 12801 } 12802 } 12803 } 12804 12805 PackageSetting ps = mSettings.mPackages.get(pkgName); 12806 if (ps != null) { 12807 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12808 12809 // Quick sanity check that we're signed correctly if updating; 12810 // we'll check this again later when scanning, but we want to 12811 // bail early here before tripping over redefined permissions. 12812 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12813 if (!checkUpgradeKeySetLP(ps, pkg)) { 12814 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12815 + pkg.packageName + " upgrade keys do not match the " 12816 + "previously installed version"); 12817 return; 12818 } 12819 } else { 12820 try { 12821 verifySignaturesLP(ps, pkg); 12822 } catch (PackageManagerException e) { 12823 res.setError(e.error, e.getMessage()); 12824 return; 12825 } 12826 } 12827 12828 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12829 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12830 systemApp = (ps.pkg.applicationInfo.flags & 12831 ApplicationInfo.FLAG_SYSTEM) != 0; 12832 } 12833 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12834 } 12835 12836 // Check whether the newly-scanned package wants to define an already-defined perm 12837 int N = pkg.permissions.size(); 12838 for (int i = N-1; i >= 0; i--) { 12839 PackageParser.Permission perm = pkg.permissions.get(i); 12840 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12841 if (bp != null) { 12842 // If the defining package is signed with our cert, it's okay. This 12843 // also includes the "updating the same package" case, of course. 12844 // "updating same package" could also involve key-rotation. 12845 final boolean sigsOk; 12846 if (bp.sourcePackage.equals(pkg.packageName) 12847 && (bp.packageSetting instanceof PackageSetting) 12848 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12849 scanFlags))) { 12850 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12851 } else { 12852 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12853 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12854 } 12855 if (!sigsOk) { 12856 // If the owning package is the system itself, we log but allow 12857 // install to proceed; we fail the install on all other permission 12858 // redefinitions. 12859 if (!bp.sourcePackage.equals("android")) { 12860 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12861 + pkg.packageName + " attempting to redeclare permission " 12862 + perm.info.name + " already owned by " + bp.sourcePackage); 12863 res.origPermission = perm.info.name; 12864 res.origPackage = bp.sourcePackage; 12865 return; 12866 } else { 12867 Slog.w(TAG, "Package " + pkg.packageName 12868 + " attempting to redeclare system permission " 12869 + perm.info.name + "; ignoring new declaration"); 12870 pkg.permissions.remove(i); 12871 } 12872 } 12873 } 12874 } 12875 12876 } 12877 12878 if (systemApp) { 12879 if (onExternal) { 12880 // Abort update; system app can't be replaced with app on sdcard 12881 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12882 "Cannot install updates to system apps on sdcard"); 12883 return; 12884 } else if (ephemeral) { 12885 // Abort update; system app can't be replaced with an ephemeral app 12886 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12887 "Cannot update a system app with an ephemeral app"); 12888 return; 12889 } 12890 } 12891 12892 if (args.move != null) { 12893 // We did an in-place move, so dex is ready to roll 12894 scanFlags |= SCAN_NO_DEX; 12895 scanFlags |= SCAN_MOVE; 12896 12897 synchronized (mPackages) { 12898 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12899 if (ps == null) { 12900 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12901 "Missing settings for moved package " + pkgName); 12902 } 12903 12904 // We moved the entire application as-is, so bring over the 12905 // previously derived ABI information. 12906 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12907 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12908 } 12909 12910 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12911 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12912 scanFlags |= SCAN_NO_DEX; 12913 12914 try { 12915 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12916 true /* extract libs */); 12917 } catch (PackageManagerException pme) { 12918 Slog.e(TAG, "Error deriving application ABI", pme); 12919 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12920 return; 12921 } 12922 } 12923 12924 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12925 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12926 return; 12927 } 12928 12929 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12930 12931 if (replace) { 12932 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12933 installerPackageName, volumeUuid, res); 12934 } else { 12935 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12936 args.user, installerPackageName, volumeUuid, res); 12937 } 12938 synchronized (mPackages) { 12939 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12940 if (ps != null) { 12941 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12942 } 12943 } 12944 } 12945 12946 private void startIntentFilterVerifications(int userId, boolean replacing, 12947 PackageParser.Package pkg) { 12948 if (mIntentFilterVerifierComponent == null) { 12949 Slog.w(TAG, "No IntentFilter verification will not be done as " 12950 + "there is no IntentFilterVerifier available!"); 12951 return; 12952 } 12953 12954 final int verifierUid = getPackageUid( 12955 mIntentFilterVerifierComponent.getPackageName(), 12956 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12957 12958 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12959 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12960 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12961 mHandler.sendMessage(msg); 12962 } 12963 12964 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12965 PackageParser.Package pkg) { 12966 int size = pkg.activities.size(); 12967 if (size == 0) { 12968 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12969 "No activity, so no need to verify any IntentFilter!"); 12970 return; 12971 } 12972 12973 final boolean hasDomainURLs = hasDomainURLs(pkg); 12974 if (!hasDomainURLs) { 12975 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12976 "No domain URLs, so no need to verify any IntentFilter!"); 12977 return; 12978 } 12979 12980 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12981 + " if any IntentFilter from the " + size 12982 + " Activities needs verification ..."); 12983 12984 int count = 0; 12985 final String packageName = pkg.packageName; 12986 12987 synchronized (mPackages) { 12988 // If this is a new install and we see that we've already run verification for this 12989 // package, we have nothing to do: it means the state was restored from backup. 12990 if (!replacing) { 12991 IntentFilterVerificationInfo ivi = 12992 mSettings.getIntentFilterVerificationLPr(packageName); 12993 if (ivi != null) { 12994 if (DEBUG_DOMAIN_VERIFICATION) { 12995 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12996 + ivi.getStatusString()); 12997 } 12998 return; 12999 } 13000 } 13001 13002 // If any filters need to be verified, then all need to be. 13003 boolean needToVerify = false; 13004 for (PackageParser.Activity a : pkg.activities) { 13005 for (ActivityIntentInfo filter : a.intents) { 13006 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13007 if (DEBUG_DOMAIN_VERIFICATION) { 13008 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13009 } 13010 needToVerify = true; 13011 break; 13012 } 13013 } 13014 } 13015 13016 if (needToVerify) { 13017 final int verificationId = mIntentFilterVerificationToken++; 13018 for (PackageParser.Activity a : pkg.activities) { 13019 for (ActivityIntentInfo filter : a.intents) { 13020 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13021 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13022 "Verification needed for IntentFilter:" + filter.toString()); 13023 mIntentFilterVerifier.addOneIntentFilterVerification( 13024 verifierUid, userId, verificationId, filter, packageName); 13025 count++; 13026 } 13027 } 13028 } 13029 } 13030 } 13031 13032 if (count > 0) { 13033 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13034 + " IntentFilter verification" + (count > 1 ? "s" : "") 13035 + " for userId:" + userId); 13036 mIntentFilterVerifier.startVerifications(userId); 13037 } else { 13038 if (DEBUG_DOMAIN_VERIFICATION) { 13039 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13040 } 13041 } 13042 } 13043 13044 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13045 final ComponentName cn = filter.activity.getComponentName(); 13046 final String packageName = cn.getPackageName(); 13047 13048 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13049 packageName); 13050 if (ivi == null) { 13051 return true; 13052 } 13053 int status = ivi.getStatus(); 13054 switch (status) { 13055 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13056 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13057 return true; 13058 13059 default: 13060 // Nothing to do 13061 return false; 13062 } 13063 } 13064 13065 private static boolean isMultiArch(PackageSetting ps) { 13066 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13067 } 13068 13069 private static boolean isMultiArch(ApplicationInfo info) { 13070 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13071 } 13072 13073 private static boolean isExternal(PackageParser.Package pkg) { 13074 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13075 } 13076 13077 private static boolean isExternal(PackageSetting ps) { 13078 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13079 } 13080 13081 private static boolean isExternal(ApplicationInfo info) { 13082 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13083 } 13084 13085 private static boolean isEphemeral(PackageParser.Package pkg) { 13086 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13087 } 13088 13089 private static boolean isEphemeral(PackageSetting ps) { 13090 return (ps.pkgFlags & ApplicationInfo.FLAG_EPHEMERAL) != 0; 13091 } 13092 13093 private static boolean isSystemApp(PackageParser.Package pkg) { 13094 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13095 } 13096 13097 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13098 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13099 } 13100 13101 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13102 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13103 } 13104 13105 private static boolean isSystemApp(PackageSetting ps) { 13106 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13107 } 13108 13109 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13110 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13111 } 13112 13113 private int packageFlagsToInstallFlags(PackageSetting ps) { 13114 int installFlags = 0; 13115 if (isEphemeral(ps)) { 13116 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13117 } 13118 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13119 // This existing package was an external ASEC install when we have 13120 // the external flag without a UUID 13121 installFlags |= PackageManager.INSTALL_EXTERNAL; 13122 } 13123 if (ps.isForwardLocked()) { 13124 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13125 } 13126 return installFlags; 13127 } 13128 13129 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13130 if (isExternal(pkg)) { 13131 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13132 return StorageManager.UUID_PRIMARY_PHYSICAL; 13133 } else { 13134 return pkg.volumeUuid; 13135 } 13136 } else { 13137 return StorageManager.UUID_PRIVATE_INTERNAL; 13138 } 13139 } 13140 13141 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13142 if (isExternal(pkg)) { 13143 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13144 return mSettings.getExternalVersion(); 13145 } else { 13146 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13147 } 13148 } else { 13149 return mSettings.getInternalVersion(); 13150 } 13151 } 13152 13153 private void deleteTempPackageFiles() { 13154 final FilenameFilter filter = new FilenameFilter() { 13155 public boolean accept(File dir, String name) { 13156 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13157 } 13158 }; 13159 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13160 file.delete(); 13161 } 13162 } 13163 13164 @Override 13165 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13166 int flags) { 13167 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13168 flags); 13169 } 13170 13171 @Override 13172 public void deletePackage(final String packageName, 13173 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13174 mContext.enforceCallingOrSelfPermission( 13175 android.Manifest.permission.DELETE_PACKAGES, null); 13176 Preconditions.checkNotNull(packageName); 13177 Preconditions.checkNotNull(observer); 13178 final int uid = Binder.getCallingUid(); 13179 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13180 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13181 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13182 mContext.enforceCallingOrSelfPermission( 13183 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13184 "deletePackage for user " + userId); 13185 } 13186 13187 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13188 try { 13189 observer.onPackageDeleted(packageName, 13190 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13191 } catch (RemoteException re) { 13192 } 13193 return; 13194 } 13195 13196 for (int currentUserId : users) { 13197 if (getBlockUninstallForUser(packageName, currentUserId)) { 13198 try { 13199 observer.onPackageDeleted(packageName, 13200 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13201 } catch (RemoteException re) { 13202 } 13203 return; 13204 } 13205 } 13206 13207 if (DEBUG_REMOVE) { 13208 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13209 } 13210 // Queue up an async operation since the package deletion may take a little while. 13211 mHandler.post(new Runnable() { 13212 public void run() { 13213 mHandler.removeCallbacks(this); 13214 final int returnCode = deletePackageX(packageName, userId, flags); 13215 try { 13216 observer.onPackageDeleted(packageName, returnCode, null); 13217 } catch (RemoteException e) { 13218 Log.i(TAG, "Observer no longer exists."); 13219 } //end catch 13220 } //end run 13221 }); 13222 } 13223 13224 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13225 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13226 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13227 try { 13228 if (dpm != null) { 13229 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13230 /* callingUserOnly =*/ false); 13231 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13232 : deviceOwnerComponentName.getPackageName(); 13233 // Does the package contains the device owner? 13234 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13235 // this check is probably not needed, since DO should be registered as a device 13236 // admin on some user too. (Original bug for this: b/17657954) 13237 if (packageName.equals(deviceOwnerPackageName)) { 13238 return true; 13239 } 13240 // Does it contain a device admin for any user? 13241 int[] users; 13242 if (userId == UserHandle.USER_ALL) { 13243 users = sUserManager.getUserIds(); 13244 } else { 13245 users = new int[]{userId}; 13246 } 13247 for (int i = 0; i < users.length; ++i) { 13248 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13249 return true; 13250 } 13251 } 13252 } 13253 } catch (RemoteException e) { 13254 } 13255 return false; 13256 } 13257 13258 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13259 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13260 } 13261 13262 /** 13263 * This method is an internal method that could be get invoked either 13264 * to delete an installed package or to clean up a failed installation. 13265 * After deleting an installed package, a broadcast is sent to notify any 13266 * listeners that the package has been installed. For cleaning up a failed 13267 * installation, the broadcast is not necessary since the package's 13268 * installation wouldn't have sent the initial broadcast either 13269 * The key steps in deleting a package are 13270 * deleting the package information in internal structures like mPackages, 13271 * deleting the packages base directories through installd 13272 * updating mSettings to reflect current status 13273 * persisting settings for later use 13274 * sending a broadcast if necessary 13275 */ 13276 private int deletePackageX(String packageName, int userId, int flags) { 13277 final PackageRemovedInfo info = new PackageRemovedInfo(); 13278 final boolean res; 13279 13280 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13281 ? UserHandle.ALL : new UserHandle(userId); 13282 13283 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13284 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13285 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13286 } 13287 13288 boolean removedForAllUsers = false; 13289 boolean systemUpdate = false; 13290 13291 // for the uninstall-updates case and restricted profiles, remember the per- 13292 // userhandle installed state 13293 int[] allUsers; 13294 boolean[] perUserInstalled; 13295 synchronized (mPackages) { 13296 PackageSetting ps = mSettings.mPackages.get(packageName); 13297 allUsers = sUserManager.getUserIds(); 13298 perUserInstalled = new boolean[allUsers.length]; 13299 for (int i = 0; i < allUsers.length; i++) { 13300 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13301 } 13302 } 13303 13304 synchronized (mInstallLock) { 13305 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13306 res = deletePackageLI(packageName, removeForUser, 13307 true, allUsers, perUserInstalled, 13308 flags | REMOVE_CHATTY, info, true); 13309 systemUpdate = info.isRemovedPackageSystemUpdate; 13310 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13311 removedForAllUsers = true; 13312 } 13313 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13314 + " removedForAllUsers=" + removedForAllUsers); 13315 } 13316 13317 if (res) { 13318 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13319 13320 // If the removed package was a system update, the old system package 13321 // was re-enabled; we need to broadcast this information 13322 if (systemUpdate) { 13323 Bundle extras = new Bundle(1); 13324 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13325 ? info.removedAppId : info.uid); 13326 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13327 13328 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13329 extras, 0, null, null, null); 13330 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13331 extras, 0, null, null, null); 13332 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13333 null, 0, packageName, null, null); 13334 } 13335 } 13336 // Force a gc here. 13337 Runtime.getRuntime().gc(); 13338 // Delete the resources here after sending the broadcast to let 13339 // other processes clean up before deleting resources. 13340 if (info.args != null) { 13341 synchronized (mInstallLock) { 13342 info.args.doPostDeleteLI(true); 13343 } 13344 } 13345 13346 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13347 } 13348 13349 class PackageRemovedInfo { 13350 String removedPackage; 13351 int uid = -1; 13352 int removedAppId = -1; 13353 int[] removedUsers = null; 13354 boolean isRemovedPackageSystemUpdate = false; 13355 // Clean up resources deleted packages. 13356 InstallArgs args = null; 13357 13358 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13359 Bundle extras = new Bundle(1); 13360 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13361 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13362 if (replacing) { 13363 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13364 } 13365 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13366 if (removedPackage != null) { 13367 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13368 extras, 0, null, null, removedUsers); 13369 if (fullRemove && !replacing) { 13370 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13371 extras, 0, null, null, removedUsers); 13372 } 13373 } 13374 if (removedAppId >= 0) { 13375 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13376 removedUsers); 13377 } 13378 } 13379 } 13380 13381 /* 13382 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13383 * flag is not set, the data directory is removed as well. 13384 * make sure this flag is set for partially installed apps. If not its meaningless to 13385 * delete a partially installed application. 13386 */ 13387 private void removePackageDataLI(PackageSetting ps, 13388 int[] allUserHandles, boolean[] perUserInstalled, 13389 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13390 String packageName = ps.name; 13391 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13392 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13393 // Retrieve object to delete permissions for shared user later on 13394 final PackageSetting deletedPs; 13395 // reader 13396 synchronized (mPackages) { 13397 deletedPs = mSettings.mPackages.get(packageName); 13398 if (outInfo != null) { 13399 outInfo.removedPackage = packageName; 13400 outInfo.removedUsers = deletedPs != null 13401 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13402 : null; 13403 } 13404 } 13405 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13406 removeDataDirsLI(ps.volumeUuid, packageName); 13407 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13408 } 13409 // writer 13410 synchronized (mPackages) { 13411 if (deletedPs != null) { 13412 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13413 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13414 clearDefaultBrowserIfNeeded(packageName); 13415 if (outInfo != null) { 13416 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13417 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13418 } 13419 updatePermissionsLPw(deletedPs.name, null, 0); 13420 if (deletedPs.sharedUser != null) { 13421 // Remove permissions associated with package. Since runtime 13422 // permissions are per user we have to kill the removed package 13423 // or packages running under the shared user of the removed 13424 // package if revoking the permissions requested only by the removed 13425 // package is successful and this causes a change in gids. 13426 for (int userId : UserManagerService.getInstance().getUserIds()) { 13427 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13428 userId); 13429 if (userIdToKill == UserHandle.USER_ALL 13430 || userIdToKill >= UserHandle.USER_SYSTEM) { 13431 // If gids changed for this user, kill all affected packages. 13432 mHandler.post(new Runnable() { 13433 @Override 13434 public void run() { 13435 // This has to happen with no lock held. 13436 killApplication(deletedPs.name, deletedPs.appId, 13437 KILL_APP_REASON_GIDS_CHANGED); 13438 } 13439 }); 13440 break; 13441 } 13442 } 13443 } 13444 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13445 } 13446 // make sure to preserve per-user disabled state if this removal was just 13447 // a downgrade of a system app to the factory package 13448 if (allUserHandles != null && perUserInstalled != null) { 13449 if (DEBUG_REMOVE) { 13450 Slog.d(TAG, "Propagating install state across downgrade"); 13451 } 13452 for (int i = 0; i < allUserHandles.length; i++) { 13453 if (DEBUG_REMOVE) { 13454 Slog.d(TAG, " user " + allUserHandles[i] 13455 + " => " + perUserInstalled[i]); 13456 } 13457 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13458 } 13459 } 13460 } 13461 // can downgrade to reader 13462 if (writeSettings) { 13463 // Save settings now 13464 mSettings.writeLPr(); 13465 } 13466 } 13467 if (outInfo != null) { 13468 // A user ID was deleted here. Go through all users and remove it 13469 // from KeyStore. 13470 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13471 } 13472 } 13473 13474 static boolean locationIsPrivileged(File path) { 13475 try { 13476 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13477 .getCanonicalPath(); 13478 return path.getCanonicalPath().startsWith(privilegedAppDir); 13479 } catch (IOException e) { 13480 Slog.e(TAG, "Unable to access code path " + path); 13481 } 13482 return false; 13483 } 13484 13485 /* 13486 * Tries to delete system package. 13487 */ 13488 private boolean deleteSystemPackageLI(PackageSetting newPs, 13489 int[] allUserHandles, boolean[] perUserInstalled, 13490 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13491 final boolean applyUserRestrictions 13492 = (allUserHandles != null) && (perUserInstalled != null); 13493 PackageSetting disabledPs = null; 13494 // Confirm if the system package has been updated 13495 // An updated system app can be deleted. This will also have to restore 13496 // the system pkg from system partition 13497 // reader 13498 synchronized (mPackages) { 13499 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13500 } 13501 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13502 + " disabledPs=" + disabledPs); 13503 if (disabledPs == null) { 13504 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13505 return false; 13506 } else if (DEBUG_REMOVE) { 13507 Slog.d(TAG, "Deleting system pkg from data partition"); 13508 } 13509 if (DEBUG_REMOVE) { 13510 if (applyUserRestrictions) { 13511 Slog.d(TAG, "Remembering install states:"); 13512 for (int i = 0; i < allUserHandles.length; i++) { 13513 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13514 } 13515 } 13516 } 13517 // Delete the updated package 13518 outInfo.isRemovedPackageSystemUpdate = true; 13519 if (disabledPs.versionCode < newPs.versionCode) { 13520 // Delete data for downgrades 13521 flags &= ~PackageManager.DELETE_KEEP_DATA; 13522 } else { 13523 // Preserve data by setting flag 13524 flags |= PackageManager.DELETE_KEEP_DATA; 13525 } 13526 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13527 allUserHandles, perUserInstalled, outInfo, writeSettings); 13528 if (!ret) { 13529 return false; 13530 } 13531 // writer 13532 synchronized (mPackages) { 13533 // Reinstate the old system package 13534 mSettings.enableSystemPackageLPw(newPs.name); 13535 // Remove any native libraries from the upgraded package. 13536 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13537 } 13538 // Install the system package 13539 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13540 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13541 if (locationIsPrivileged(disabledPs.codePath)) { 13542 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13543 } 13544 13545 final PackageParser.Package newPkg; 13546 try { 13547 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13548 } catch (PackageManagerException e) { 13549 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13550 return false; 13551 } 13552 13553 // writer 13554 synchronized (mPackages) { 13555 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13556 13557 // Propagate the permissions state as we do not want to drop on the floor 13558 // runtime permissions. The update permissions method below will take 13559 // care of removing obsolete permissions and grant install permissions. 13560 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13561 updatePermissionsLPw(newPkg.packageName, newPkg, 13562 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13563 13564 if (applyUserRestrictions) { 13565 if (DEBUG_REMOVE) { 13566 Slog.d(TAG, "Propagating install state across reinstall"); 13567 } 13568 for (int i = 0; i < allUserHandles.length; i++) { 13569 if (DEBUG_REMOVE) { 13570 Slog.d(TAG, " user " + allUserHandles[i] 13571 + " => " + perUserInstalled[i]); 13572 } 13573 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13574 13575 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13576 } 13577 // Regardless of writeSettings we need to ensure that this restriction 13578 // state propagation is persisted 13579 mSettings.writeAllUsersPackageRestrictionsLPr(); 13580 } 13581 // can downgrade to reader here 13582 if (writeSettings) { 13583 mSettings.writeLPr(); 13584 } 13585 } 13586 return true; 13587 } 13588 13589 private boolean deleteInstalledPackageLI(PackageSetting ps, 13590 boolean deleteCodeAndResources, int flags, 13591 int[] allUserHandles, boolean[] perUserInstalled, 13592 PackageRemovedInfo outInfo, boolean writeSettings) { 13593 if (outInfo != null) { 13594 outInfo.uid = ps.appId; 13595 } 13596 13597 // Delete package data from internal structures and also remove data if flag is set 13598 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13599 13600 // Delete application code and resources 13601 if (deleteCodeAndResources && (outInfo != null)) { 13602 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13603 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13604 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13605 } 13606 return true; 13607 } 13608 13609 @Override 13610 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13611 int userId) { 13612 mContext.enforceCallingOrSelfPermission( 13613 android.Manifest.permission.DELETE_PACKAGES, null); 13614 synchronized (mPackages) { 13615 PackageSetting ps = mSettings.mPackages.get(packageName); 13616 if (ps == null) { 13617 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13618 return false; 13619 } 13620 if (!ps.getInstalled(userId)) { 13621 // Can't block uninstall for an app that is not installed or enabled. 13622 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13623 return false; 13624 } 13625 ps.setBlockUninstall(blockUninstall, userId); 13626 mSettings.writePackageRestrictionsLPr(userId); 13627 } 13628 return true; 13629 } 13630 13631 @Override 13632 public boolean getBlockUninstallForUser(String packageName, int userId) { 13633 synchronized (mPackages) { 13634 PackageSetting ps = mSettings.mPackages.get(packageName); 13635 if (ps == null) { 13636 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13637 return false; 13638 } 13639 return ps.getBlockUninstall(userId); 13640 } 13641 } 13642 13643 /* 13644 * This method handles package deletion in general 13645 */ 13646 private boolean deletePackageLI(String packageName, UserHandle user, 13647 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13648 int flags, PackageRemovedInfo outInfo, 13649 boolean writeSettings) { 13650 if (packageName == null) { 13651 Slog.w(TAG, "Attempt to delete null packageName."); 13652 return false; 13653 } 13654 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13655 PackageSetting ps; 13656 boolean dataOnly = false; 13657 int removeUser = -1; 13658 int appId = -1; 13659 synchronized (mPackages) { 13660 ps = mSettings.mPackages.get(packageName); 13661 if (ps == null) { 13662 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13663 return false; 13664 } 13665 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13666 && user.getIdentifier() != UserHandle.USER_ALL) { 13667 // The caller is asking that the package only be deleted for a single 13668 // user. To do this, we just mark its uninstalled state and delete 13669 // its data. If this is a system app, we only allow this to happen if 13670 // they have set the special DELETE_SYSTEM_APP which requests different 13671 // semantics than normal for uninstalling system apps. 13672 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13673 final int userId = user.getIdentifier(); 13674 ps.setUserState(userId, 13675 COMPONENT_ENABLED_STATE_DEFAULT, 13676 false, //installed 13677 true, //stopped 13678 true, //notLaunched 13679 false, //hidden 13680 null, null, null, 13681 false, // blockUninstall 13682 ps.readUserState(userId).domainVerificationStatus, 0); 13683 if (!isSystemApp(ps)) { 13684 // Do not uninstall the APK if an app should be cached 13685 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13686 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13687 // Other user 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, "Still installed by other users"); 13691 removeUser = user.getIdentifier(); 13692 appId = ps.appId; 13693 scheduleWritePackageRestrictionsLocked(removeUser); 13694 } else { 13695 // We need to set it back to 'installed' so the uninstall 13696 // broadcasts will be sent correctly. 13697 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13698 ps.setInstalled(true, user.getIdentifier()); 13699 } 13700 } else { 13701 // This is a system app, so we assume that the 13702 // other users still have this package installed, so all 13703 // we need to do is clear this user's data and save that 13704 // it is uninstalled. 13705 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13706 removeUser = user.getIdentifier(); 13707 appId = ps.appId; 13708 scheduleWritePackageRestrictionsLocked(removeUser); 13709 } 13710 } 13711 } 13712 13713 if (removeUser >= 0) { 13714 // From above, we determined that we are deleting this only 13715 // for a single user. Continue the work here. 13716 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13717 if (outInfo != null) { 13718 outInfo.removedPackage = packageName; 13719 outInfo.removedAppId = appId; 13720 outInfo.removedUsers = new int[] {removeUser}; 13721 } 13722 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13723 removeKeystoreDataIfNeeded(removeUser, appId); 13724 schedulePackageCleaning(packageName, removeUser, false); 13725 synchronized (mPackages) { 13726 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13727 scheduleWritePackageRestrictionsLocked(removeUser); 13728 } 13729 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13730 } 13731 return true; 13732 } 13733 13734 if (dataOnly) { 13735 // Delete application data first 13736 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13737 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13738 return true; 13739 } 13740 13741 boolean ret = false; 13742 if (isSystemApp(ps)) { 13743 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13744 // When an updated system application is deleted we delete the existing resources as well and 13745 // fall back to existing code in system partition 13746 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13747 flags, outInfo, writeSettings); 13748 } else { 13749 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13750 // Kill application pre-emptively especially for apps on sd. 13751 killApplication(packageName, ps.appId, "uninstall pkg"); 13752 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13753 allUserHandles, perUserInstalled, 13754 outInfo, writeSettings); 13755 } 13756 13757 return ret; 13758 } 13759 13760 private final class ClearStorageConnection implements ServiceConnection { 13761 IMediaContainerService mContainerService; 13762 13763 @Override 13764 public void onServiceConnected(ComponentName name, IBinder service) { 13765 synchronized (this) { 13766 mContainerService = IMediaContainerService.Stub.asInterface(service); 13767 notifyAll(); 13768 } 13769 } 13770 13771 @Override 13772 public void onServiceDisconnected(ComponentName name) { 13773 } 13774 } 13775 13776 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13777 final boolean mounted; 13778 if (Environment.isExternalStorageEmulated()) { 13779 mounted = true; 13780 } else { 13781 final String status = Environment.getExternalStorageState(); 13782 13783 mounted = status.equals(Environment.MEDIA_MOUNTED) 13784 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13785 } 13786 13787 if (!mounted) { 13788 return; 13789 } 13790 13791 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13792 int[] users; 13793 if (userId == UserHandle.USER_ALL) { 13794 users = sUserManager.getUserIds(); 13795 } else { 13796 users = new int[] { userId }; 13797 } 13798 final ClearStorageConnection conn = new ClearStorageConnection(); 13799 if (mContext.bindServiceAsUser( 13800 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13801 try { 13802 for (int curUser : users) { 13803 long timeout = SystemClock.uptimeMillis() + 5000; 13804 synchronized (conn) { 13805 long now = SystemClock.uptimeMillis(); 13806 while (conn.mContainerService == null && now < timeout) { 13807 try { 13808 conn.wait(timeout - now); 13809 } catch (InterruptedException e) { 13810 } 13811 } 13812 } 13813 if (conn.mContainerService == null) { 13814 return; 13815 } 13816 13817 final UserEnvironment userEnv = new UserEnvironment(curUser); 13818 clearDirectory(conn.mContainerService, 13819 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13820 if (allData) { 13821 clearDirectory(conn.mContainerService, 13822 userEnv.buildExternalStorageAppDataDirs(packageName)); 13823 clearDirectory(conn.mContainerService, 13824 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13825 } 13826 } 13827 } finally { 13828 mContext.unbindService(conn); 13829 } 13830 } 13831 } 13832 13833 @Override 13834 public void clearApplicationUserData(final String packageName, 13835 final IPackageDataObserver observer, final int userId) { 13836 mContext.enforceCallingOrSelfPermission( 13837 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13838 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13839 // Queue up an async operation since the package deletion may take a little while. 13840 mHandler.post(new Runnable() { 13841 public void run() { 13842 mHandler.removeCallbacks(this); 13843 final boolean succeeded; 13844 synchronized (mInstallLock) { 13845 succeeded = clearApplicationUserDataLI(packageName, userId); 13846 } 13847 clearExternalStorageDataSync(packageName, userId, true); 13848 if (succeeded) { 13849 // invoke DeviceStorageMonitor's update method to clear any notifications 13850 DeviceStorageMonitorInternal 13851 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13852 if (dsm != null) { 13853 dsm.checkMemory(); 13854 } 13855 } 13856 if(observer != null) { 13857 try { 13858 observer.onRemoveCompleted(packageName, succeeded); 13859 } catch (RemoteException e) { 13860 Log.i(TAG, "Observer no longer exists."); 13861 } 13862 } //end if observer 13863 } //end run 13864 }); 13865 } 13866 13867 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13868 if (packageName == null) { 13869 Slog.w(TAG, "Attempt to delete null packageName."); 13870 return false; 13871 } 13872 13873 // Try finding details about the requested package 13874 PackageParser.Package pkg; 13875 synchronized (mPackages) { 13876 pkg = mPackages.get(packageName); 13877 if (pkg == null) { 13878 final PackageSetting ps = mSettings.mPackages.get(packageName); 13879 if (ps != null) { 13880 pkg = ps.pkg; 13881 } 13882 } 13883 13884 if (pkg == null) { 13885 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13886 return false; 13887 } 13888 13889 PackageSetting ps = (PackageSetting) pkg.mExtras; 13890 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13891 } 13892 13893 // Always delete data directories for package, even if we found no other 13894 // record of app. This helps users recover from UID mismatches without 13895 // resorting to a full data wipe. 13896 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13897 if (retCode < 0) { 13898 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13899 return false; 13900 } 13901 13902 final int appId = pkg.applicationInfo.uid; 13903 removeKeystoreDataIfNeeded(userId, appId); 13904 13905 // Create a native library symlink only if we have native libraries 13906 // and if the native libraries are 32 bit libraries. We do not provide 13907 // this symlink for 64 bit libraries. 13908 if (pkg.applicationInfo.primaryCpuAbi != null && 13909 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13910 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13911 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13912 nativeLibPath, userId) < 0) { 13913 Slog.w(TAG, "Failed linking native library dir"); 13914 return false; 13915 } 13916 } 13917 13918 return true; 13919 } 13920 13921 /** 13922 * Reverts user permission state changes (permissions and flags) in 13923 * all packages for a given user. 13924 * 13925 * @param userId The device user for which to do a reset. 13926 */ 13927 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13928 final int packageCount = mPackages.size(); 13929 for (int i = 0; i < packageCount; i++) { 13930 PackageParser.Package pkg = mPackages.valueAt(i); 13931 PackageSetting ps = (PackageSetting) pkg.mExtras; 13932 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13933 } 13934 } 13935 13936 /** 13937 * Reverts user permission state changes (permissions and flags). 13938 * 13939 * @param ps The package for which to reset. 13940 * @param userId The device user for which to do a reset. 13941 */ 13942 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13943 final PackageSetting ps, final int userId) { 13944 if (ps.pkg == null) { 13945 return; 13946 } 13947 13948 // These are flags that can change base on user actions. 13949 final int userSettableMask = FLAG_PERMISSION_USER_SET 13950 | FLAG_PERMISSION_USER_FIXED 13951 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 13952 | FLAG_PERMISSION_REVIEW_REQUIRED; 13953 13954 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13955 | FLAG_PERMISSION_POLICY_FIXED; 13956 13957 boolean writeInstallPermissions = false; 13958 boolean writeRuntimePermissions = false; 13959 13960 final int permissionCount = ps.pkg.requestedPermissions.size(); 13961 for (int i = 0; i < permissionCount; i++) { 13962 String permission = ps.pkg.requestedPermissions.get(i); 13963 13964 BasePermission bp = mSettings.mPermissions.get(permission); 13965 if (bp == null) { 13966 continue; 13967 } 13968 13969 // If shared user we just reset the state to which only this app contributed. 13970 if (ps.sharedUser != null) { 13971 boolean used = false; 13972 final int packageCount = ps.sharedUser.packages.size(); 13973 for (int j = 0; j < packageCount; j++) { 13974 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13975 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13976 && pkg.pkg.requestedPermissions.contains(permission)) { 13977 used = true; 13978 break; 13979 } 13980 } 13981 if (used) { 13982 continue; 13983 } 13984 } 13985 13986 PermissionsState permissionsState = ps.getPermissionsState(); 13987 13988 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13989 13990 // Always clear the user settable flags. 13991 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13992 bp.name) != null; 13993 // If permission review is enabled and this is a legacy app, mark the 13994 // permission as requiring a review as this is the initial state. 13995 int flags = 0; 13996 if (Build.PERMISSIONS_REVIEW_REQUIRED 13997 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 13998 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 13999 } 14000 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14001 if (hasInstallState) { 14002 writeInstallPermissions = true; 14003 } else { 14004 writeRuntimePermissions = true; 14005 } 14006 } 14007 14008 // Below is only runtime permission handling. 14009 if (!bp.isRuntime()) { 14010 continue; 14011 } 14012 14013 // Never clobber system or policy. 14014 if ((oldFlags & policyOrSystemFlags) != 0) { 14015 continue; 14016 } 14017 14018 // If this permission was granted by default, make sure it is. 14019 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14020 if (permissionsState.grantRuntimePermission(bp, userId) 14021 != PERMISSION_OPERATION_FAILURE) { 14022 writeRuntimePermissions = true; 14023 } 14024 // If permission review is enabled the permissions for a legacy apps 14025 // are represented as constantly granted runtime ones, so don't revoke. 14026 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14027 // Otherwise, reset the permission. 14028 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14029 switch (revokeResult) { 14030 case PERMISSION_OPERATION_SUCCESS: { 14031 writeRuntimePermissions = true; 14032 } break; 14033 14034 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14035 writeRuntimePermissions = true; 14036 final int appId = ps.appId; 14037 mHandler.post(new Runnable() { 14038 @Override 14039 public void run() { 14040 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14041 } 14042 }); 14043 } break; 14044 } 14045 } 14046 } 14047 14048 // Synchronously write as we are taking permissions away. 14049 if (writeRuntimePermissions) { 14050 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14051 } 14052 14053 // Synchronously write as we are taking permissions away. 14054 if (writeInstallPermissions) { 14055 mSettings.writeLPr(); 14056 } 14057 } 14058 14059 /** 14060 * Remove entries from the keystore daemon. Will only remove it if the 14061 * {@code appId} is valid. 14062 */ 14063 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14064 if (appId < 0) { 14065 return; 14066 } 14067 14068 final KeyStore keyStore = KeyStore.getInstance(); 14069 if (keyStore != null) { 14070 if (userId == UserHandle.USER_ALL) { 14071 for (final int individual : sUserManager.getUserIds()) { 14072 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14073 } 14074 } else { 14075 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14076 } 14077 } else { 14078 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14079 } 14080 } 14081 14082 @Override 14083 public void deleteApplicationCacheFiles(final String packageName, 14084 final IPackageDataObserver observer) { 14085 mContext.enforceCallingOrSelfPermission( 14086 android.Manifest.permission.DELETE_CACHE_FILES, null); 14087 // Queue up an async operation since the package deletion may take a little while. 14088 final int userId = UserHandle.getCallingUserId(); 14089 mHandler.post(new Runnable() { 14090 public void run() { 14091 mHandler.removeCallbacks(this); 14092 final boolean succeded; 14093 synchronized (mInstallLock) { 14094 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14095 } 14096 clearExternalStorageDataSync(packageName, userId, false); 14097 if (observer != null) { 14098 try { 14099 observer.onRemoveCompleted(packageName, succeded); 14100 } catch (RemoteException e) { 14101 Log.i(TAG, "Observer no longer exists."); 14102 } 14103 } //end if observer 14104 } //end run 14105 }); 14106 } 14107 14108 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14109 if (packageName == null) { 14110 Slog.w(TAG, "Attempt to delete null packageName."); 14111 return false; 14112 } 14113 PackageParser.Package p; 14114 synchronized (mPackages) { 14115 p = mPackages.get(packageName); 14116 } 14117 if (p == null) { 14118 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14119 return false; 14120 } 14121 final ApplicationInfo applicationInfo = p.applicationInfo; 14122 if (applicationInfo == null) { 14123 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14124 return false; 14125 } 14126 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14127 if (retCode < 0) { 14128 Slog.w(TAG, "Couldn't remove cache files for package: " 14129 + packageName + " u" + userId); 14130 return false; 14131 } 14132 return true; 14133 } 14134 14135 @Override 14136 public void getPackageSizeInfo(final String packageName, int userHandle, 14137 final IPackageStatsObserver observer) { 14138 mContext.enforceCallingOrSelfPermission( 14139 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14140 if (packageName == null) { 14141 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14142 } 14143 14144 PackageStats stats = new PackageStats(packageName, userHandle); 14145 14146 /* 14147 * Queue up an async operation since the package measurement may take a 14148 * little while. 14149 */ 14150 Message msg = mHandler.obtainMessage(INIT_COPY); 14151 msg.obj = new MeasureParams(stats, observer); 14152 mHandler.sendMessage(msg); 14153 } 14154 14155 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14156 PackageStats pStats) { 14157 if (packageName == null) { 14158 Slog.w(TAG, "Attempt to get size of null packageName."); 14159 return false; 14160 } 14161 PackageParser.Package p; 14162 boolean dataOnly = false; 14163 String libDirRoot = null; 14164 String asecPath = null; 14165 PackageSetting ps = null; 14166 synchronized (mPackages) { 14167 p = mPackages.get(packageName); 14168 ps = mSettings.mPackages.get(packageName); 14169 if(p == null) { 14170 dataOnly = true; 14171 if((ps == null) || (ps.pkg == null)) { 14172 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14173 return false; 14174 } 14175 p = ps.pkg; 14176 } 14177 if (ps != null) { 14178 libDirRoot = ps.legacyNativeLibraryPathString; 14179 } 14180 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14181 final long token = Binder.clearCallingIdentity(); 14182 try { 14183 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14184 if (secureContainerId != null) { 14185 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14186 } 14187 } finally { 14188 Binder.restoreCallingIdentity(token); 14189 } 14190 } 14191 } 14192 String publicSrcDir = null; 14193 if(!dataOnly) { 14194 final ApplicationInfo applicationInfo = p.applicationInfo; 14195 if (applicationInfo == null) { 14196 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14197 return false; 14198 } 14199 if (p.isForwardLocked()) { 14200 publicSrcDir = applicationInfo.getBaseResourcePath(); 14201 } 14202 } 14203 // TODO: extend to measure size of split APKs 14204 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14205 // not just the first level. 14206 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14207 // just the primary. 14208 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14209 14210 String apkPath; 14211 File packageDir = new File(p.codePath); 14212 14213 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14214 apkPath = packageDir.getAbsolutePath(); 14215 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14216 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14217 libDirRoot = null; 14218 } 14219 } else { 14220 apkPath = p.baseCodePath; 14221 } 14222 14223 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14224 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14225 if (res < 0) { 14226 return false; 14227 } 14228 14229 // Fix-up for forward-locked applications in ASEC containers. 14230 if (!isExternal(p)) { 14231 pStats.codeSize += pStats.externalCodeSize; 14232 pStats.externalCodeSize = 0L; 14233 } 14234 14235 return true; 14236 } 14237 14238 14239 @Override 14240 public void addPackageToPreferred(String packageName) { 14241 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14242 } 14243 14244 @Override 14245 public void removePackageFromPreferred(String packageName) { 14246 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14247 } 14248 14249 @Override 14250 public List<PackageInfo> getPreferredPackages(int flags) { 14251 return new ArrayList<PackageInfo>(); 14252 } 14253 14254 private int getUidTargetSdkVersionLockedLPr(int uid) { 14255 Object obj = mSettings.getUserIdLPr(uid); 14256 if (obj instanceof SharedUserSetting) { 14257 final SharedUserSetting sus = (SharedUserSetting) obj; 14258 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14259 final Iterator<PackageSetting> it = sus.packages.iterator(); 14260 while (it.hasNext()) { 14261 final PackageSetting ps = it.next(); 14262 if (ps.pkg != null) { 14263 int v = ps.pkg.applicationInfo.targetSdkVersion; 14264 if (v < vers) vers = v; 14265 } 14266 } 14267 return vers; 14268 } else if (obj instanceof PackageSetting) { 14269 final PackageSetting ps = (PackageSetting) obj; 14270 if (ps.pkg != null) { 14271 return ps.pkg.applicationInfo.targetSdkVersion; 14272 } 14273 } 14274 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14275 } 14276 14277 @Override 14278 public void addPreferredActivity(IntentFilter filter, int match, 14279 ComponentName[] set, ComponentName activity, int userId) { 14280 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14281 "Adding preferred"); 14282 } 14283 14284 private void addPreferredActivityInternal(IntentFilter filter, int match, 14285 ComponentName[] set, ComponentName activity, boolean always, int userId, 14286 String opname) { 14287 // writer 14288 int callingUid = Binder.getCallingUid(); 14289 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14290 if (filter.countActions() == 0) { 14291 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14292 return; 14293 } 14294 synchronized (mPackages) { 14295 if (mContext.checkCallingOrSelfPermission( 14296 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14297 != PackageManager.PERMISSION_GRANTED) { 14298 if (getUidTargetSdkVersionLockedLPr(callingUid) 14299 < Build.VERSION_CODES.FROYO) { 14300 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14301 + callingUid); 14302 return; 14303 } 14304 mContext.enforceCallingOrSelfPermission( 14305 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14306 } 14307 14308 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14309 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14310 + userId + ":"); 14311 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14312 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14313 scheduleWritePackageRestrictionsLocked(userId); 14314 } 14315 } 14316 14317 @Override 14318 public void replacePreferredActivity(IntentFilter filter, int match, 14319 ComponentName[] set, ComponentName activity, int userId) { 14320 if (filter.countActions() != 1) { 14321 throw new IllegalArgumentException( 14322 "replacePreferredActivity expects filter to have only 1 action."); 14323 } 14324 if (filter.countDataAuthorities() != 0 14325 || filter.countDataPaths() != 0 14326 || filter.countDataSchemes() > 1 14327 || filter.countDataTypes() != 0) { 14328 throw new IllegalArgumentException( 14329 "replacePreferredActivity expects filter to have no data authorities, " + 14330 "paths, or types; and at most one scheme."); 14331 } 14332 14333 final int callingUid = Binder.getCallingUid(); 14334 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14335 synchronized (mPackages) { 14336 if (mContext.checkCallingOrSelfPermission( 14337 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14338 != PackageManager.PERMISSION_GRANTED) { 14339 if (getUidTargetSdkVersionLockedLPr(callingUid) 14340 < Build.VERSION_CODES.FROYO) { 14341 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14342 + Binder.getCallingUid()); 14343 return; 14344 } 14345 mContext.enforceCallingOrSelfPermission( 14346 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14347 } 14348 14349 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14350 if (pir != null) { 14351 // Get all of the existing entries that exactly match this filter. 14352 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14353 if (existing != null && existing.size() == 1) { 14354 PreferredActivity cur = existing.get(0); 14355 if (DEBUG_PREFERRED) { 14356 Slog.i(TAG, "Checking replace of preferred:"); 14357 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14358 if (!cur.mPref.mAlways) { 14359 Slog.i(TAG, " -- CUR; not mAlways!"); 14360 } else { 14361 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14362 Slog.i(TAG, " -- CUR: mSet=" 14363 + Arrays.toString(cur.mPref.mSetComponents)); 14364 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14365 Slog.i(TAG, " -- NEW: mMatch=" 14366 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14367 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14368 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14369 } 14370 } 14371 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14372 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14373 && cur.mPref.sameSet(set)) { 14374 // Setting the preferred activity to what it happens to be already 14375 if (DEBUG_PREFERRED) { 14376 Slog.i(TAG, "Replacing with same preferred activity " 14377 + cur.mPref.mShortComponent + " for user " 14378 + userId + ":"); 14379 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14380 } 14381 return; 14382 } 14383 } 14384 14385 if (existing != null) { 14386 if (DEBUG_PREFERRED) { 14387 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14389 } 14390 for (int i = 0; i < existing.size(); i++) { 14391 PreferredActivity pa = existing.get(i); 14392 if (DEBUG_PREFERRED) { 14393 Slog.i(TAG, "Removing existing preferred activity " 14394 + pa.mPref.mComponent + ":"); 14395 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14396 } 14397 pir.removeFilter(pa); 14398 } 14399 } 14400 } 14401 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14402 "Replacing preferred"); 14403 } 14404 } 14405 14406 @Override 14407 public void clearPackagePreferredActivities(String packageName) { 14408 final int uid = Binder.getCallingUid(); 14409 // writer 14410 synchronized (mPackages) { 14411 PackageParser.Package pkg = mPackages.get(packageName); 14412 if (pkg == null || pkg.applicationInfo.uid != uid) { 14413 if (mContext.checkCallingOrSelfPermission( 14414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14415 != PackageManager.PERMISSION_GRANTED) { 14416 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14417 < Build.VERSION_CODES.FROYO) { 14418 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14419 + Binder.getCallingUid()); 14420 return; 14421 } 14422 mContext.enforceCallingOrSelfPermission( 14423 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14424 } 14425 } 14426 14427 int user = UserHandle.getCallingUserId(); 14428 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14429 scheduleWritePackageRestrictionsLocked(user); 14430 } 14431 } 14432 } 14433 14434 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14435 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14436 ArrayList<PreferredActivity> removed = null; 14437 boolean changed = false; 14438 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14439 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14440 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14441 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14442 continue; 14443 } 14444 Iterator<PreferredActivity> it = pir.filterIterator(); 14445 while (it.hasNext()) { 14446 PreferredActivity pa = it.next(); 14447 // Mark entry for removal only if it matches the package name 14448 // and the entry is of type "always". 14449 if (packageName == null || 14450 (pa.mPref.mComponent.getPackageName().equals(packageName) 14451 && pa.mPref.mAlways)) { 14452 if (removed == null) { 14453 removed = new ArrayList<PreferredActivity>(); 14454 } 14455 removed.add(pa); 14456 } 14457 } 14458 if (removed != null) { 14459 for (int j=0; j<removed.size(); j++) { 14460 PreferredActivity pa = removed.get(j); 14461 pir.removeFilter(pa); 14462 } 14463 changed = true; 14464 } 14465 } 14466 return changed; 14467 } 14468 14469 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14470 private void clearIntentFilterVerificationsLPw(int userId) { 14471 final int packageCount = mPackages.size(); 14472 for (int i = 0; i < packageCount; i++) { 14473 PackageParser.Package pkg = mPackages.valueAt(i); 14474 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14475 } 14476 } 14477 14478 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14479 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14480 if (userId == UserHandle.USER_ALL) { 14481 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14482 sUserManager.getUserIds())) { 14483 for (int oneUserId : sUserManager.getUserIds()) { 14484 scheduleWritePackageRestrictionsLocked(oneUserId); 14485 } 14486 } 14487 } else { 14488 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14489 scheduleWritePackageRestrictionsLocked(userId); 14490 } 14491 } 14492 } 14493 14494 void clearDefaultBrowserIfNeeded(String packageName) { 14495 for (int oneUserId : sUserManager.getUserIds()) { 14496 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14497 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14498 if (packageName.equals(defaultBrowserPackageName)) { 14499 setDefaultBrowserPackageName(null, oneUserId); 14500 } 14501 } 14502 } 14503 14504 @Override 14505 public void resetApplicationPreferences(int userId) { 14506 mContext.enforceCallingOrSelfPermission( 14507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14508 // writer 14509 synchronized (mPackages) { 14510 final long identity = Binder.clearCallingIdentity(); 14511 try { 14512 clearPackagePreferredActivitiesLPw(null, userId); 14513 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14514 // TODO: We have to reset the default SMS and Phone. This requires 14515 // significant refactoring to keep all default apps in the package 14516 // manager (cleaner but more work) or have the services provide 14517 // callbacks to the package manager to request a default app reset. 14518 applyFactoryDefaultBrowserLPw(userId); 14519 clearIntentFilterVerificationsLPw(userId); 14520 primeDomainVerificationsLPw(userId); 14521 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14522 scheduleWritePackageRestrictionsLocked(userId); 14523 } finally { 14524 Binder.restoreCallingIdentity(identity); 14525 } 14526 } 14527 } 14528 14529 @Override 14530 public int getPreferredActivities(List<IntentFilter> outFilters, 14531 List<ComponentName> outActivities, String packageName) { 14532 14533 int num = 0; 14534 final int userId = UserHandle.getCallingUserId(); 14535 // reader 14536 synchronized (mPackages) { 14537 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14538 if (pir != null) { 14539 final Iterator<PreferredActivity> it = pir.filterIterator(); 14540 while (it.hasNext()) { 14541 final PreferredActivity pa = it.next(); 14542 if (packageName == null 14543 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14544 && pa.mPref.mAlways)) { 14545 if (outFilters != null) { 14546 outFilters.add(new IntentFilter(pa)); 14547 } 14548 if (outActivities != null) { 14549 outActivities.add(pa.mPref.mComponent); 14550 } 14551 } 14552 } 14553 } 14554 } 14555 14556 return num; 14557 } 14558 14559 @Override 14560 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14561 int userId) { 14562 int callingUid = Binder.getCallingUid(); 14563 if (callingUid != Process.SYSTEM_UID) { 14564 throw new SecurityException( 14565 "addPersistentPreferredActivity can only be run by the system"); 14566 } 14567 if (filter.countActions() == 0) { 14568 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14569 return; 14570 } 14571 synchronized (mPackages) { 14572 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14573 " :"); 14574 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14575 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14576 new PersistentPreferredActivity(filter, activity)); 14577 scheduleWritePackageRestrictionsLocked(userId); 14578 } 14579 } 14580 14581 @Override 14582 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14583 int callingUid = Binder.getCallingUid(); 14584 if (callingUid != Process.SYSTEM_UID) { 14585 throw new SecurityException( 14586 "clearPackagePersistentPreferredActivities can only be run by the system"); 14587 } 14588 ArrayList<PersistentPreferredActivity> removed = null; 14589 boolean changed = false; 14590 synchronized (mPackages) { 14591 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14592 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14593 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14594 .valueAt(i); 14595 if (userId != thisUserId) { 14596 continue; 14597 } 14598 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14599 while (it.hasNext()) { 14600 PersistentPreferredActivity ppa = it.next(); 14601 // Mark entry for removal only if it matches the package name. 14602 if (ppa.mComponent.getPackageName().equals(packageName)) { 14603 if (removed == null) { 14604 removed = new ArrayList<PersistentPreferredActivity>(); 14605 } 14606 removed.add(ppa); 14607 } 14608 } 14609 if (removed != null) { 14610 for (int j=0; j<removed.size(); j++) { 14611 PersistentPreferredActivity ppa = removed.get(j); 14612 ppir.removeFilter(ppa); 14613 } 14614 changed = true; 14615 } 14616 } 14617 14618 if (changed) { 14619 scheduleWritePackageRestrictionsLocked(userId); 14620 } 14621 } 14622 } 14623 14624 /** 14625 * Common machinery for picking apart a restored XML blob and passing 14626 * it to a caller-supplied functor to be applied to the running system. 14627 */ 14628 private void restoreFromXml(XmlPullParser parser, int userId, 14629 String expectedStartTag, BlobXmlRestorer functor) 14630 throws IOException, XmlPullParserException { 14631 int type; 14632 while ((type = parser.next()) != XmlPullParser.START_TAG 14633 && type != XmlPullParser.END_DOCUMENT) { 14634 } 14635 if (type != XmlPullParser.START_TAG) { 14636 // oops didn't find a start tag?! 14637 if (DEBUG_BACKUP) { 14638 Slog.e(TAG, "Didn't find start tag during restore"); 14639 } 14640 return; 14641 } 14642 14643 // this is supposed to be TAG_PREFERRED_BACKUP 14644 if (!expectedStartTag.equals(parser.getName())) { 14645 if (DEBUG_BACKUP) { 14646 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14647 } 14648 return; 14649 } 14650 14651 // skip interfering stuff, then we're aligned with the backing implementation 14652 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14653 functor.apply(parser, userId); 14654 } 14655 14656 private interface BlobXmlRestorer { 14657 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14658 } 14659 14660 /** 14661 * Non-Binder method, support for the backup/restore mechanism: write the 14662 * full set of preferred activities in its canonical XML format. Returns the 14663 * XML output as a byte array, or null if there is none. 14664 */ 14665 @Override 14666 public byte[] getPreferredActivityBackup(int userId) { 14667 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14668 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14669 } 14670 14671 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14672 try { 14673 final XmlSerializer serializer = new FastXmlSerializer(); 14674 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14675 serializer.startDocument(null, true); 14676 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14677 14678 synchronized (mPackages) { 14679 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14680 } 14681 14682 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14683 serializer.endDocument(); 14684 serializer.flush(); 14685 } catch (Exception e) { 14686 if (DEBUG_BACKUP) { 14687 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14688 } 14689 return null; 14690 } 14691 14692 return dataStream.toByteArray(); 14693 } 14694 14695 @Override 14696 public void restorePreferredActivities(byte[] backup, int userId) { 14697 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14698 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14699 } 14700 14701 try { 14702 final XmlPullParser parser = Xml.newPullParser(); 14703 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14704 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14705 new BlobXmlRestorer() { 14706 @Override 14707 public void apply(XmlPullParser parser, int userId) 14708 throws XmlPullParserException, IOException { 14709 synchronized (mPackages) { 14710 mSettings.readPreferredActivitiesLPw(parser, userId); 14711 } 14712 } 14713 } ); 14714 } catch (Exception e) { 14715 if (DEBUG_BACKUP) { 14716 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14717 } 14718 } 14719 } 14720 14721 /** 14722 * Non-Binder method, support for the backup/restore mechanism: write the 14723 * default browser (etc) settings in its canonical XML format. Returns the default 14724 * browser XML representation as a byte array, or null if there is none. 14725 */ 14726 @Override 14727 public byte[] getDefaultAppsBackup(int userId) { 14728 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14729 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14730 } 14731 14732 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14733 try { 14734 final XmlSerializer serializer = new FastXmlSerializer(); 14735 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14736 serializer.startDocument(null, true); 14737 serializer.startTag(null, TAG_DEFAULT_APPS); 14738 14739 synchronized (mPackages) { 14740 mSettings.writeDefaultAppsLPr(serializer, userId); 14741 } 14742 14743 serializer.endTag(null, TAG_DEFAULT_APPS); 14744 serializer.endDocument(); 14745 serializer.flush(); 14746 } catch (Exception e) { 14747 if (DEBUG_BACKUP) { 14748 Slog.e(TAG, "Unable to write default apps for backup", e); 14749 } 14750 return null; 14751 } 14752 14753 return dataStream.toByteArray(); 14754 } 14755 14756 @Override 14757 public void restoreDefaultApps(byte[] backup, int userId) { 14758 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14759 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14760 } 14761 14762 try { 14763 final XmlPullParser parser = Xml.newPullParser(); 14764 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14765 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14766 new BlobXmlRestorer() { 14767 @Override 14768 public void apply(XmlPullParser parser, int userId) 14769 throws XmlPullParserException, IOException { 14770 synchronized (mPackages) { 14771 mSettings.readDefaultAppsLPw(parser, userId); 14772 } 14773 } 14774 } ); 14775 } catch (Exception e) { 14776 if (DEBUG_BACKUP) { 14777 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14778 } 14779 } 14780 } 14781 14782 @Override 14783 public byte[] getIntentFilterVerificationBackup(int userId) { 14784 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14785 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14786 } 14787 14788 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14789 try { 14790 final XmlSerializer serializer = new FastXmlSerializer(); 14791 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14792 serializer.startDocument(null, true); 14793 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14794 14795 synchronized (mPackages) { 14796 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14797 } 14798 14799 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14800 serializer.endDocument(); 14801 serializer.flush(); 14802 } catch (Exception e) { 14803 if (DEBUG_BACKUP) { 14804 Slog.e(TAG, "Unable to write default apps for backup", e); 14805 } 14806 return null; 14807 } 14808 14809 return dataStream.toByteArray(); 14810 } 14811 14812 @Override 14813 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14814 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14815 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14816 } 14817 14818 try { 14819 final XmlPullParser parser = Xml.newPullParser(); 14820 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14821 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14822 new BlobXmlRestorer() { 14823 @Override 14824 public void apply(XmlPullParser parser, int userId) 14825 throws XmlPullParserException, IOException { 14826 synchronized (mPackages) { 14827 mSettings.readAllDomainVerificationsLPr(parser, userId); 14828 mSettings.writeLPr(); 14829 } 14830 } 14831 } ); 14832 } catch (Exception e) { 14833 if (DEBUG_BACKUP) { 14834 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14835 } 14836 } 14837 } 14838 14839 @Override 14840 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14841 int sourceUserId, int targetUserId, int flags) { 14842 mContext.enforceCallingOrSelfPermission( 14843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14844 int callingUid = Binder.getCallingUid(); 14845 enforceOwnerRights(ownerPackage, callingUid); 14846 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14847 if (intentFilter.countActions() == 0) { 14848 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14849 return; 14850 } 14851 synchronized (mPackages) { 14852 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14853 ownerPackage, targetUserId, flags); 14854 CrossProfileIntentResolver resolver = 14855 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14856 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14857 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14858 if (existing != null) { 14859 int size = existing.size(); 14860 for (int i = 0; i < size; i++) { 14861 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14862 return; 14863 } 14864 } 14865 } 14866 resolver.addFilter(newFilter); 14867 scheduleWritePackageRestrictionsLocked(sourceUserId); 14868 } 14869 } 14870 14871 @Override 14872 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14873 mContext.enforceCallingOrSelfPermission( 14874 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14875 int callingUid = Binder.getCallingUid(); 14876 enforceOwnerRights(ownerPackage, callingUid); 14877 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14878 synchronized (mPackages) { 14879 CrossProfileIntentResolver resolver = 14880 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14881 ArraySet<CrossProfileIntentFilter> set = 14882 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14883 for (CrossProfileIntentFilter filter : set) { 14884 if (filter.getOwnerPackage().equals(ownerPackage)) { 14885 resolver.removeFilter(filter); 14886 } 14887 } 14888 scheduleWritePackageRestrictionsLocked(sourceUserId); 14889 } 14890 } 14891 14892 // Enforcing that callingUid is owning pkg on userId 14893 private void enforceOwnerRights(String pkg, int callingUid) { 14894 // The system owns everything. 14895 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14896 return; 14897 } 14898 int callingUserId = UserHandle.getUserId(callingUid); 14899 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14900 if (pi == null) { 14901 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14902 + callingUserId); 14903 } 14904 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14905 throw new SecurityException("Calling uid " + callingUid 14906 + " does not own package " + pkg); 14907 } 14908 } 14909 14910 @Override 14911 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14912 Intent intent = new Intent(Intent.ACTION_MAIN); 14913 intent.addCategory(Intent.CATEGORY_HOME); 14914 14915 final int callingUserId = UserHandle.getCallingUserId(); 14916 List<ResolveInfo> list = queryIntentActivities(intent, null, 14917 PackageManager.GET_META_DATA, callingUserId); 14918 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14919 true, false, false, callingUserId); 14920 14921 allHomeCandidates.clear(); 14922 if (list != null) { 14923 for (ResolveInfo ri : list) { 14924 allHomeCandidates.add(ri); 14925 } 14926 } 14927 return (preferred == null || preferred.activityInfo == null) 14928 ? null 14929 : new ComponentName(preferred.activityInfo.packageName, 14930 preferred.activityInfo.name); 14931 } 14932 14933 @Override 14934 public void setApplicationEnabledSetting(String appPackageName, 14935 int newState, int flags, int userId, String callingPackage) { 14936 if (!sUserManager.exists(userId)) return; 14937 if (callingPackage == null) { 14938 callingPackage = Integer.toString(Binder.getCallingUid()); 14939 } 14940 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14941 } 14942 14943 @Override 14944 public void setComponentEnabledSetting(ComponentName componentName, 14945 int newState, int flags, int userId) { 14946 if (!sUserManager.exists(userId)) return; 14947 setEnabledSetting(componentName.getPackageName(), 14948 componentName.getClassName(), newState, flags, userId, null); 14949 } 14950 14951 private void setEnabledSetting(final String packageName, String className, int newState, 14952 final int flags, int userId, String callingPackage) { 14953 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14954 || newState == COMPONENT_ENABLED_STATE_ENABLED 14955 || newState == COMPONENT_ENABLED_STATE_DISABLED 14956 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14957 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14958 throw new IllegalArgumentException("Invalid new component state: " 14959 + newState); 14960 } 14961 PackageSetting pkgSetting; 14962 final int uid = Binder.getCallingUid(); 14963 final int permission = mContext.checkCallingOrSelfPermission( 14964 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14965 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14966 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14967 boolean sendNow = false; 14968 boolean isApp = (className == null); 14969 String componentName = isApp ? packageName : className; 14970 int packageUid = -1; 14971 ArrayList<String> components; 14972 14973 // writer 14974 synchronized (mPackages) { 14975 pkgSetting = mSettings.mPackages.get(packageName); 14976 if (pkgSetting == null) { 14977 if (className == null) { 14978 throw new IllegalArgumentException( 14979 "Unknown package: " + packageName); 14980 } 14981 throw new IllegalArgumentException( 14982 "Unknown component: " + packageName 14983 + "/" + className); 14984 } 14985 // Allow root and verify that userId is not being specified by a different user 14986 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14987 throw new SecurityException( 14988 "Permission Denial: attempt to change component state from pid=" 14989 + Binder.getCallingPid() 14990 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14991 } 14992 if (className == null) { 14993 // We're dealing with an application/package level state change 14994 if (pkgSetting.getEnabled(userId) == newState) { 14995 // Nothing to do 14996 return; 14997 } 14998 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14999 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15000 // Don't care about who enables an app. 15001 callingPackage = null; 15002 } 15003 pkgSetting.setEnabled(newState, userId, callingPackage); 15004 // pkgSetting.pkg.mSetEnabled = newState; 15005 } else { 15006 // We're dealing with a component level state change 15007 // First, verify that this is a valid class name. 15008 PackageParser.Package pkg = pkgSetting.pkg; 15009 if (pkg == null || !pkg.hasComponentClassName(className)) { 15010 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 15011 throw new IllegalArgumentException("Component class " + className 15012 + " does not exist in " + packageName); 15013 } else { 15014 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15015 + className + " does not exist in " + packageName); 15016 } 15017 } 15018 switch (newState) { 15019 case COMPONENT_ENABLED_STATE_ENABLED: 15020 if (!pkgSetting.enableComponentLPw(className, userId)) { 15021 return; 15022 } 15023 break; 15024 case COMPONENT_ENABLED_STATE_DISABLED: 15025 if (!pkgSetting.disableComponentLPw(className, userId)) { 15026 return; 15027 } 15028 break; 15029 case COMPONENT_ENABLED_STATE_DEFAULT: 15030 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15031 return; 15032 } 15033 break; 15034 default: 15035 Slog.e(TAG, "Invalid new component state: " + newState); 15036 return; 15037 } 15038 } 15039 scheduleWritePackageRestrictionsLocked(userId); 15040 components = mPendingBroadcasts.get(userId, packageName); 15041 final boolean newPackage = components == null; 15042 if (newPackage) { 15043 components = new ArrayList<String>(); 15044 } 15045 if (!components.contains(componentName)) { 15046 components.add(componentName); 15047 } 15048 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15049 sendNow = true; 15050 // Purge entry from pending broadcast list if another one exists already 15051 // since we are sending one right away. 15052 mPendingBroadcasts.remove(userId, packageName); 15053 } else { 15054 if (newPackage) { 15055 mPendingBroadcasts.put(userId, packageName, components); 15056 } 15057 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15058 // Schedule a message 15059 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15060 } 15061 } 15062 } 15063 15064 long callingId = Binder.clearCallingIdentity(); 15065 try { 15066 if (sendNow) { 15067 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15068 sendPackageChangedBroadcast(packageName, 15069 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15070 } 15071 } finally { 15072 Binder.restoreCallingIdentity(callingId); 15073 } 15074 } 15075 15076 private void sendPackageChangedBroadcast(String packageName, 15077 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15078 if (DEBUG_INSTALL) 15079 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15080 + componentNames); 15081 Bundle extras = new Bundle(4); 15082 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15083 String nameList[] = new String[componentNames.size()]; 15084 componentNames.toArray(nameList); 15085 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15086 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15087 extras.putInt(Intent.EXTRA_UID, packageUid); 15088 // If this is not reporting a change of the overall package, then only send it 15089 // to registered receivers. We don't want to launch a swath of apps for every 15090 // little component state change. 15091 final int flags = !componentNames.contains(packageName) 15092 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15093 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15094 new int[] {UserHandle.getUserId(packageUid)}); 15095 } 15096 15097 @Override 15098 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15099 if (!sUserManager.exists(userId)) return; 15100 final int uid = Binder.getCallingUid(); 15101 final int permission = mContext.checkCallingOrSelfPermission( 15102 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15103 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15104 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15105 // writer 15106 synchronized (mPackages) { 15107 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15108 allowedByPermission, uid, userId)) { 15109 scheduleWritePackageRestrictionsLocked(userId); 15110 } 15111 } 15112 } 15113 15114 @Override 15115 public String getInstallerPackageName(String packageName) { 15116 // reader 15117 synchronized (mPackages) { 15118 return mSettings.getInstallerPackageNameLPr(packageName); 15119 } 15120 } 15121 15122 @Override 15123 public int getApplicationEnabledSetting(String packageName, int userId) { 15124 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15125 int uid = Binder.getCallingUid(); 15126 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15127 // reader 15128 synchronized (mPackages) { 15129 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15130 } 15131 } 15132 15133 @Override 15134 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15135 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15136 int uid = Binder.getCallingUid(); 15137 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15138 // reader 15139 synchronized (mPackages) { 15140 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15141 } 15142 } 15143 15144 @Override 15145 public void enterSafeMode() { 15146 enforceSystemOrRoot("Only the system can request entering safe mode"); 15147 15148 if (!mSystemReady) { 15149 mSafeMode = true; 15150 } 15151 } 15152 15153 @Override 15154 public void systemReady() { 15155 mSystemReady = true; 15156 15157 // Read the compatibilty setting when the system is ready. 15158 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15159 mContext.getContentResolver(), 15160 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15161 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15162 if (DEBUG_SETTINGS) { 15163 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15164 } 15165 15166 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15167 15168 synchronized (mPackages) { 15169 // Verify that all of the preferred activity components actually 15170 // exist. It is possible for applications to be updated and at 15171 // that point remove a previously declared activity component that 15172 // had been set as a preferred activity. We try to clean this up 15173 // the next time we encounter that preferred activity, but it is 15174 // possible for the user flow to never be able to return to that 15175 // situation so here we do a sanity check to make sure we haven't 15176 // left any junk around. 15177 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15178 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15179 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15180 removed.clear(); 15181 for (PreferredActivity pa : pir.filterSet()) { 15182 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15183 removed.add(pa); 15184 } 15185 } 15186 if (removed.size() > 0) { 15187 for (int r=0; r<removed.size(); r++) { 15188 PreferredActivity pa = removed.get(r); 15189 Slog.w(TAG, "Removing dangling preferred activity: " 15190 + pa.mPref.mComponent); 15191 pir.removeFilter(pa); 15192 } 15193 mSettings.writePackageRestrictionsLPr( 15194 mSettings.mPreferredActivities.keyAt(i)); 15195 } 15196 } 15197 15198 for (int userId : UserManagerService.getInstance().getUserIds()) { 15199 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15200 grantPermissionsUserIds = ArrayUtils.appendInt( 15201 grantPermissionsUserIds, userId); 15202 } 15203 } 15204 } 15205 sUserManager.systemReady(); 15206 15207 // If we upgraded grant all default permissions before kicking off. 15208 for (int userId : grantPermissionsUserIds) { 15209 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15210 } 15211 15212 // Kick off any messages waiting for system ready 15213 if (mPostSystemReadyMessages != null) { 15214 for (Message msg : mPostSystemReadyMessages) { 15215 msg.sendToTarget(); 15216 } 15217 mPostSystemReadyMessages = null; 15218 } 15219 15220 // Watch for external volumes that come and go over time 15221 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15222 storage.registerListener(mStorageListener); 15223 15224 mInstallerService.systemReady(); 15225 mPackageDexOptimizer.systemReady(); 15226 15227 MountServiceInternal mountServiceInternal = LocalServices.getService( 15228 MountServiceInternal.class); 15229 mountServiceInternal.addExternalStoragePolicy( 15230 new MountServiceInternal.ExternalStorageMountPolicy() { 15231 @Override 15232 public int getMountMode(int uid, String packageName) { 15233 if (Process.isIsolated(uid)) { 15234 return Zygote.MOUNT_EXTERNAL_NONE; 15235 } 15236 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15237 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15238 } 15239 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15240 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15241 } 15242 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15243 return Zygote.MOUNT_EXTERNAL_READ; 15244 } 15245 return Zygote.MOUNT_EXTERNAL_WRITE; 15246 } 15247 15248 @Override 15249 public boolean hasExternalStorage(int uid, String packageName) { 15250 return true; 15251 } 15252 }); 15253 } 15254 15255 @Override 15256 public boolean isSafeMode() { 15257 return mSafeMode; 15258 } 15259 15260 @Override 15261 public boolean hasSystemUidErrors() { 15262 return mHasSystemUidErrors; 15263 } 15264 15265 static String arrayToString(int[] array) { 15266 StringBuffer buf = new StringBuffer(128); 15267 buf.append('['); 15268 if (array != null) { 15269 for (int i=0; i<array.length; i++) { 15270 if (i > 0) buf.append(", "); 15271 buf.append(array[i]); 15272 } 15273 } 15274 buf.append(']'); 15275 return buf.toString(); 15276 } 15277 15278 static class DumpState { 15279 public static final int DUMP_LIBS = 1 << 0; 15280 public static final int DUMP_FEATURES = 1 << 1; 15281 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15282 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15283 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15284 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15285 public static final int DUMP_PERMISSIONS = 1 << 6; 15286 public static final int DUMP_PACKAGES = 1 << 7; 15287 public static final int DUMP_SHARED_USERS = 1 << 8; 15288 public static final int DUMP_MESSAGES = 1 << 9; 15289 public static final int DUMP_PROVIDERS = 1 << 10; 15290 public static final int DUMP_VERIFIERS = 1 << 11; 15291 public static final int DUMP_PREFERRED = 1 << 12; 15292 public static final int DUMP_PREFERRED_XML = 1 << 13; 15293 public static final int DUMP_KEYSETS = 1 << 14; 15294 public static final int DUMP_VERSION = 1 << 15; 15295 public static final int DUMP_INSTALLS = 1 << 16; 15296 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15297 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15298 15299 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15300 15301 private int mTypes; 15302 15303 private int mOptions; 15304 15305 private boolean mTitlePrinted; 15306 15307 private SharedUserSetting mSharedUser; 15308 15309 public boolean isDumping(int type) { 15310 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15311 return true; 15312 } 15313 15314 return (mTypes & type) != 0; 15315 } 15316 15317 public void setDump(int type) { 15318 mTypes |= type; 15319 } 15320 15321 public boolean isOptionEnabled(int option) { 15322 return (mOptions & option) != 0; 15323 } 15324 15325 public void setOptionEnabled(int option) { 15326 mOptions |= option; 15327 } 15328 15329 public boolean onTitlePrinted() { 15330 final boolean printed = mTitlePrinted; 15331 mTitlePrinted = true; 15332 return printed; 15333 } 15334 15335 public boolean getTitlePrinted() { 15336 return mTitlePrinted; 15337 } 15338 15339 public void setTitlePrinted(boolean enabled) { 15340 mTitlePrinted = enabled; 15341 } 15342 15343 public SharedUserSetting getSharedUser() { 15344 return mSharedUser; 15345 } 15346 15347 public void setSharedUser(SharedUserSetting user) { 15348 mSharedUser = user; 15349 } 15350 } 15351 15352 @Override 15353 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15354 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15355 (new PackageManagerShellCommand(this)).exec( 15356 this, in, out, err, args, resultReceiver); 15357 } 15358 15359 @Override 15360 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15361 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15362 != PackageManager.PERMISSION_GRANTED) { 15363 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15364 + Binder.getCallingPid() 15365 + ", uid=" + Binder.getCallingUid() 15366 + " without permission " 15367 + android.Manifest.permission.DUMP); 15368 return; 15369 } 15370 15371 DumpState dumpState = new DumpState(); 15372 boolean fullPreferred = false; 15373 boolean checkin = false; 15374 15375 String packageName = null; 15376 ArraySet<String> permissionNames = null; 15377 15378 int opti = 0; 15379 while (opti < args.length) { 15380 String opt = args[opti]; 15381 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15382 break; 15383 } 15384 opti++; 15385 15386 if ("-a".equals(opt)) { 15387 // Right now we only know how to print all. 15388 } else if ("-h".equals(opt)) { 15389 pw.println("Package manager dump options:"); 15390 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15391 pw.println(" --checkin: dump for a checkin"); 15392 pw.println(" -f: print details of intent filters"); 15393 pw.println(" -h: print this help"); 15394 pw.println(" cmd may be one of:"); 15395 pw.println(" l[ibraries]: list known shared libraries"); 15396 pw.println(" f[eatures]: list device features"); 15397 pw.println(" k[eysets]: print known keysets"); 15398 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15399 pw.println(" perm[issions]: dump permissions"); 15400 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15401 pw.println(" pref[erred]: print preferred package settings"); 15402 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15403 pw.println(" prov[iders]: dump content providers"); 15404 pw.println(" p[ackages]: dump installed packages"); 15405 pw.println(" s[hared-users]: dump shared user IDs"); 15406 pw.println(" m[essages]: print collected runtime messages"); 15407 pw.println(" v[erifiers]: print package verifier info"); 15408 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15409 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15410 pw.println(" version: print database version info"); 15411 pw.println(" write: write current settings now"); 15412 pw.println(" installs: details about install sessions"); 15413 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15414 pw.println(" <package.name>: info about given package"); 15415 return; 15416 } else if ("--checkin".equals(opt)) { 15417 checkin = true; 15418 } else if ("-f".equals(opt)) { 15419 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15420 } else { 15421 pw.println("Unknown argument: " + opt + "; use -h for help"); 15422 } 15423 } 15424 15425 // Is the caller requesting to dump a particular piece of data? 15426 if (opti < args.length) { 15427 String cmd = args[opti]; 15428 opti++; 15429 // Is this a package name? 15430 if ("android".equals(cmd) || cmd.contains(".")) { 15431 packageName = cmd; 15432 // When dumping a single package, we always dump all of its 15433 // filter information since the amount of data will be reasonable. 15434 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15435 } else if ("check-permission".equals(cmd)) { 15436 if (opti >= args.length) { 15437 pw.println("Error: check-permission missing permission argument"); 15438 return; 15439 } 15440 String perm = args[opti]; 15441 opti++; 15442 if (opti >= args.length) { 15443 pw.println("Error: check-permission missing package argument"); 15444 return; 15445 } 15446 String pkg = args[opti]; 15447 opti++; 15448 int user = UserHandle.getUserId(Binder.getCallingUid()); 15449 if (opti < args.length) { 15450 try { 15451 user = Integer.parseInt(args[opti]); 15452 } catch (NumberFormatException e) { 15453 pw.println("Error: check-permission user argument is not a number: " 15454 + args[opti]); 15455 return; 15456 } 15457 } 15458 pw.println(checkPermission(perm, pkg, user)); 15459 return; 15460 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15461 dumpState.setDump(DumpState.DUMP_LIBS); 15462 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15463 dumpState.setDump(DumpState.DUMP_FEATURES); 15464 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15465 if (opti >= args.length) { 15466 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15467 | DumpState.DUMP_SERVICE_RESOLVERS 15468 | DumpState.DUMP_RECEIVER_RESOLVERS 15469 | DumpState.DUMP_CONTENT_RESOLVERS); 15470 } else { 15471 while (opti < args.length) { 15472 String name = args[opti]; 15473 if ("a".equals(name) || "activity".equals(name)) { 15474 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15475 } else if ("s".equals(name) || "service".equals(name)) { 15476 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15477 } else if ("r".equals(name) || "receiver".equals(name)) { 15478 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15479 } else if ("c".equals(name) || "content".equals(name)) { 15480 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15481 } else { 15482 pw.println("Error: unknown resolver table type: " + name); 15483 return; 15484 } 15485 opti++; 15486 } 15487 } 15488 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15489 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15490 } else if ("permission".equals(cmd)) { 15491 if (opti >= args.length) { 15492 pw.println("Error: permission requires permission name"); 15493 return; 15494 } 15495 permissionNames = new ArraySet<>(); 15496 while (opti < args.length) { 15497 permissionNames.add(args[opti]); 15498 opti++; 15499 } 15500 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15501 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15502 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15503 dumpState.setDump(DumpState.DUMP_PREFERRED); 15504 } else if ("preferred-xml".equals(cmd)) { 15505 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15506 if (opti < args.length && "--full".equals(args[opti])) { 15507 fullPreferred = true; 15508 opti++; 15509 } 15510 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15511 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15512 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15513 dumpState.setDump(DumpState.DUMP_PACKAGES); 15514 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15515 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15516 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15517 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15518 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15519 dumpState.setDump(DumpState.DUMP_MESSAGES); 15520 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15521 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15522 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15523 || "intent-filter-verifiers".equals(cmd)) { 15524 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15525 } else if ("version".equals(cmd)) { 15526 dumpState.setDump(DumpState.DUMP_VERSION); 15527 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15528 dumpState.setDump(DumpState.DUMP_KEYSETS); 15529 } else if ("installs".equals(cmd)) { 15530 dumpState.setDump(DumpState.DUMP_INSTALLS); 15531 } else if ("write".equals(cmd)) { 15532 synchronized (mPackages) { 15533 mSettings.writeLPr(); 15534 pw.println("Settings written."); 15535 return; 15536 } 15537 } 15538 } 15539 15540 if (checkin) { 15541 pw.println("vers,1"); 15542 } 15543 15544 // reader 15545 synchronized (mPackages) { 15546 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15547 if (!checkin) { 15548 if (dumpState.onTitlePrinted()) 15549 pw.println(); 15550 pw.println("Database versions:"); 15551 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15552 } 15553 } 15554 15555 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15556 if (!checkin) { 15557 if (dumpState.onTitlePrinted()) 15558 pw.println(); 15559 pw.println("Verifiers:"); 15560 pw.print(" Required: "); 15561 pw.print(mRequiredVerifierPackage); 15562 pw.print(" (uid="); 15563 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15564 pw.println(")"); 15565 } else if (mRequiredVerifierPackage != null) { 15566 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15567 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15568 } 15569 } 15570 15571 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15572 packageName == null) { 15573 if (mIntentFilterVerifierComponent != null) { 15574 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15575 if (!checkin) { 15576 if (dumpState.onTitlePrinted()) 15577 pw.println(); 15578 pw.println("Intent Filter Verifier:"); 15579 pw.print(" Using: "); 15580 pw.print(verifierPackageName); 15581 pw.print(" (uid="); 15582 pw.print(getPackageUid(verifierPackageName, 0)); 15583 pw.println(")"); 15584 } else if (verifierPackageName != null) { 15585 pw.print("ifv,"); pw.print(verifierPackageName); 15586 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15587 } 15588 } else { 15589 pw.println(); 15590 pw.println("No Intent Filter Verifier available!"); 15591 } 15592 } 15593 15594 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15595 boolean printedHeader = false; 15596 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15597 while (it.hasNext()) { 15598 String name = it.next(); 15599 SharedLibraryEntry ent = mSharedLibraries.get(name); 15600 if (!checkin) { 15601 if (!printedHeader) { 15602 if (dumpState.onTitlePrinted()) 15603 pw.println(); 15604 pw.println("Libraries:"); 15605 printedHeader = true; 15606 } 15607 pw.print(" "); 15608 } else { 15609 pw.print("lib,"); 15610 } 15611 pw.print(name); 15612 if (!checkin) { 15613 pw.print(" -> "); 15614 } 15615 if (ent.path != null) { 15616 if (!checkin) { 15617 pw.print("(jar) "); 15618 pw.print(ent.path); 15619 } else { 15620 pw.print(",jar,"); 15621 pw.print(ent.path); 15622 } 15623 } else { 15624 if (!checkin) { 15625 pw.print("(apk) "); 15626 pw.print(ent.apk); 15627 } else { 15628 pw.print(",apk,"); 15629 pw.print(ent.apk); 15630 } 15631 } 15632 pw.println(); 15633 } 15634 } 15635 15636 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15637 if (dumpState.onTitlePrinted()) 15638 pw.println(); 15639 if (!checkin) { 15640 pw.println("Features:"); 15641 } 15642 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15643 while (it.hasNext()) { 15644 String name = it.next(); 15645 if (!checkin) { 15646 pw.print(" "); 15647 } else { 15648 pw.print("feat,"); 15649 } 15650 pw.println(name); 15651 } 15652 } 15653 15654 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15655 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15656 : "Activity Resolver Table:", " ", packageName, 15657 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15658 dumpState.setTitlePrinted(true); 15659 } 15660 } 15661 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15662 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15663 : "Receiver Resolver Table:", " ", packageName, 15664 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15665 dumpState.setTitlePrinted(true); 15666 } 15667 } 15668 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15669 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15670 : "Service Resolver Table:", " ", packageName, 15671 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15672 dumpState.setTitlePrinted(true); 15673 } 15674 } 15675 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15676 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15677 : "Provider Resolver Table:", " ", packageName, 15678 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15679 dumpState.setTitlePrinted(true); 15680 } 15681 } 15682 15683 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15684 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15685 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15686 int user = mSettings.mPreferredActivities.keyAt(i); 15687 if (pir.dump(pw, 15688 dumpState.getTitlePrinted() 15689 ? "\nPreferred Activities User " + user + ":" 15690 : "Preferred Activities User " + user + ":", " ", 15691 packageName, true, false)) { 15692 dumpState.setTitlePrinted(true); 15693 } 15694 } 15695 } 15696 15697 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15698 pw.flush(); 15699 FileOutputStream fout = new FileOutputStream(fd); 15700 BufferedOutputStream str = new BufferedOutputStream(fout); 15701 XmlSerializer serializer = new FastXmlSerializer(); 15702 try { 15703 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15704 serializer.startDocument(null, true); 15705 serializer.setFeature( 15706 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15707 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15708 serializer.endDocument(); 15709 serializer.flush(); 15710 } catch (IllegalArgumentException e) { 15711 pw.println("Failed writing: " + e); 15712 } catch (IllegalStateException e) { 15713 pw.println("Failed writing: " + e); 15714 } catch (IOException e) { 15715 pw.println("Failed writing: " + e); 15716 } 15717 } 15718 15719 if (!checkin 15720 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15721 && packageName == null) { 15722 pw.println(); 15723 int count = mSettings.mPackages.size(); 15724 if (count == 0) { 15725 pw.println("No applications!"); 15726 pw.println(); 15727 } else { 15728 final String prefix = " "; 15729 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15730 if (allPackageSettings.size() == 0) { 15731 pw.println("No domain preferred apps!"); 15732 pw.println(); 15733 } else { 15734 pw.println("App verification status:"); 15735 pw.println(); 15736 count = 0; 15737 for (PackageSetting ps : allPackageSettings) { 15738 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15739 if (ivi == null || ivi.getPackageName() == null) continue; 15740 pw.println(prefix + "Package: " + ivi.getPackageName()); 15741 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15742 pw.println(prefix + "Status: " + ivi.getStatusString()); 15743 pw.println(); 15744 count++; 15745 } 15746 if (count == 0) { 15747 pw.println(prefix + "No app verification established."); 15748 pw.println(); 15749 } 15750 for (int userId : sUserManager.getUserIds()) { 15751 pw.println("App linkages for user " + userId + ":"); 15752 pw.println(); 15753 count = 0; 15754 for (PackageSetting ps : allPackageSettings) { 15755 final long status = ps.getDomainVerificationStatusForUser(userId); 15756 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15757 continue; 15758 } 15759 pw.println(prefix + "Package: " + ps.name); 15760 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15761 String statusStr = IntentFilterVerificationInfo. 15762 getStatusStringFromValue(status); 15763 pw.println(prefix + "Status: " + statusStr); 15764 pw.println(); 15765 count++; 15766 } 15767 if (count == 0) { 15768 pw.println(prefix + "No configured app linkages."); 15769 pw.println(); 15770 } 15771 } 15772 } 15773 } 15774 } 15775 15776 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15777 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15778 if (packageName == null && permissionNames == null) { 15779 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15780 if (iperm == 0) { 15781 if (dumpState.onTitlePrinted()) 15782 pw.println(); 15783 pw.println("AppOp Permissions:"); 15784 } 15785 pw.print(" AppOp Permission "); 15786 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15787 pw.println(":"); 15788 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15789 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15790 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15791 } 15792 } 15793 } 15794 } 15795 15796 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15797 boolean printedSomething = false; 15798 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15799 if (packageName != null && !packageName.equals(p.info.packageName)) { 15800 continue; 15801 } 15802 if (!printedSomething) { 15803 if (dumpState.onTitlePrinted()) 15804 pw.println(); 15805 pw.println("Registered ContentProviders:"); 15806 printedSomething = true; 15807 } 15808 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15809 pw.print(" "); pw.println(p.toString()); 15810 } 15811 printedSomething = false; 15812 for (Map.Entry<String, PackageParser.Provider> entry : 15813 mProvidersByAuthority.entrySet()) { 15814 PackageParser.Provider p = entry.getValue(); 15815 if (packageName != null && !packageName.equals(p.info.packageName)) { 15816 continue; 15817 } 15818 if (!printedSomething) { 15819 if (dumpState.onTitlePrinted()) 15820 pw.println(); 15821 pw.println("ContentProvider Authorities:"); 15822 printedSomething = true; 15823 } 15824 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15825 pw.print(" "); pw.println(p.toString()); 15826 if (p.info != null && p.info.applicationInfo != null) { 15827 final String appInfo = p.info.applicationInfo.toString(); 15828 pw.print(" applicationInfo="); pw.println(appInfo); 15829 } 15830 } 15831 } 15832 15833 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15834 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15835 } 15836 15837 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15838 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15839 } 15840 15841 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15842 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15843 } 15844 15845 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15846 // XXX should handle packageName != null by dumping only install data that 15847 // the given package is involved with. 15848 if (dumpState.onTitlePrinted()) pw.println(); 15849 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15850 } 15851 15852 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15853 if (dumpState.onTitlePrinted()) pw.println(); 15854 mSettings.dumpReadMessagesLPr(pw, dumpState); 15855 15856 pw.println(); 15857 pw.println("Package warning 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.println(line); 15865 } 15866 } catch (IOException ignored) { 15867 } finally { 15868 IoUtils.closeQuietly(in); 15869 } 15870 } 15871 15872 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15873 BufferedReader in = null; 15874 String line = null; 15875 try { 15876 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15877 while ((line = in.readLine()) != null) { 15878 if (line.contains("ignored: updated version")) continue; 15879 pw.print("msg,"); 15880 pw.println(line); 15881 } 15882 } catch (IOException ignored) { 15883 } finally { 15884 IoUtils.closeQuietly(in); 15885 } 15886 } 15887 } 15888 } 15889 15890 private String dumpDomainString(String packageName) { 15891 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15892 List<IntentFilter> filters = getAllIntentFilters(packageName); 15893 15894 ArraySet<String> result = new ArraySet<>(); 15895 if (iviList.size() > 0) { 15896 for (IntentFilterVerificationInfo ivi : iviList) { 15897 for (String host : ivi.getDomains()) { 15898 result.add(host); 15899 } 15900 } 15901 } 15902 if (filters != null && filters.size() > 0) { 15903 for (IntentFilter filter : filters) { 15904 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15905 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15906 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15907 result.addAll(filter.getHostsList()); 15908 } 15909 } 15910 } 15911 15912 StringBuilder sb = new StringBuilder(result.size() * 16); 15913 for (String domain : result) { 15914 if (sb.length() > 0) sb.append(" "); 15915 sb.append(domain); 15916 } 15917 return sb.toString(); 15918 } 15919 15920 // ------- apps on sdcard specific code ------- 15921 static final boolean DEBUG_SD_INSTALL = false; 15922 15923 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15924 15925 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15926 15927 private boolean mMediaMounted = false; 15928 15929 static String getEncryptKey() { 15930 try { 15931 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15932 SD_ENCRYPTION_KEYSTORE_NAME); 15933 if (sdEncKey == null) { 15934 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15935 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15936 if (sdEncKey == null) { 15937 Slog.e(TAG, "Failed to create encryption keys"); 15938 return null; 15939 } 15940 } 15941 return sdEncKey; 15942 } catch (NoSuchAlgorithmException nsae) { 15943 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15944 return null; 15945 } catch (IOException ioe) { 15946 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15947 return null; 15948 } 15949 } 15950 15951 /* 15952 * Update media status on PackageManager. 15953 */ 15954 @Override 15955 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15956 int callingUid = Binder.getCallingUid(); 15957 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15958 throw new SecurityException("Media status can only be updated by the system"); 15959 } 15960 // reader; this apparently protects mMediaMounted, but should probably 15961 // be a different lock in that case. 15962 synchronized (mPackages) { 15963 Log.i(TAG, "Updating external media status from " 15964 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15965 + (mediaStatus ? "mounted" : "unmounted")); 15966 if (DEBUG_SD_INSTALL) 15967 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15968 + ", mMediaMounted=" + mMediaMounted); 15969 if (mediaStatus == mMediaMounted) { 15970 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15971 : 0, -1); 15972 mHandler.sendMessage(msg); 15973 return; 15974 } 15975 mMediaMounted = mediaStatus; 15976 } 15977 // Queue up an async operation since the package installation may take a 15978 // little while. 15979 mHandler.post(new Runnable() { 15980 public void run() { 15981 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15982 } 15983 }); 15984 } 15985 15986 /** 15987 * Called by MountService when the initial ASECs to scan are available. 15988 * Should block until all the ASEC containers are finished being scanned. 15989 */ 15990 public void scanAvailableAsecs() { 15991 updateExternalMediaStatusInner(true, false, false); 15992 if (mShouldRestoreconData) { 15993 SELinuxMMAC.setRestoreconDone(); 15994 mShouldRestoreconData = false; 15995 } 15996 } 15997 15998 /* 15999 * Collect information of applications on external media, map them against 16000 * existing containers and update information based on current mount status. 16001 * Please note that we always have to report status if reportStatus has been 16002 * set to true especially when unloading packages. 16003 */ 16004 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16005 boolean externalStorage) { 16006 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16007 int[] uidArr = EmptyArray.INT; 16008 16009 final String[] list = PackageHelper.getSecureContainerList(); 16010 if (ArrayUtils.isEmpty(list)) { 16011 Log.i(TAG, "No secure containers found"); 16012 } else { 16013 // Process list of secure containers and categorize them 16014 // as active or stale based on their package internal state. 16015 16016 // reader 16017 synchronized (mPackages) { 16018 for (String cid : list) { 16019 // Leave stages untouched for now; installer service owns them 16020 if (PackageInstallerService.isStageName(cid)) continue; 16021 16022 if (DEBUG_SD_INSTALL) 16023 Log.i(TAG, "Processing container " + cid); 16024 String pkgName = getAsecPackageName(cid); 16025 if (pkgName == null) { 16026 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16027 continue; 16028 } 16029 if (DEBUG_SD_INSTALL) 16030 Log.i(TAG, "Looking for pkg : " + pkgName); 16031 16032 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16033 if (ps == null) { 16034 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16035 continue; 16036 } 16037 16038 /* 16039 * Skip packages that are not external if we're unmounting 16040 * external storage. 16041 */ 16042 if (externalStorage && !isMounted && !isExternal(ps)) { 16043 continue; 16044 } 16045 16046 final AsecInstallArgs args = new AsecInstallArgs(cid, 16047 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16048 // The package status is changed only if the code path 16049 // matches between settings and the container id. 16050 if (ps.codePathString != null 16051 && ps.codePathString.startsWith(args.getCodePath())) { 16052 if (DEBUG_SD_INSTALL) { 16053 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16054 + " at code path: " + ps.codePathString); 16055 } 16056 16057 // We do have a valid package installed on sdcard 16058 processCids.put(args, ps.codePathString); 16059 final int uid = ps.appId; 16060 if (uid != -1) { 16061 uidArr = ArrayUtils.appendInt(uidArr, uid); 16062 } 16063 } else { 16064 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16065 + ps.codePathString); 16066 } 16067 } 16068 } 16069 16070 Arrays.sort(uidArr); 16071 } 16072 16073 // Process packages with valid entries. 16074 if (isMounted) { 16075 if (DEBUG_SD_INSTALL) 16076 Log.i(TAG, "Loading packages"); 16077 loadMediaPackages(processCids, uidArr, externalStorage); 16078 startCleaningPackages(); 16079 mInstallerService.onSecureContainersAvailable(); 16080 } else { 16081 if (DEBUG_SD_INSTALL) 16082 Log.i(TAG, "Unloading packages"); 16083 unloadMediaPackages(processCids, uidArr, reportStatus); 16084 } 16085 } 16086 16087 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16088 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16089 final int size = infos.size(); 16090 final String[] packageNames = new String[size]; 16091 final int[] packageUids = new int[size]; 16092 for (int i = 0; i < size; i++) { 16093 final ApplicationInfo info = infos.get(i); 16094 packageNames[i] = info.packageName; 16095 packageUids[i] = info.uid; 16096 } 16097 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16098 finishedReceiver); 16099 } 16100 16101 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16102 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16103 sendResourcesChangedBroadcast(mediaStatus, replacing, 16104 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16105 } 16106 16107 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16108 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16109 int size = pkgList.length; 16110 if (size > 0) { 16111 // Send broadcasts here 16112 Bundle extras = new Bundle(); 16113 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16114 if (uidArr != null) { 16115 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16116 } 16117 if (replacing) { 16118 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16119 } 16120 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16121 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16122 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16123 } 16124 } 16125 16126 /* 16127 * Look at potentially valid container ids from processCids If package 16128 * information doesn't match the one on record or package scanning fails, 16129 * the cid is added to list of removeCids. We currently don't delete stale 16130 * containers. 16131 */ 16132 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16133 boolean externalStorage) { 16134 ArrayList<String> pkgList = new ArrayList<String>(); 16135 Set<AsecInstallArgs> keys = processCids.keySet(); 16136 16137 for (AsecInstallArgs args : keys) { 16138 String codePath = processCids.get(args); 16139 if (DEBUG_SD_INSTALL) 16140 Log.i(TAG, "Loading container : " + args.cid); 16141 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16142 try { 16143 // Make sure there are no container errors first. 16144 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16145 Slog.e(TAG, "Failed to mount cid : " + args.cid 16146 + " when installing from sdcard"); 16147 continue; 16148 } 16149 // Check code path here. 16150 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16151 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16152 + " does not match one in settings " + codePath); 16153 continue; 16154 } 16155 // Parse package 16156 int parseFlags = mDefParseFlags; 16157 if (args.isExternalAsec()) { 16158 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16159 } 16160 if (args.isFwdLocked()) { 16161 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16162 } 16163 16164 synchronized (mInstallLock) { 16165 PackageParser.Package pkg = null; 16166 try { 16167 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16168 } catch (PackageManagerException e) { 16169 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16170 } 16171 // Scan the package 16172 if (pkg != null) { 16173 /* 16174 * TODO why is the lock being held? doPostInstall is 16175 * called in other places without the lock. This needs 16176 * to be straightened out. 16177 */ 16178 // writer 16179 synchronized (mPackages) { 16180 retCode = PackageManager.INSTALL_SUCCEEDED; 16181 pkgList.add(pkg.packageName); 16182 // Post process args 16183 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16184 pkg.applicationInfo.uid); 16185 } 16186 } else { 16187 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16188 } 16189 } 16190 16191 } finally { 16192 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16193 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16194 } 16195 } 16196 } 16197 // writer 16198 synchronized (mPackages) { 16199 // If the platform SDK has changed since the last time we booted, 16200 // we need to re-grant app permission to catch any new ones that 16201 // appear. This is really a hack, and means that apps can in some 16202 // cases get permissions that the user didn't initially explicitly 16203 // allow... it would be nice to have some better way to handle 16204 // this situation. 16205 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16206 : mSettings.getInternalVersion(); 16207 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16208 : StorageManager.UUID_PRIVATE_INTERNAL; 16209 16210 int updateFlags = UPDATE_PERMISSIONS_ALL; 16211 if (ver.sdkVersion != mSdkVersion) { 16212 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16213 + mSdkVersion + "; regranting permissions for external"); 16214 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16215 } 16216 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16217 16218 // Yay, everything is now upgraded 16219 ver.forceCurrent(); 16220 16221 // can downgrade to reader 16222 // Persist settings 16223 mSettings.writeLPr(); 16224 } 16225 // Send a broadcast to let everyone know we are done processing 16226 if (pkgList.size() > 0) { 16227 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16228 } 16229 } 16230 16231 /* 16232 * Utility method to unload a list of specified containers 16233 */ 16234 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16235 // Just unmount all valid containers. 16236 for (AsecInstallArgs arg : cidArgs) { 16237 synchronized (mInstallLock) { 16238 arg.doPostDeleteLI(false); 16239 } 16240 } 16241 } 16242 16243 /* 16244 * Unload packages mounted on external media. This involves deleting package 16245 * data from internal structures, sending broadcasts about diabled packages, 16246 * gc'ing to free up references, unmounting all secure containers 16247 * corresponding to packages on external media, and posting a 16248 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16249 * that we always have to post this message if status has been requested no 16250 * matter what. 16251 */ 16252 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16253 final boolean reportStatus) { 16254 if (DEBUG_SD_INSTALL) 16255 Log.i(TAG, "unloading media packages"); 16256 ArrayList<String> pkgList = new ArrayList<String>(); 16257 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16258 final Set<AsecInstallArgs> keys = processCids.keySet(); 16259 for (AsecInstallArgs args : keys) { 16260 String pkgName = args.getPackageName(); 16261 if (DEBUG_SD_INSTALL) 16262 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16263 // Delete package internally 16264 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16265 synchronized (mInstallLock) { 16266 boolean res = deletePackageLI(pkgName, null, false, null, null, 16267 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16268 if (res) { 16269 pkgList.add(pkgName); 16270 } else { 16271 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16272 failedList.add(args); 16273 } 16274 } 16275 } 16276 16277 // reader 16278 synchronized (mPackages) { 16279 // We didn't update the settings after removing each package; 16280 // write them now for all packages. 16281 mSettings.writeLPr(); 16282 } 16283 16284 // We have to absolutely send UPDATED_MEDIA_STATUS only 16285 // after confirming that all the receivers processed the ordered 16286 // broadcast when packages get disabled, force a gc to clean things up. 16287 // and unload all the containers. 16288 if (pkgList.size() > 0) { 16289 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16290 new IIntentReceiver.Stub() { 16291 public void performReceive(Intent intent, int resultCode, String data, 16292 Bundle extras, boolean ordered, boolean sticky, 16293 int sendingUser) throws RemoteException { 16294 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16295 reportStatus ? 1 : 0, 1, keys); 16296 mHandler.sendMessage(msg); 16297 } 16298 }); 16299 } else { 16300 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16301 keys); 16302 mHandler.sendMessage(msg); 16303 } 16304 } 16305 16306 private void loadPrivatePackages(final VolumeInfo vol) { 16307 mHandler.post(new Runnable() { 16308 @Override 16309 public void run() { 16310 loadPrivatePackagesInner(vol); 16311 } 16312 }); 16313 } 16314 16315 private void loadPrivatePackagesInner(VolumeInfo vol) { 16316 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16317 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16318 16319 final VersionInfo ver; 16320 final List<PackageSetting> packages; 16321 synchronized (mPackages) { 16322 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16323 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16324 } 16325 16326 for (PackageSetting ps : packages) { 16327 synchronized (mInstallLock) { 16328 final PackageParser.Package pkg; 16329 try { 16330 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16331 loaded.add(pkg.applicationInfo); 16332 } catch (PackageManagerException e) { 16333 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16334 } 16335 16336 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16337 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16338 } 16339 } 16340 } 16341 16342 synchronized (mPackages) { 16343 int updateFlags = UPDATE_PERMISSIONS_ALL; 16344 if (ver.sdkVersion != mSdkVersion) { 16345 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16346 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16347 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16348 } 16349 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16350 16351 // Yay, everything is now upgraded 16352 ver.forceCurrent(); 16353 16354 mSettings.writeLPr(); 16355 } 16356 16357 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16358 sendResourcesChangedBroadcast(true, false, loaded, null); 16359 } 16360 16361 private void unloadPrivatePackages(final VolumeInfo vol) { 16362 mHandler.post(new Runnable() { 16363 @Override 16364 public void run() { 16365 unloadPrivatePackagesInner(vol); 16366 } 16367 }); 16368 } 16369 16370 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16371 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16372 synchronized (mInstallLock) { 16373 synchronized (mPackages) { 16374 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16375 for (PackageSetting ps : packages) { 16376 if (ps.pkg == null) continue; 16377 16378 final ApplicationInfo info = ps.pkg.applicationInfo; 16379 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16380 if (deletePackageLI(ps.name, null, false, null, null, 16381 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16382 unloaded.add(info); 16383 } else { 16384 Slog.w(TAG, "Failed to unload " + ps.codePath); 16385 } 16386 } 16387 16388 mSettings.writeLPr(); 16389 } 16390 } 16391 16392 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16393 sendResourcesChangedBroadcast(false, false, unloaded, null); 16394 } 16395 16396 /** 16397 * Examine all users present on given mounted volume, and destroy data 16398 * belonging to users that are no longer valid, or whose user ID has been 16399 * recycled. 16400 */ 16401 private void reconcileUsers(String volumeUuid) { 16402 final File[] files = FileUtils 16403 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16404 for (File file : files) { 16405 if (!file.isDirectory()) continue; 16406 16407 final int userId; 16408 final UserInfo info; 16409 try { 16410 userId = Integer.parseInt(file.getName()); 16411 info = sUserManager.getUserInfo(userId); 16412 } catch (NumberFormatException e) { 16413 Slog.w(TAG, "Invalid user directory " + file); 16414 continue; 16415 } 16416 16417 boolean destroyUser = false; 16418 if (info == null) { 16419 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16420 + " because no matching user was found"); 16421 destroyUser = true; 16422 } else { 16423 try { 16424 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16425 } catch (IOException e) { 16426 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16427 + " because we failed to enforce serial number: " + e); 16428 destroyUser = true; 16429 } 16430 } 16431 16432 if (destroyUser) { 16433 synchronized (mInstallLock) { 16434 mInstaller.removeUserDataDirs(volumeUuid, userId); 16435 } 16436 } 16437 } 16438 16439 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16440 final UserManager um = mContext.getSystemService(UserManager.class); 16441 for (UserInfo user : um.getUsers()) { 16442 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16443 if (userDir.exists()) continue; 16444 16445 try { 16446 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 16447 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16448 } catch (IOException e) { 16449 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16450 } 16451 } 16452 } 16453 16454 /** 16455 * Examine all apps present on given mounted volume, and destroy apps that 16456 * aren't expected, either due to uninstallation or reinstallation on 16457 * another volume. 16458 */ 16459 private void reconcileApps(String volumeUuid) { 16460 final File[] files = FileUtils 16461 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16462 for (File file : files) { 16463 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16464 && !PackageInstallerService.isStageName(file.getName()); 16465 if (!isPackage) { 16466 // Ignore entries which are not packages 16467 continue; 16468 } 16469 16470 boolean destroyApp = false; 16471 String packageName = null; 16472 try { 16473 final PackageLite pkg = PackageParser.parsePackageLite(file, 16474 PackageParser.PARSE_MUST_BE_APK); 16475 packageName = pkg.packageName; 16476 16477 synchronized (mPackages) { 16478 final PackageSetting ps = mSettings.mPackages.get(packageName); 16479 if (ps == null) { 16480 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16481 + volumeUuid + " because we found no install record"); 16482 destroyApp = true; 16483 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16484 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16485 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16486 destroyApp = true; 16487 } 16488 } 16489 16490 } catch (PackageParserException e) { 16491 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16492 destroyApp = true; 16493 } 16494 16495 if (destroyApp) { 16496 synchronized (mInstallLock) { 16497 if (packageName != null) { 16498 removeDataDirsLI(volumeUuid, packageName); 16499 } 16500 if (file.isDirectory()) { 16501 mInstaller.rmPackageDir(file.getAbsolutePath()); 16502 } else { 16503 file.delete(); 16504 } 16505 } 16506 } 16507 } 16508 } 16509 16510 private void unfreezePackage(String packageName) { 16511 synchronized (mPackages) { 16512 final PackageSetting ps = mSettings.mPackages.get(packageName); 16513 if (ps != null) { 16514 ps.frozen = false; 16515 } 16516 } 16517 } 16518 16519 @Override 16520 public int movePackage(final String packageName, final String volumeUuid) { 16521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16522 16523 final int moveId = mNextMoveId.getAndIncrement(); 16524 mHandler.post(new Runnable() { 16525 @Override 16526 public void run() { 16527 try { 16528 movePackageInternal(packageName, volumeUuid, moveId); 16529 } catch (PackageManagerException e) { 16530 Slog.w(TAG, "Failed to move " + packageName, e); 16531 mMoveCallbacks.notifyStatusChanged(moveId, 16532 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16533 } 16534 } 16535 }); 16536 return moveId; 16537 } 16538 16539 private void movePackageInternal(final String packageName, final String volumeUuid, 16540 final int moveId) throws PackageManagerException { 16541 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16542 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16543 final PackageManager pm = mContext.getPackageManager(); 16544 16545 final boolean currentAsec; 16546 final String currentVolumeUuid; 16547 final File codeFile; 16548 final String installerPackageName; 16549 final String packageAbiOverride; 16550 final int appId; 16551 final String seinfo; 16552 final String label; 16553 16554 // reader 16555 synchronized (mPackages) { 16556 final PackageParser.Package pkg = mPackages.get(packageName); 16557 final PackageSetting ps = mSettings.mPackages.get(packageName); 16558 if (pkg == null || ps == null) { 16559 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16560 } 16561 16562 if (pkg.applicationInfo.isSystemApp()) { 16563 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16564 "Cannot move system application"); 16565 } 16566 16567 if (pkg.applicationInfo.isExternalAsec()) { 16568 currentAsec = true; 16569 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16570 } else if (pkg.applicationInfo.isForwardLocked()) { 16571 currentAsec = true; 16572 currentVolumeUuid = "forward_locked"; 16573 } else { 16574 currentAsec = false; 16575 currentVolumeUuid = ps.volumeUuid; 16576 16577 final File probe = new File(pkg.codePath); 16578 final File probeOat = new File(probe, "oat"); 16579 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16580 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16581 "Move only supported for modern cluster style installs"); 16582 } 16583 } 16584 16585 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16586 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16587 "Package already moved to " + volumeUuid); 16588 } 16589 16590 if (ps.frozen) { 16591 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16592 "Failed to move already frozen package"); 16593 } 16594 ps.frozen = true; 16595 16596 codeFile = new File(pkg.codePath); 16597 installerPackageName = ps.installerPackageName; 16598 packageAbiOverride = ps.cpuAbiOverrideString; 16599 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16600 seinfo = pkg.applicationInfo.seinfo; 16601 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16602 } 16603 16604 // Now that we're guarded by frozen state, kill app during move 16605 final long token = Binder.clearCallingIdentity(); 16606 try { 16607 killApplication(packageName, appId, "move pkg"); 16608 } finally { 16609 Binder.restoreCallingIdentity(token); 16610 } 16611 16612 final Bundle extras = new Bundle(); 16613 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16614 extras.putString(Intent.EXTRA_TITLE, label); 16615 mMoveCallbacks.notifyCreated(moveId, extras); 16616 16617 int installFlags; 16618 final boolean moveCompleteApp; 16619 final File measurePath; 16620 16621 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16622 installFlags = INSTALL_INTERNAL; 16623 moveCompleteApp = !currentAsec; 16624 measurePath = Environment.getDataAppDirectory(volumeUuid); 16625 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16626 installFlags = INSTALL_EXTERNAL; 16627 moveCompleteApp = false; 16628 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16629 } else { 16630 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16631 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16632 || !volume.isMountedWritable()) { 16633 unfreezePackage(packageName); 16634 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16635 "Move location not mounted private volume"); 16636 } 16637 16638 Preconditions.checkState(!currentAsec); 16639 16640 installFlags = INSTALL_INTERNAL; 16641 moveCompleteApp = true; 16642 measurePath = Environment.getDataAppDirectory(volumeUuid); 16643 } 16644 16645 final PackageStats stats = new PackageStats(null, -1); 16646 synchronized (mInstaller) { 16647 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16648 unfreezePackage(packageName); 16649 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16650 "Failed to measure package size"); 16651 } 16652 } 16653 16654 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16655 + stats.dataSize); 16656 16657 final long startFreeBytes = measurePath.getFreeSpace(); 16658 final long sizeBytes; 16659 if (moveCompleteApp) { 16660 sizeBytes = stats.codeSize + stats.dataSize; 16661 } else { 16662 sizeBytes = stats.codeSize; 16663 } 16664 16665 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16666 unfreezePackage(packageName); 16667 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16668 "Not enough free space to move"); 16669 } 16670 16671 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16672 16673 final CountDownLatch installedLatch = new CountDownLatch(1); 16674 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16675 @Override 16676 public void onUserActionRequired(Intent intent) throws RemoteException { 16677 throw new IllegalStateException(); 16678 } 16679 16680 @Override 16681 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16682 Bundle extras) throws RemoteException { 16683 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16684 + PackageManager.installStatusToString(returnCode, msg)); 16685 16686 installedLatch.countDown(); 16687 16688 // Regardless of success or failure of the move operation, 16689 // always unfreeze the package 16690 unfreezePackage(packageName); 16691 16692 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16693 switch (status) { 16694 case PackageInstaller.STATUS_SUCCESS: 16695 mMoveCallbacks.notifyStatusChanged(moveId, 16696 PackageManager.MOVE_SUCCEEDED); 16697 break; 16698 case PackageInstaller.STATUS_FAILURE_STORAGE: 16699 mMoveCallbacks.notifyStatusChanged(moveId, 16700 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16701 break; 16702 default: 16703 mMoveCallbacks.notifyStatusChanged(moveId, 16704 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16705 break; 16706 } 16707 } 16708 }; 16709 16710 final MoveInfo move; 16711 if (moveCompleteApp) { 16712 // Kick off a thread to report progress estimates 16713 new Thread() { 16714 @Override 16715 public void run() { 16716 while (true) { 16717 try { 16718 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16719 break; 16720 } 16721 } catch (InterruptedException ignored) { 16722 } 16723 16724 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16725 final int progress = 10 + (int) MathUtils.constrain( 16726 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16727 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16728 } 16729 } 16730 }.start(); 16731 16732 final String dataAppName = codeFile.getName(); 16733 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16734 dataAppName, appId, seinfo); 16735 } else { 16736 move = null; 16737 } 16738 16739 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16740 16741 final Message msg = mHandler.obtainMessage(INIT_COPY); 16742 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16743 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16744 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16745 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16746 msg.obj = params; 16747 16748 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16749 System.identityHashCode(msg.obj)); 16750 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16751 System.identityHashCode(msg.obj)); 16752 16753 mHandler.sendMessage(msg); 16754 } 16755 16756 @Override 16757 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16759 16760 final int realMoveId = mNextMoveId.getAndIncrement(); 16761 final Bundle extras = new Bundle(); 16762 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16763 mMoveCallbacks.notifyCreated(realMoveId, extras); 16764 16765 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16766 @Override 16767 public void onCreated(int moveId, Bundle extras) { 16768 // Ignored 16769 } 16770 16771 @Override 16772 public void onStatusChanged(int moveId, int status, long estMillis) { 16773 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16774 } 16775 }; 16776 16777 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16778 storage.setPrimaryStorageUuid(volumeUuid, callback); 16779 return realMoveId; 16780 } 16781 16782 @Override 16783 public int getMoveStatus(int moveId) { 16784 mContext.enforceCallingOrSelfPermission( 16785 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16786 return mMoveCallbacks.mLastStatus.get(moveId); 16787 } 16788 16789 @Override 16790 public void registerMoveCallback(IPackageMoveObserver callback) { 16791 mContext.enforceCallingOrSelfPermission( 16792 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16793 mMoveCallbacks.register(callback); 16794 } 16795 16796 @Override 16797 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16798 mContext.enforceCallingOrSelfPermission( 16799 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16800 mMoveCallbacks.unregister(callback); 16801 } 16802 16803 @Override 16804 public boolean setInstallLocation(int loc) { 16805 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16806 null); 16807 if (getInstallLocation() == loc) { 16808 return true; 16809 } 16810 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16811 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16812 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16813 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16814 return true; 16815 } 16816 return false; 16817 } 16818 16819 @Override 16820 public int getInstallLocation() { 16821 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16822 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16823 PackageHelper.APP_INSTALL_AUTO); 16824 } 16825 16826 /** Called by UserManagerService */ 16827 void cleanUpUser(UserManagerService userManager, int userHandle) { 16828 synchronized (mPackages) { 16829 mDirtyUsers.remove(userHandle); 16830 mUserNeedsBadging.delete(userHandle); 16831 mSettings.removeUserLPw(userHandle); 16832 mPendingBroadcasts.remove(userHandle); 16833 } 16834 synchronized (mInstallLock) { 16835 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16836 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16837 final String volumeUuid = vol.getFsUuid(); 16838 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16839 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16840 } 16841 synchronized (mPackages) { 16842 removeUnusedPackagesLILPw(userManager, userHandle); 16843 } 16844 } 16845 } 16846 16847 /** 16848 * We're removing userHandle and would like to remove any downloaded packages 16849 * that are no longer in use by any other user. 16850 * @param userHandle the user being removed 16851 */ 16852 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16853 final boolean DEBUG_CLEAN_APKS = false; 16854 int [] users = userManager.getUserIds(); 16855 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16856 while (psit.hasNext()) { 16857 PackageSetting ps = psit.next(); 16858 if (ps.pkg == null) { 16859 continue; 16860 } 16861 final String packageName = ps.pkg.packageName; 16862 // Skip over if system app 16863 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16864 continue; 16865 } 16866 if (DEBUG_CLEAN_APKS) { 16867 Slog.i(TAG, "Checking package " + packageName); 16868 } 16869 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16870 if (keep) { 16871 if (DEBUG_CLEAN_APKS) { 16872 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16873 } 16874 } else { 16875 for (int i = 0; i < users.length; i++) { 16876 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16877 keep = true; 16878 if (DEBUG_CLEAN_APKS) { 16879 Slog.i(TAG, " Keeping package " + packageName + " for user " 16880 + users[i]); 16881 } 16882 break; 16883 } 16884 } 16885 } 16886 if (!keep) { 16887 if (DEBUG_CLEAN_APKS) { 16888 Slog.i(TAG, " Removing package " + packageName); 16889 } 16890 mHandler.post(new Runnable() { 16891 public void run() { 16892 deletePackageX(packageName, userHandle, 0); 16893 } //end run 16894 }); 16895 } 16896 } 16897 } 16898 16899 /** Called by UserManagerService */ 16900 void createNewUser(int userHandle) { 16901 synchronized (mInstallLock) { 16902 mInstaller.createUserConfig(userHandle); 16903 mSettings.createNewUserLI(this, mInstaller, userHandle); 16904 } 16905 synchronized (mPackages) { 16906 applyFactoryDefaultBrowserLPw(userHandle); 16907 primeDomainVerificationsLPw(userHandle); 16908 } 16909 } 16910 16911 void newUserCreated(final int userHandle) { 16912 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16913 // If permission review for legacy apps is required, we represent 16914 // dagerous permissions for such apps as always granted runtime 16915 // permissions to keep per user flag state whether review is needed. 16916 // Hence, if a new user is added we have to propagate dangerous 16917 // permission grants for these legacy apps. 16918 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 16919 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 16920 | UPDATE_PERMISSIONS_REPLACE_ALL); 16921 } 16922 } 16923 16924 @Override 16925 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16926 mContext.enforceCallingOrSelfPermission( 16927 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16928 "Only package verification agents can read the verifier device identity"); 16929 16930 synchronized (mPackages) { 16931 return mSettings.getVerifierDeviceIdentityLPw(); 16932 } 16933 } 16934 16935 @Override 16936 public void setPermissionEnforced(String permission, boolean enforced) { 16937 // TODO: Now that we no longer change GID for storage, this should to away. 16938 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16939 "setPermissionEnforced"); 16940 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16941 synchronized (mPackages) { 16942 if (mSettings.mReadExternalStorageEnforced == null 16943 || mSettings.mReadExternalStorageEnforced != enforced) { 16944 mSettings.mReadExternalStorageEnforced = enforced; 16945 mSettings.writeLPr(); 16946 } 16947 } 16948 // kill any non-foreground processes so we restart them and 16949 // grant/revoke the GID. 16950 final IActivityManager am = ActivityManagerNative.getDefault(); 16951 if (am != null) { 16952 final long token = Binder.clearCallingIdentity(); 16953 try { 16954 am.killProcessesBelowForeground("setPermissionEnforcement"); 16955 } catch (RemoteException e) { 16956 } finally { 16957 Binder.restoreCallingIdentity(token); 16958 } 16959 } 16960 } else { 16961 throw new IllegalArgumentException("No selective enforcement for " + permission); 16962 } 16963 } 16964 16965 @Override 16966 @Deprecated 16967 public boolean isPermissionEnforced(String permission) { 16968 return true; 16969 } 16970 16971 @Override 16972 public boolean isStorageLow() { 16973 final long token = Binder.clearCallingIdentity(); 16974 try { 16975 final DeviceStorageMonitorInternal 16976 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16977 if (dsm != null) { 16978 return dsm.isMemoryLow(); 16979 } else { 16980 return false; 16981 } 16982 } finally { 16983 Binder.restoreCallingIdentity(token); 16984 } 16985 } 16986 16987 @Override 16988 public IPackageInstaller getPackageInstaller() { 16989 return mInstallerService; 16990 } 16991 16992 private boolean userNeedsBadging(int userId) { 16993 int index = mUserNeedsBadging.indexOfKey(userId); 16994 if (index < 0) { 16995 final UserInfo userInfo; 16996 final long token = Binder.clearCallingIdentity(); 16997 try { 16998 userInfo = sUserManager.getUserInfo(userId); 16999 } finally { 17000 Binder.restoreCallingIdentity(token); 17001 } 17002 final boolean b; 17003 if (userInfo != null && userInfo.isManagedProfile()) { 17004 b = true; 17005 } else { 17006 b = false; 17007 } 17008 mUserNeedsBadging.put(userId, b); 17009 return b; 17010 } 17011 return mUserNeedsBadging.valueAt(index); 17012 } 17013 17014 @Override 17015 public KeySet getKeySetByAlias(String packageName, String alias) { 17016 if (packageName == null || alias == null) { 17017 return null; 17018 } 17019 synchronized(mPackages) { 17020 final PackageParser.Package pkg = mPackages.get(packageName); 17021 if (pkg == null) { 17022 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17023 throw new IllegalArgumentException("Unknown package: " + packageName); 17024 } 17025 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17026 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17027 } 17028 } 17029 17030 @Override 17031 public KeySet getSigningKeySet(String packageName) { 17032 if (packageName == null) { 17033 return null; 17034 } 17035 synchronized(mPackages) { 17036 final PackageParser.Package pkg = mPackages.get(packageName); 17037 if (pkg == null) { 17038 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17039 throw new IllegalArgumentException("Unknown package: " + packageName); 17040 } 17041 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17042 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17043 throw new SecurityException("May not access signing KeySet of other apps."); 17044 } 17045 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17046 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17047 } 17048 } 17049 17050 @Override 17051 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17052 if (packageName == null || ks == null) { 17053 return false; 17054 } 17055 synchronized(mPackages) { 17056 final PackageParser.Package pkg = mPackages.get(packageName); 17057 if (pkg == null) { 17058 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17059 throw new IllegalArgumentException("Unknown package: " + packageName); 17060 } 17061 IBinder ksh = ks.getToken(); 17062 if (ksh instanceof KeySetHandle) { 17063 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17064 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17065 } 17066 return false; 17067 } 17068 } 17069 17070 @Override 17071 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17072 if (packageName == null || ks == null) { 17073 return false; 17074 } 17075 synchronized(mPackages) { 17076 final PackageParser.Package pkg = mPackages.get(packageName); 17077 if (pkg == null) { 17078 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17079 throw new IllegalArgumentException("Unknown package: " + packageName); 17080 } 17081 IBinder ksh = ks.getToken(); 17082 if (ksh instanceof KeySetHandle) { 17083 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17084 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17085 } 17086 return false; 17087 } 17088 } 17089 17090 private void deletePackageIfUnusedLPr(final String packageName) { 17091 PackageSetting ps = mSettings.mPackages.get(packageName); 17092 if (ps == null) { 17093 return; 17094 } 17095 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17096 // TODO Implement atomic delete if package is unused 17097 // It is currently possible that the package will be deleted even if it is installed 17098 // after this method returns. 17099 mHandler.post(new Runnable() { 17100 public void run() { 17101 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17102 } 17103 }); 17104 } 17105 } 17106 17107 /** 17108 * Check and throw if the given before/after packages would be considered a 17109 * downgrade. 17110 */ 17111 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17112 throws PackageManagerException { 17113 if (after.versionCode < before.mVersionCode) { 17114 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17115 "Update version code " + after.versionCode + " is older than current " 17116 + before.mVersionCode); 17117 } else if (after.versionCode == before.mVersionCode) { 17118 if (after.baseRevisionCode < before.baseRevisionCode) { 17119 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17120 "Update base revision code " + after.baseRevisionCode 17121 + " is older than current " + before.baseRevisionCode); 17122 } 17123 17124 if (!ArrayUtils.isEmpty(after.splitNames)) { 17125 for (int i = 0; i < after.splitNames.length; i++) { 17126 final String splitName = after.splitNames[i]; 17127 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17128 if (j != -1) { 17129 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17130 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17131 "Update split " + splitName + " revision code " 17132 + after.splitRevisionCodes[i] + " is older than current " 17133 + before.splitRevisionCodes[j]); 17134 } 17135 } 17136 } 17137 } 17138 } 17139 } 17140 17141 private static class MoveCallbacks extends Handler { 17142 private static final int MSG_CREATED = 1; 17143 private static final int MSG_STATUS_CHANGED = 2; 17144 17145 private final RemoteCallbackList<IPackageMoveObserver> 17146 mCallbacks = new RemoteCallbackList<>(); 17147 17148 private final SparseIntArray mLastStatus = new SparseIntArray(); 17149 17150 public MoveCallbacks(Looper looper) { 17151 super(looper); 17152 } 17153 17154 public void register(IPackageMoveObserver callback) { 17155 mCallbacks.register(callback); 17156 } 17157 17158 public void unregister(IPackageMoveObserver callback) { 17159 mCallbacks.unregister(callback); 17160 } 17161 17162 @Override 17163 public void handleMessage(Message msg) { 17164 final SomeArgs args = (SomeArgs) msg.obj; 17165 final int n = mCallbacks.beginBroadcast(); 17166 for (int i = 0; i < n; i++) { 17167 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17168 try { 17169 invokeCallback(callback, msg.what, args); 17170 } catch (RemoteException ignored) { 17171 } 17172 } 17173 mCallbacks.finishBroadcast(); 17174 args.recycle(); 17175 } 17176 17177 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17178 throws RemoteException { 17179 switch (what) { 17180 case MSG_CREATED: { 17181 callback.onCreated(args.argi1, (Bundle) args.arg2); 17182 break; 17183 } 17184 case MSG_STATUS_CHANGED: { 17185 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17186 break; 17187 } 17188 } 17189 } 17190 17191 private void notifyCreated(int moveId, Bundle extras) { 17192 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17193 17194 final SomeArgs args = SomeArgs.obtain(); 17195 args.argi1 = moveId; 17196 args.arg2 = extras; 17197 obtainMessage(MSG_CREATED, args).sendToTarget(); 17198 } 17199 17200 private void notifyStatusChanged(int moveId, int status) { 17201 notifyStatusChanged(moveId, status, -1); 17202 } 17203 17204 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17205 Slog.v(TAG, "Move " + moveId + " status " + status); 17206 17207 final SomeArgs args = SomeArgs.obtain(); 17208 args.argi1 = moveId; 17209 args.argi2 = status; 17210 args.arg3 = estMillis; 17211 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17212 17213 synchronized (mLastStatus) { 17214 mLastStatus.put(moveId, status); 17215 } 17216 } 17217 } 17218 17219 private final class OnPermissionChangeListeners extends Handler { 17220 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17221 17222 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17223 new RemoteCallbackList<>(); 17224 17225 public OnPermissionChangeListeners(Looper looper) { 17226 super(looper); 17227 } 17228 17229 @Override 17230 public void handleMessage(Message msg) { 17231 switch (msg.what) { 17232 case MSG_ON_PERMISSIONS_CHANGED: { 17233 final int uid = msg.arg1; 17234 handleOnPermissionsChanged(uid); 17235 } break; 17236 } 17237 } 17238 17239 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17240 mPermissionListeners.register(listener); 17241 17242 } 17243 17244 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17245 mPermissionListeners.unregister(listener); 17246 } 17247 17248 public void onPermissionsChanged(int uid) { 17249 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17250 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17251 } 17252 } 17253 17254 private void handleOnPermissionsChanged(int uid) { 17255 final int count = mPermissionListeners.beginBroadcast(); 17256 try { 17257 for (int i = 0; i < count; i++) { 17258 IOnPermissionsChangeListener callback = mPermissionListeners 17259 .getBroadcastItem(i); 17260 try { 17261 callback.onPermissionsChanged(uid); 17262 } catch (RemoteException e) { 17263 Log.e(TAG, "Permission listener is dead", e); 17264 } 17265 } 17266 } finally { 17267 mPermissionListeners.finishBroadcast(); 17268 } 17269 } 17270 } 17271 17272 private class PackageManagerInternalImpl extends PackageManagerInternal { 17273 @Override 17274 public void setLocationPackagesProvider(PackagesProvider provider) { 17275 synchronized (mPackages) { 17276 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17277 } 17278 } 17279 17280 @Override 17281 public void setImePackagesProvider(PackagesProvider provider) { 17282 synchronized (mPackages) { 17283 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17284 } 17285 } 17286 17287 @Override 17288 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17289 synchronized (mPackages) { 17290 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17291 } 17292 } 17293 17294 @Override 17295 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17296 synchronized (mPackages) { 17297 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17298 } 17299 } 17300 17301 @Override 17302 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17303 synchronized (mPackages) { 17304 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17305 } 17306 } 17307 17308 @Override 17309 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17310 synchronized (mPackages) { 17311 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17312 } 17313 } 17314 17315 @Override 17316 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17317 synchronized (mPackages) { 17318 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17319 } 17320 } 17321 17322 @Override 17323 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17324 synchronized (mPackages) { 17325 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17326 packageName, userId); 17327 } 17328 } 17329 17330 @Override 17331 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17332 synchronized (mPackages) { 17333 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17334 packageName, userId); 17335 } 17336 } 17337 17338 @Override 17339 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17340 synchronized (mPackages) { 17341 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17342 packageName, userId); 17343 } 17344 } 17345 17346 @Override 17347 public void setKeepUninstalledPackages(final List<String> packageList) { 17348 Preconditions.checkNotNull(packageList); 17349 List<String> removedFromList = null; 17350 synchronized (mPackages) { 17351 if (mKeepUninstalledPackages != null) { 17352 final int packagesCount = mKeepUninstalledPackages.size(); 17353 for (int i = 0; i < packagesCount; i++) { 17354 String oldPackage = mKeepUninstalledPackages.get(i); 17355 if (packageList != null && packageList.contains(oldPackage)) { 17356 continue; 17357 } 17358 if (removedFromList == null) { 17359 removedFromList = new ArrayList<>(); 17360 } 17361 removedFromList.add(oldPackage); 17362 } 17363 } 17364 mKeepUninstalledPackages = new ArrayList<>(packageList); 17365 if (removedFromList != null) { 17366 final int removedCount = removedFromList.size(); 17367 for (int i = 0; i < removedCount; i++) { 17368 deletePackageIfUnusedLPr(removedFromList.get(i)); 17369 } 17370 } 17371 } 17372 } 17373 17374 @Override 17375 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17376 synchronized (mPackages) { 17377 // If we do not support permission review, done. 17378 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17379 return false; 17380 } 17381 17382 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17383 if (packageSetting == null) { 17384 return false; 17385 } 17386 17387 // Permission review applies only to apps not supporting the new permission model. 17388 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17389 return false; 17390 } 17391 17392 // Legacy apps have the permission and get user consent on launch. 17393 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17394 return permissionsState.isPermissionReviewRequired(userId); 17395 } 17396 } 17397 } 17398 17399 @Override 17400 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17401 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17402 synchronized (mPackages) { 17403 final long identity = Binder.clearCallingIdentity(); 17404 try { 17405 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17406 packageNames, userId); 17407 } finally { 17408 Binder.restoreCallingIdentity(identity); 17409 } 17410 } 17411 } 17412 17413 private static void enforceSystemOrPhoneCaller(String tag) { 17414 int callingUid = Binder.getCallingUid(); 17415 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17416 throw new SecurityException( 17417 "Cannot call " + tag + " from UID " + callingUid); 17418 } 17419 } 17420} 17421