PackageManagerService.java revision cbeb114881c2bd3408ce302b0d48cb2449f1dcb0
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.EphemeralApplicationInfo; 109import android.content.pm.FeatureInfo; 110import android.content.pm.IOnPermissionsChangeListener; 111import android.content.pm.IPackageDataObserver; 112import android.content.pm.IPackageDeleteObserver; 113import android.content.pm.IPackageDeleteObserver2; 114import android.content.pm.IPackageInstallObserver2; 115import android.content.pm.IPackageInstaller; 116import android.content.pm.IPackageManager; 117import android.content.pm.IPackageMoveObserver; 118import android.content.pm.IPackageStatsObserver; 119import android.content.pm.InstrumentationInfo; 120import android.content.pm.IntentFilterVerificationInfo; 121import android.content.pm.KeySet; 122import android.content.pm.ManifestDigest; 123import android.content.pm.PackageCleanItem; 124import android.content.pm.PackageInfo; 125import android.content.pm.PackageInfoLite; 126import android.content.pm.PackageInstaller; 127import android.content.pm.PackageManager; 128import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 129import android.content.pm.PackageManagerInternal; 130import android.content.pm.PackageParser; 131import android.content.pm.PackageParser.ActivityIntentInfo; 132import android.content.pm.PackageParser.PackageLite; 133import android.content.pm.PackageParser.PackageParserException; 134import android.content.pm.PackageStats; 135import android.content.pm.PackageUserState; 136import android.content.pm.ParceledListSlice; 137import android.content.pm.PermissionGroupInfo; 138import android.content.pm.PermissionInfo; 139import android.content.pm.ProviderInfo; 140import android.content.pm.ResolveInfo; 141import android.content.pm.ServiceInfo; 142import android.content.pm.Signature; 143import android.content.pm.UserInfo; 144import android.content.pm.VerificationParams; 145import android.content.pm.VerifierDeviceIdentity; 146import android.content.pm.VerifierInfo; 147import android.content.res.Resources; 148import android.graphics.Bitmap; 149import android.hardware.display.DisplayManager; 150import android.net.Uri; 151import android.os.Debug; 152import android.os.Binder; 153import android.os.Build; 154import android.os.Bundle; 155import android.os.Environment; 156import android.os.Environment.UserEnvironment; 157import android.os.FileUtils; 158import android.os.Handler; 159import android.os.IBinder; 160import android.os.Looper; 161import android.os.Message; 162import android.os.Parcel; 163import android.os.ParcelFileDescriptor; 164import android.os.Process; 165import android.os.RemoteCallbackList; 166import android.os.RemoteException; 167import android.os.ResultReceiver; 168import android.os.SELinux; 169import android.os.ServiceManager; 170import android.os.SystemClock; 171import android.os.SystemProperties; 172import android.os.Trace; 173import android.os.UserHandle; 174import android.os.UserManager; 175import android.os.storage.IMountService; 176import android.os.storage.MountServiceInternal; 177import android.os.storage.StorageEventListener; 178import android.os.storage.StorageManager; 179import android.os.storage.VolumeInfo; 180import android.os.storage.VolumeRecord; 181import android.security.KeyStore; 182import android.security.SystemKeyStore; 183import android.system.ErrnoException; 184import android.system.Os; 185import android.system.StructStat; 186import android.text.TextUtils; 187import android.text.format.DateUtils; 188import android.util.ArrayMap; 189import android.util.ArraySet; 190import android.util.AtomicFile; 191import android.util.DisplayMetrics; 192import android.util.EventLog; 193import android.util.ExceptionUtils; 194import android.util.Log; 195import android.util.LogPrinter; 196import android.util.MathUtils; 197import android.util.PrintStreamPrinter; 198import android.util.Slog; 199import android.util.SparseArray; 200import android.util.SparseBooleanArray; 201import android.util.SparseIntArray; 202import android.util.Xml; 203import android.view.Display; 204 205import com.android.internal.annotations.GuardedBy; 206import dalvik.system.DexFile; 207import dalvik.system.VMRuntime; 208 209import libcore.io.IoUtils; 210import libcore.util.EmptyArray; 211 212import com.android.internal.R; 213import com.android.internal.app.EphemeralResolveInfo; 214import com.android.internal.app.IMediaContainerService; 215import com.android.internal.app.ResolverActivity; 216import com.android.internal.content.NativeLibraryHelper; 217import com.android.internal.content.PackageHelper; 218import com.android.internal.os.IParcelFileDescriptorFactory; 219import com.android.internal.os.SomeArgs; 220import com.android.internal.os.Zygote; 221import com.android.internal.util.ArrayUtils; 222import com.android.internal.util.FastPrintWriter; 223import com.android.internal.util.FastXmlSerializer; 224import com.android.internal.util.IndentingPrintWriter; 225import com.android.internal.util.Preconditions; 226import com.android.server.EventLogTags; 227import com.android.server.FgThread; 228import com.android.server.IntentResolver; 229import com.android.server.LocalServices; 230import com.android.server.ServiceThread; 231import com.android.server.SystemConfig; 232import com.android.server.Watchdog; 233import com.android.server.pm.PermissionsState.PermissionState; 234import com.android.server.pm.Settings.DatabaseVersion; 235import com.android.server.pm.Settings.VersionInfo; 236import com.android.server.storage.DeviceStorageMonitorInternal; 237 238import org.xmlpull.v1.XmlPullParser; 239import org.xmlpull.v1.XmlPullParserException; 240import org.xmlpull.v1.XmlSerializer; 241 242import java.io.BufferedInputStream; 243import java.io.BufferedOutputStream; 244import java.io.BufferedReader; 245import java.io.ByteArrayInputStream; 246import java.io.ByteArrayOutputStream; 247import java.io.File; 248import java.io.FileDescriptor; 249import java.io.FileNotFoundException; 250import java.io.FileOutputStream; 251import java.io.FileReader; 252import java.io.FilenameFilter; 253import java.io.IOException; 254import java.io.InputStream; 255import java.io.PrintWriter; 256import java.nio.charset.StandardCharsets; 257import java.security.MessageDigest; 258import java.security.NoSuchAlgorithmException; 259import java.security.PublicKey; 260import java.security.cert.CertificateEncodingException; 261import java.security.cert.CertificateException; 262import java.text.SimpleDateFormat; 263import java.util.ArrayList; 264import java.util.Arrays; 265import java.util.Collection; 266import java.util.Collections; 267import java.util.Comparator; 268import java.util.Date; 269import java.util.Iterator; 270import java.util.List; 271import java.util.Map; 272import java.util.Objects; 273import java.util.Set; 274import java.util.concurrent.CountDownLatch; 275import java.util.concurrent.TimeUnit; 276import java.util.concurrent.atomic.AtomicBoolean; 277import java.util.concurrent.atomic.AtomicInteger; 278import java.util.concurrent.atomic.AtomicLong; 279 280/** 281 * Keep track of all those .apks everywhere. 282 * 283 * This is very central to the platform's security; please run the unit 284 * tests whenever making modifications here: 285 * 286runtest -c android.content.pm.PackageManagerTests frameworks-core 287 * 288 * {@hide} 289 */ 290public class PackageManagerService extends IPackageManager.Stub { 291 static final String TAG = "PackageManager"; 292 static final boolean DEBUG_SETTINGS = false; 293 static final boolean DEBUG_PREFERRED = false; 294 static final boolean DEBUG_UPGRADE = false; 295 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 296 private static final boolean DEBUG_BACKUP = false; 297 private static final boolean DEBUG_INSTALL = false; 298 private static final boolean DEBUG_REMOVE = false; 299 private static final boolean DEBUG_BROADCASTS = false; 300 private static final boolean DEBUG_SHOW_INFO = false; 301 private static final boolean DEBUG_PACKAGE_INFO = false; 302 private static final boolean DEBUG_INTENT_MATCHING = false; 303 private static final boolean DEBUG_PACKAGE_SCANNING = false; 304 private static final boolean DEBUG_VERIFY = false; 305 private static final boolean DEBUG_DEXOPT = false; 306 private static final boolean DEBUG_ABI_SELECTION = false; 307 private static final boolean DEBUG_EPHEMERAL = false; 308 309 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 310 311 private static final int RADIO_UID = Process.PHONE_UID; 312 private static final int LOG_UID = Process.LOG_UID; 313 private static final int NFC_UID = Process.NFC_UID; 314 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 315 private static final int SHELL_UID = Process.SHELL_UID; 316 317 // Cap the size of permission trees that 3rd party apps can define 318 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 319 320 // Suffix used during package installation when copying/moving 321 // package apks to install directory. 322 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 323 324 static final int SCAN_NO_DEX = 1<<1; 325 static final int SCAN_FORCE_DEX = 1<<2; 326 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 327 static final int SCAN_NEW_INSTALL = 1<<4; 328 static final int SCAN_NO_PATHS = 1<<5; 329 static final int SCAN_UPDATE_TIME = 1<<6; 330 static final int SCAN_DEFER_DEX = 1<<7; 331 static final int SCAN_BOOTING = 1<<8; 332 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 333 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 334 static final int SCAN_REPLACING = 1<<11; 335 static final int SCAN_REQUIRE_KNOWN = 1<<12; 336 static final int SCAN_MOVE = 1<<13; 337 static final int SCAN_INITIAL = 1<<14; 338 339 static final int REMOVE_CHATTY = 1<<16; 340 341 private static final int[] EMPTY_INT_ARRAY = new int[0]; 342 343 /** 344 * Timeout (in milliseconds) after which the watchdog should declare that 345 * our handler thread is wedged. The usual default for such things is one 346 * minute but we sometimes do very lengthy I/O operations on this thread, 347 * such as installing multi-gigabyte applications, so ours needs to be longer. 348 */ 349 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 350 351 /** 352 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 353 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 354 * settings entry if available, otherwise we use the hardcoded default. If it's been 355 * more than this long since the last fstrim, we force one during the boot sequence. 356 * 357 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 358 * one gets run at the next available charging+idle time. This final mandatory 359 * no-fstrim check kicks in only of the other scheduling criteria is never met. 360 */ 361 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 362 363 /** 364 * Whether verification is enabled by default. 365 */ 366 private static final boolean DEFAULT_VERIFY_ENABLE = true; 367 368 /** 369 * The default maximum time to wait for the verification agent to return in 370 * milliseconds. 371 */ 372 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 373 374 /** 375 * The default response for package verification timeout. 376 * 377 * This can be either PackageManager.VERIFICATION_ALLOW or 378 * PackageManager.VERIFICATION_REJECT. 379 */ 380 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 381 382 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 383 384 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 385 DEFAULT_CONTAINER_PACKAGE, 386 "com.android.defcontainer.DefaultContainerService"); 387 388 private static final String KILL_APP_REASON_GIDS_CHANGED = 389 "permission grant or revoke changed gids"; 390 391 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 392 "permissions revoked"; 393 394 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 395 396 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 397 398 /** Permission grant: not grant the permission. */ 399 private static final int GRANT_DENIED = 1; 400 401 /** Permission grant: grant the permission as an install permission. */ 402 private static final int GRANT_INSTALL = 2; 403 404 /** Permission grant: grant the permission as a runtime one. */ 405 private static final int GRANT_RUNTIME = 3; 406 407 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 408 private static final int GRANT_UPGRADE = 4; 409 410 /** Canonical intent used to identify what counts as a "web browser" app */ 411 private static final Intent sBrowserIntent; 412 static { 413 sBrowserIntent = new Intent(); 414 sBrowserIntent.setAction(Intent.ACTION_VIEW); 415 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 416 sBrowserIntent.setData(Uri.parse("http:")); 417 } 418 419 final ServiceThread mHandlerThread; 420 421 final PackageHandler mHandler; 422 423 /** 424 * Messages for {@link #mHandler} that need to wait for system ready before 425 * being dispatched. 426 */ 427 private ArrayList<Message> mPostSystemReadyMessages; 428 429 final int mSdkVersion = Build.VERSION.SDK_INT; 430 431 final Context mContext; 432 final boolean mFactoryTest; 433 final boolean mOnlyCore; 434 final DisplayMetrics mMetrics; 435 final int mDefParseFlags; 436 final String[] mSeparateProcesses; 437 final boolean mIsUpgrade; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 final File mEphemeralInstallDir; 450 451 /** 452 * Directory to which applications installed internally have their 453 * 32 bit native libraries copied. 454 */ 455 private File mAppLib32InstallDir; 456 457 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 458 // apps. 459 final File mDrmAppPrivateInstallDir; 460 461 // ---------------------------------------------------------------- 462 463 // Lock for state used when installing and doing other long running 464 // operations. Methods that must be called with this lock held have 465 // the suffix "LI". 466 final Object mInstallLock = new Object(); 467 468 // ---------------------------------------------------------------- 469 470 // Keys are String (package name), values are Package. This also serves 471 // as the lock for the global state. Methods that must be called with 472 // this lock held have the prefix "LP". 473 @GuardedBy("mPackages") 474 final ArrayMap<String, PackageParser.Package> mPackages = 475 new ArrayMap<String, PackageParser.Package>(); 476 477 // Tracks available target package names -> overlay package paths. 478 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 479 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 480 481 /** 482 * Tracks new system packages [received in an OTA] that we expect to 483 * find updated user-installed versions. Keys are package name, values 484 * are package location. 485 */ 486 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 487 488 /** 489 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 490 */ 491 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 492 /** 493 * Whether or not system app permissions should be promoted from install to runtime. 494 */ 495 boolean mPromoteSystemApps; 496 497 final Settings mSettings; 498 boolean mRestoredSettings; 499 500 // System configuration read by SystemConfig. 501 final int[] mGlobalGids; 502 final SparseArray<ArraySet<String>> mSystemPermissions; 503 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 504 505 // If mac_permissions.xml was found for seinfo labeling. 506 boolean mFoundPolicyFile; 507 508 // If a recursive restorecon of /data/data/<pkg> is needed. 509 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 510 511 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 512 513 public static final class SharedLibraryEntry { 514 public final String path; 515 public final String apk; 516 517 SharedLibraryEntry(String _path, String _apk) { 518 path = _path; 519 apk = _apk; 520 } 521 } 522 523 // Currently known shared libraries. 524 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 525 new ArrayMap<String, SharedLibraryEntry>(); 526 527 // All available activities, for your resolving pleasure. 528 final ActivityIntentResolver mActivities = 529 new ActivityIntentResolver(); 530 531 // All available receivers, for your resolving pleasure. 532 final ActivityIntentResolver mReceivers = 533 new ActivityIntentResolver(); 534 535 // All available services, for your resolving pleasure. 536 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 537 538 // All available providers, for your resolving pleasure. 539 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 540 541 // Mapping from provider base names (first directory in content URI codePath) 542 // to the provider information. 543 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 544 new ArrayMap<String, PackageParser.Provider>(); 545 546 // Mapping from instrumentation class names to info about them. 547 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 548 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 549 550 // Mapping from permission names to info about them. 551 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 552 new ArrayMap<String, PackageParser.PermissionGroup>(); 553 554 // Packages whose data we have transfered into another package, thus 555 // should no longer exist. 556 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 557 558 // Broadcast actions that are only available to the system. 559 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 560 561 /** List of packages waiting for verification. */ 562 final SparseArray<PackageVerificationState> mPendingVerification 563 = new SparseArray<PackageVerificationState>(); 564 565 /** Set of packages associated with each app op permission. */ 566 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 567 568 final PackageInstallerService mInstallerService; 569 570 private final PackageDexOptimizer mPackageDexOptimizer; 571 572 private AtomicInteger mNextMoveId = new AtomicInteger(); 573 private final MoveCallbacks mMoveCallbacks; 574 575 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 576 577 // Cache of users who need badging. 578 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 579 580 /** Token for keys in mPendingVerification. */ 581 private int mPendingVerificationToken = 0; 582 583 volatile boolean mSystemReady; 584 volatile boolean mSafeMode; 585 volatile boolean mHasSystemUidErrors; 586 587 ApplicationInfo mAndroidApplication; 588 final ActivityInfo mResolveActivity = new ActivityInfo(); 589 final ResolveInfo mResolveInfo = new ResolveInfo(); 590 ComponentName mResolveComponentName; 591 PackageParser.Package mPlatformPackage; 592 ComponentName mCustomResolverComponentName; 593 594 boolean mResolverReplaced = false; 595 596 private final ComponentName mIntentFilterVerifierComponent; 597 private int mIntentFilterVerificationToken = 0; 598 599 /** Component that knows whether or not an ephemeral application exists */ 600 final ComponentName mEphemeralResolverComponent; 601 /** The service connection to the ephemeral resolver */ 602 final EphemeralResolverConnection mEphemeralResolverConnection; 603 604 /** Component used to install ephemeral applications */ 605 final ComponentName mEphemeralInstallerComponent; 606 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 607 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 608 609 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 610 = new SparseArray<IntentFilterVerificationState>(); 611 612 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 613 new DefaultPermissionGrantPolicy(this); 614 615 // List of packages names to keep cached, even if they are uninstalled for all users 616 private List<String> mKeepUninstalledPackages; 617 618 private static class IFVerificationParams { 619 PackageParser.Package pkg; 620 boolean replacing; 621 int userId; 622 int verifierUid; 623 624 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 625 int _userId, int _verifierUid) { 626 pkg = _pkg; 627 replacing = _replacing; 628 userId = _userId; 629 replacing = _replacing; 630 verifierUid = _verifierUid; 631 } 632 } 633 634 private interface IntentFilterVerifier<T extends IntentFilter> { 635 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 636 T filter, String packageName); 637 void startVerifications(int userId); 638 void receiveVerificationResponse(int verificationId); 639 } 640 641 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 642 private Context mContext; 643 private ComponentName mIntentFilterVerifierComponent; 644 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 645 646 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 647 mContext = context; 648 mIntentFilterVerifierComponent = verifierComponent; 649 } 650 651 private String getDefaultScheme() { 652 return IntentFilter.SCHEME_HTTPS; 653 } 654 655 @Override 656 public void startVerifications(int userId) { 657 // Launch verifications requests 658 int count = mCurrentIntentFilterVerifications.size(); 659 for (int n=0; n<count; n++) { 660 int verificationId = mCurrentIntentFilterVerifications.get(n); 661 final IntentFilterVerificationState ivs = 662 mIntentFilterVerificationStates.get(verificationId); 663 664 String packageName = ivs.getPackageName(); 665 666 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 667 final int filterCount = filters.size(); 668 ArraySet<String> domainsSet = new ArraySet<>(); 669 for (int m=0; m<filterCount; m++) { 670 PackageParser.ActivityIntentInfo filter = filters.get(m); 671 domainsSet.addAll(filter.getHostsList()); 672 } 673 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 674 synchronized (mPackages) { 675 if (mSettings.createIntentFilterVerificationIfNeededLPw( 676 packageName, domainsList) != null) { 677 scheduleWriteSettingsLocked(); 678 } 679 } 680 sendVerificationRequest(userId, verificationId, ivs); 681 } 682 mCurrentIntentFilterVerifications.clear(); 683 } 684 685 private void sendVerificationRequest(int userId, int verificationId, 686 IntentFilterVerificationState ivs) { 687 688 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 689 verificationIntent.putExtra( 690 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 691 verificationId); 692 verificationIntent.putExtra( 693 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 694 getDefaultScheme()); 695 verificationIntent.putExtra( 696 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 697 ivs.getHostsString()); 698 verificationIntent.putExtra( 699 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 700 ivs.getPackageName()); 701 verificationIntent.setComponent(mIntentFilterVerifierComponent); 702 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 703 704 UserHandle user = new UserHandle(userId); 705 mContext.sendBroadcastAsUser(verificationIntent, user); 706 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 707 "Sending IntentFilter verification broadcast"); 708 } 709 710 public void receiveVerificationResponse(int verificationId) { 711 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 712 713 final boolean verified = ivs.isVerified(); 714 715 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 716 final int count = filters.size(); 717 if (DEBUG_DOMAIN_VERIFICATION) { 718 Slog.i(TAG, "Received verification response " + verificationId 719 + " for " + count + " filters, verified=" + verified); 720 } 721 for (int n=0; n<count; n++) { 722 PackageParser.ActivityIntentInfo filter = filters.get(n); 723 filter.setVerified(verified); 724 725 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 726 + " verified with result:" + verified + " and hosts:" 727 + ivs.getHostsString()); 728 } 729 730 mIntentFilterVerificationStates.remove(verificationId); 731 732 final String packageName = ivs.getPackageName(); 733 IntentFilterVerificationInfo ivi = null; 734 735 synchronized (mPackages) { 736 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 737 } 738 if (ivi == null) { 739 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 740 + verificationId + " packageName:" + packageName); 741 return; 742 } 743 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 744 "Updating IntentFilterVerificationInfo for package " + packageName 745 +" verificationId:" + verificationId); 746 747 synchronized (mPackages) { 748 if (verified) { 749 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 750 } else { 751 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 752 } 753 scheduleWriteSettingsLocked(); 754 755 final int userId = ivs.getUserId(); 756 if (userId != UserHandle.USER_ALL) { 757 final int userStatus = 758 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 759 760 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 761 boolean needUpdate = false; 762 763 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 764 // already been set by the User thru the Disambiguation dialog 765 switch (userStatus) { 766 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 767 if (verified) { 768 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 769 } else { 770 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 771 } 772 needUpdate = true; 773 break; 774 775 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 776 if (verified) { 777 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 778 needUpdate = true; 779 } 780 break; 781 782 default: 783 // Nothing to do 784 } 785 786 if (needUpdate) { 787 mSettings.updateIntentFilterVerificationStatusLPw( 788 packageName, updatedStatus, userId); 789 scheduleWritePackageRestrictionsLocked(userId); 790 } 791 } 792 } 793 } 794 795 @Override 796 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 797 ActivityIntentInfo filter, String packageName) { 798 if (!hasValidDomains(filter)) { 799 return false; 800 } 801 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 802 if (ivs == null) { 803 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 804 packageName); 805 } 806 if (DEBUG_DOMAIN_VERIFICATION) { 807 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 808 } 809 ivs.addFilter(filter); 810 return true; 811 } 812 813 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 814 int userId, int verificationId, String packageName) { 815 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 816 verifierUid, userId, packageName); 817 ivs.setPendingState(); 818 synchronized (mPackages) { 819 mIntentFilterVerificationStates.append(verificationId, ivs); 820 mCurrentIntentFilterVerifications.add(verificationId); 821 } 822 return ivs; 823 } 824 } 825 826 private static boolean hasValidDomains(ActivityIntentInfo filter) { 827 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 828 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 829 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 830 } 831 832 private IntentFilterVerifier mIntentFilterVerifier; 833 834 // Set of pending broadcasts for aggregating enable/disable of components. 835 static class PendingPackageBroadcasts { 836 // for each user id, a map of <package name -> components within that package> 837 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 838 839 public PendingPackageBroadcasts() { 840 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 841 } 842 843 public ArrayList<String> get(int userId, String packageName) { 844 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 845 return packages.get(packageName); 846 } 847 848 public void put(int userId, String packageName, ArrayList<String> components) { 849 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 850 packages.put(packageName, components); 851 } 852 853 public void remove(int userId, String packageName) { 854 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 855 if (packages != null) { 856 packages.remove(packageName); 857 } 858 } 859 860 public void remove(int userId) { 861 mUidMap.remove(userId); 862 } 863 864 public int userIdCount() { 865 return mUidMap.size(); 866 } 867 868 public int userIdAt(int n) { 869 return mUidMap.keyAt(n); 870 } 871 872 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 873 return mUidMap.get(userId); 874 } 875 876 public int size() { 877 // total number of pending broadcast entries across all userIds 878 int num = 0; 879 for (int i = 0; i< mUidMap.size(); i++) { 880 num += mUidMap.valueAt(i).size(); 881 } 882 return num; 883 } 884 885 public void clear() { 886 mUidMap.clear(); 887 } 888 889 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 890 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 891 if (map == null) { 892 map = new ArrayMap<String, ArrayList<String>>(); 893 mUidMap.put(userId, map); 894 } 895 return map; 896 } 897 } 898 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 899 900 // Service Connection to remote media container service to copy 901 // package uri's from external media onto secure containers 902 // or internal storage. 903 private IMediaContainerService mContainerService = null; 904 905 static final int SEND_PENDING_BROADCAST = 1; 906 static final int MCS_BOUND = 3; 907 static final int END_COPY = 4; 908 static final int INIT_COPY = 5; 909 static final int MCS_UNBIND = 6; 910 static final int START_CLEANING_PACKAGE = 7; 911 static final int FIND_INSTALL_LOC = 8; 912 static final int POST_INSTALL = 9; 913 static final int MCS_RECONNECT = 10; 914 static final int MCS_GIVE_UP = 11; 915 static final int UPDATED_MEDIA_STATUS = 12; 916 static final int WRITE_SETTINGS = 13; 917 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 918 static final int PACKAGE_VERIFIED = 15; 919 static final int CHECK_PENDING_VERIFICATION = 16; 920 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 921 static final int INTENT_FILTER_VERIFIED = 18; 922 923 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 924 925 // Delay time in millisecs 926 static final int BROADCAST_DELAY = 10 * 1000; 927 928 static UserManagerService sUserManager; 929 930 // Stores a list of users whose package restrictions file needs to be updated 931 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 932 933 final private DefaultContainerConnection mDefContainerConn = 934 new DefaultContainerConnection(); 935 class DefaultContainerConnection implements ServiceConnection { 936 public void onServiceConnected(ComponentName name, IBinder service) { 937 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 938 IMediaContainerService imcs = 939 IMediaContainerService.Stub.asInterface(service); 940 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 941 } 942 943 public void onServiceDisconnected(ComponentName name) { 944 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 945 } 946 } 947 948 // Recordkeeping of restore-after-install operations that are currently in flight 949 // between the Package Manager and the Backup Manager 950 static class PostInstallData { 951 public InstallArgs args; 952 public PackageInstalledInfo res; 953 954 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 955 args = _a; 956 res = _r; 957 } 958 } 959 960 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 961 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 962 963 // XML tags for backup/restore of various bits of state 964 private static final String TAG_PREFERRED_BACKUP = "pa"; 965 private static final String TAG_DEFAULT_APPS = "da"; 966 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 967 968 final String mRequiredVerifierPackage; 969 final String mRequiredInstallerPackage; 970 971 private final PackageUsage mPackageUsage = new PackageUsage(); 972 973 private class PackageUsage { 974 private static final int WRITE_INTERVAL 975 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 976 977 private final Object mFileLock = new Object(); 978 private final AtomicLong mLastWritten = new AtomicLong(0); 979 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 980 981 private boolean mIsHistoricalPackageUsageAvailable = true; 982 983 boolean isHistoricalPackageUsageAvailable() { 984 return mIsHistoricalPackageUsageAvailable; 985 } 986 987 void write(boolean force) { 988 if (force) { 989 writeInternal(); 990 return; 991 } 992 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 993 && !DEBUG_DEXOPT) { 994 return; 995 } 996 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 997 new Thread("PackageUsage_DiskWriter") { 998 @Override 999 public void run() { 1000 try { 1001 writeInternal(); 1002 } finally { 1003 mBackgroundWriteRunning.set(false); 1004 } 1005 } 1006 }.start(); 1007 } 1008 } 1009 1010 private void writeInternal() { 1011 synchronized (mPackages) { 1012 synchronized (mFileLock) { 1013 AtomicFile file = getFile(); 1014 FileOutputStream f = null; 1015 try { 1016 f = file.startWrite(); 1017 BufferedOutputStream out = new BufferedOutputStream(f); 1018 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1019 StringBuilder sb = new StringBuilder(); 1020 for (PackageParser.Package pkg : mPackages.values()) { 1021 if (pkg.mLastPackageUsageTimeInMills == 0) { 1022 continue; 1023 } 1024 sb.setLength(0); 1025 sb.append(pkg.packageName); 1026 sb.append(' '); 1027 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1028 sb.append('\n'); 1029 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1030 } 1031 out.flush(); 1032 file.finishWrite(f); 1033 } catch (IOException e) { 1034 if (f != null) { 1035 file.failWrite(f); 1036 } 1037 Log.e(TAG, "Failed to write package usage times", e); 1038 } 1039 } 1040 } 1041 mLastWritten.set(SystemClock.elapsedRealtime()); 1042 } 1043 1044 void readLP() { 1045 synchronized (mFileLock) { 1046 AtomicFile file = getFile(); 1047 BufferedInputStream in = null; 1048 try { 1049 in = new BufferedInputStream(file.openRead()); 1050 StringBuffer sb = new StringBuffer(); 1051 while (true) { 1052 String packageName = readToken(in, sb, ' '); 1053 if (packageName == null) { 1054 break; 1055 } 1056 String timeInMillisString = readToken(in, sb, '\n'); 1057 if (timeInMillisString == null) { 1058 throw new IOException("Failed to find last usage time for package " 1059 + packageName); 1060 } 1061 PackageParser.Package pkg = mPackages.get(packageName); 1062 if (pkg == null) { 1063 continue; 1064 } 1065 long timeInMillis; 1066 try { 1067 timeInMillis = Long.parseLong(timeInMillisString); 1068 } catch (NumberFormatException e) { 1069 throw new IOException("Failed to parse " + timeInMillisString 1070 + " as a long.", e); 1071 } 1072 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1073 } 1074 } catch (FileNotFoundException expected) { 1075 mIsHistoricalPackageUsageAvailable = false; 1076 } catch (IOException e) { 1077 Log.w(TAG, "Failed to read package usage times", e); 1078 } finally { 1079 IoUtils.closeQuietly(in); 1080 } 1081 } 1082 mLastWritten.set(SystemClock.elapsedRealtime()); 1083 } 1084 1085 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1086 throws IOException { 1087 sb.setLength(0); 1088 while (true) { 1089 int ch = in.read(); 1090 if (ch == -1) { 1091 if (sb.length() == 0) { 1092 return null; 1093 } 1094 throw new IOException("Unexpected EOF"); 1095 } 1096 if (ch == endOfToken) { 1097 return sb.toString(); 1098 } 1099 sb.append((char)ch); 1100 } 1101 } 1102 1103 private AtomicFile getFile() { 1104 File dataDir = Environment.getDataDirectory(); 1105 File systemDir = new File(dataDir, "system"); 1106 File fname = new File(systemDir, "package-usage.list"); 1107 return new AtomicFile(fname); 1108 } 1109 } 1110 1111 class PackageHandler extends Handler { 1112 private boolean mBound = false; 1113 final ArrayList<HandlerParams> mPendingInstalls = 1114 new ArrayList<HandlerParams>(); 1115 1116 private boolean connectToService() { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1118 " DefaultContainerService"); 1119 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1120 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1121 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1122 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 mBound = true; 1125 return true; 1126 } 1127 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1128 return false; 1129 } 1130 1131 private void disconnectService() { 1132 mContainerService = null; 1133 mBound = false; 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1135 mContext.unbindService(mDefContainerConn); 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 1139 PackageHandler(Looper looper) { 1140 super(looper); 1141 } 1142 1143 public void handleMessage(Message msg) { 1144 try { 1145 doHandleMessage(msg); 1146 } finally { 1147 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1148 } 1149 } 1150 1151 void doHandleMessage(Message msg) { 1152 switch (msg.what) { 1153 case INIT_COPY: { 1154 HandlerParams params = (HandlerParams) msg.obj; 1155 int idx = mPendingInstalls.size(); 1156 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1157 // If a bind was already initiated we dont really 1158 // need to do anything. The pending install 1159 // will be processed later on. 1160 if (!mBound) { 1161 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1162 System.identityHashCode(mHandler)); 1163 // If this is the only one pending we might 1164 // have to bind to the service again. 1165 if (!connectToService()) { 1166 Slog.e(TAG, "Failed to bind to media container service"); 1167 params.serviceError(); 1168 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1169 System.identityHashCode(mHandler)); 1170 if (params.traceMethod != null) { 1171 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1172 params.traceCookie); 1173 } 1174 return; 1175 } else { 1176 // Once we bind to the service, the first 1177 // pending request will be processed. 1178 mPendingInstalls.add(idx, params); 1179 } 1180 } else { 1181 mPendingInstalls.add(idx, params); 1182 // Already bound to the service. Just make 1183 // sure we trigger off processing the first request. 1184 if (idx == 0) { 1185 mHandler.sendEmptyMessage(MCS_BOUND); 1186 } 1187 } 1188 break; 1189 } 1190 case MCS_BOUND: { 1191 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1192 if (msg.obj != null) { 1193 mContainerService = (IMediaContainerService) msg.obj; 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1195 System.identityHashCode(mHandler)); 1196 } 1197 if (mContainerService == null) { 1198 if (!mBound) { 1199 // Something seriously wrong since we are not bound and we are not 1200 // waiting for connection. Bail out. 1201 Slog.e(TAG, "Cannot bind to media container service"); 1202 for (HandlerParams params : mPendingInstalls) { 1203 // Indicate service bind error 1204 params.serviceError(); 1205 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1206 System.identityHashCode(params)); 1207 if (params.traceMethod != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1209 params.traceMethod, params.traceCookie); 1210 } 1211 return; 1212 } 1213 mPendingInstalls.clear(); 1214 } else { 1215 Slog.w(TAG, "Waiting to connect to media container service"); 1216 } 1217 } else if (mPendingInstalls.size() > 0) { 1218 HandlerParams params = mPendingInstalls.get(0); 1219 if (params != null) { 1220 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1221 System.identityHashCode(params)); 1222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1223 if (params.startCopy()) { 1224 // We are done... look for more work or to 1225 // go idle. 1226 if (DEBUG_SD_INSTALL) Log.i(TAG, 1227 "Checking for more work or unbind..."); 1228 // Delete pending install 1229 if (mPendingInstalls.size() > 0) { 1230 mPendingInstalls.remove(0); 1231 } 1232 if (mPendingInstalls.size() == 0) { 1233 if (mBound) { 1234 if (DEBUG_SD_INSTALL) Log.i(TAG, 1235 "Posting delayed MCS_UNBIND"); 1236 removeMessages(MCS_UNBIND); 1237 Message ubmsg = obtainMessage(MCS_UNBIND); 1238 // Unbind after a little delay, to avoid 1239 // continual thrashing. 1240 sendMessageDelayed(ubmsg, 10000); 1241 } 1242 } else { 1243 // There are more pending requests in queue. 1244 // Just post MCS_BOUND message to trigger processing 1245 // of next pending install. 1246 if (DEBUG_SD_INSTALL) Log.i(TAG, 1247 "Posting MCS_BOUND for next work"); 1248 mHandler.sendEmptyMessage(MCS_BOUND); 1249 } 1250 } 1251 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1252 } 1253 } else { 1254 // Should never happen ideally. 1255 Slog.w(TAG, "Empty queue"); 1256 } 1257 break; 1258 } 1259 case MCS_RECONNECT: { 1260 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1261 if (mPendingInstalls.size() > 0) { 1262 if (mBound) { 1263 disconnectService(); 1264 } 1265 if (!connectToService()) { 1266 Slog.e(TAG, "Failed to bind to media container service"); 1267 for (HandlerParams params : mPendingInstalls) { 1268 // Indicate service bind error 1269 params.serviceError(); 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1271 System.identityHashCode(params)); 1272 } 1273 mPendingInstalls.clear(); 1274 } 1275 } 1276 break; 1277 } 1278 case MCS_UNBIND: { 1279 // If there is no actual work left, then time to unbind. 1280 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1281 1282 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1283 if (mBound) { 1284 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1285 1286 disconnectService(); 1287 } 1288 } else if (mPendingInstalls.size() > 0) { 1289 // There are more pending requests in queue. 1290 // Just post MCS_BOUND message to trigger processing 1291 // of next pending install. 1292 mHandler.sendEmptyMessage(MCS_BOUND); 1293 } 1294 1295 break; 1296 } 1297 case MCS_GIVE_UP: { 1298 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1299 HandlerParams params = mPendingInstalls.remove(0); 1300 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1301 System.identityHashCode(params)); 1302 break; 1303 } 1304 case SEND_PENDING_BROADCAST: { 1305 String packages[]; 1306 ArrayList<String> components[]; 1307 int size = 0; 1308 int uids[]; 1309 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1310 synchronized (mPackages) { 1311 if (mPendingBroadcasts == null) { 1312 return; 1313 } 1314 size = mPendingBroadcasts.size(); 1315 if (size <= 0) { 1316 // Nothing to be done. Just return 1317 return; 1318 } 1319 packages = new String[size]; 1320 components = new ArrayList[size]; 1321 uids = new int[size]; 1322 int i = 0; // filling out the above arrays 1323 1324 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1325 int packageUserId = mPendingBroadcasts.userIdAt(n); 1326 Iterator<Map.Entry<String, ArrayList<String>>> it 1327 = mPendingBroadcasts.packagesForUserId(packageUserId) 1328 .entrySet().iterator(); 1329 while (it.hasNext() && i < size) { 1330 Map.Entry<String, ArrayList<String>> ent = it.next(); 1331 packages[i] = ent.getKey(); 1332 components[i] = ent.getValue(); 1333 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1334 uids[i] = (ps != null) 1335 ? UserHandle.getUid(packageUserId, ps.appId) 1336 : -1; 1337 i++; 1338 } 1339 } 1340 size = i; 1341 mPendingBroadcasts.clear(); 1342 } 1343 // Send broadcasts 1344 for (int i = 0; i < size; i++) { 1345 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1346 } 1347 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1348 break; 1349 } 1350 case START_CLEANING_PACKAGE: { 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1352 final String packageName = (String)msg.obj; 1353 final int userId = msg.arg1; 1354 final boolean andCode = msg.arg2 != 0; 1355 synchronized (mPackages) { 1356 if (userId == UserHandle.USER_ALL) { 1357 int[] users = sUserManager.getUserIds(); 1358 for (int user : users) { 1359 mSettings.addPackageToCleanLPw( 1360 new PackageCleanItem(user, packageName, andCode)); 1361 } 1362 } else { 1363 mSettings.addPackageToCleanLPw( 1364 new PackageCleanItem(userId, packageName, andCode)); 1365 } 1366 } 1367 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1368 startCleaningPackages(); 1369 } break; 1370 case POST_INSTALL: { 1371 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1372 1373 PostInstallData data = mRunningInstalls.get(msg.arg1); 1374 mRunningInstalls.delete(msg.arg1); 1375 boolean deleteOld = false; 1376 1377 if (data != null) { 1378 InstallArgs args = data.args; 1379 PackageInstalledInfo res = data.res; 1380 1381 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1382 final String packageName = res.pkg.applicationInfo.packageName; 1383 res.removedInfo.sendBroadcast(false, true, false); 1384 Bundle extras = new Bundle(1); 1385 extras.putInt(Intent.EXTRA_UID, res.uid); 1386 1387 // Now that we successfully installed the package, grant runtime 1388 // permissions if requested before broadcasting the install. 1389 if ((args.installFlags 1390 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1391 && res.pkg.applicationInfo.targetSdkVersion 1392 >= Build.VERSION_CODES.M) { 1393 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1394 args.installGrantPermissions); 1395 } 1396 1397 synchronized (mPackages) { 1398 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1399 } 1400 1401 // Determine the set of users who are adding this 1402 // package for the first time vs. those who are seeing 1403 // an update. 1404 int[] firstUsers; 1405 int[] updateUsers = new int[0]; 1406 if (res.origUsers == null || res.origUsers.length == 0) { 1407 firstUsers = res.newUsers; 1408 } else { 1409 firstUsers = new int[0]; 1410 for (int i=0; i<res.newUsers.length; i++) { 1411 int user = res.newUsers[i]; 1412 boolean isNew = true; 1413 for (int j=0; j<res.origUsers.length; j++) { 1414 if (res.origUsers[j] == user) { 1415 isNew = false; 1416 break; 1417 } 1418 } 1419 if (isNew) { 1420 int[] newFirst = new int[firstUsers.length+1]; 1421 System.arraycopy(firstUsers, 0, newFirst, 0, 1422 firstUsers.length); 1423 newFirst[firstUsers.length] = user; 1424 firstUsers = newFirst; 1425 } else { 1426 int[] newUpdate = new int[updateUsers.length+1]; 1427 System.arraycopy(updateUsers, 0, newUpdate, 0, 1428 updateUsers.length); 1429 newUpdate[updateUsers.length] = user; 1430 updateUsers = newUpdate; 1431 } 1432 } 1433 } 1434 // don't broadcast for ephemeral installs/updates 1435 final boolean isEphemeral = isEphemeral(res.pkg); 1436 if (!isEphemeral) { 1437 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1438 extras, 0 /*flags*/, null /*targetPackage*/, 1439 null /*finishedReceiver*/, firstUsers); 1440 } 1441 final boolean update = res.removedInfo.removedPackage != null; 1442 if (update) { 1443 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1444 } 1445 if (!isEphemeral) { 1446 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1447 extras, 0 /*flags*/, null /*targetPackage*/, 1448 null /*finishedReceiver*/, updateUsers); 1449 } 1450 if (update) { 1451 if (!isEphemeral) { 1452 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1453 packageName, extras, 0 /*flags*/, 1454 null /*targetPackage*/, null /*finishedReceiver*/, 1455 updateUsers); 1456 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1457 null /*package*/, null /*extras*/, 0 /*flags*/, 1458 packageName /*targetPackage*/, 1459 null /*finishedReceiver*/, updateUsers); 1460 } 1461 1462 // treat asec-hosted packages like removable media on upgrade 1463 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1464 if (DEBUG_INSTALL) { 1465 Slog.i(TAG, "upgrading pkg " + res.pkg 1466 + " is ASEC-hosted -> AVAILABLE"); 1467 } 1468 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1469 ArrayList<String> pkgList = new ArrayList<String>(1); 1470 pkgList.add(packageName); 1471 sendResourcesChangedBroadcast(true, true, 1472 pkgList,uidArray, null); 1473 } 1474 } 1475 if (res.removedInfo.args != null) { 1476 // Remove the replaced package's older resources safely now 1477 deleteOld = true; 1478 } 1479 1480 // If this app is a browser and it's newly-installed for some 1481 // users, clear any default-browser state in those users 1482 if (firstUsers.length > 0) { 1483 // the app's nature doesn't depend on the user, so we can just 1484 // check its browser nature in any user and generalize. 1485 if (packageIsBrowser(packageName, firstUsers[0])) { 1486 synchronized (mPackages) { 1487 for (int userId : firstUsers) { 1488 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1489 } 1490 } 1491 } 1492 } 1493 // Log current value of "unknown sources" setting 1494 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1495 getUnknownSourcesSettings()); 1496 } 1497 // Force a gc to clear up things 1498 Runtime.getRuntime().gc(); 1499 // We delete after a gc for applications on sdcard. 1500 if (deleteOld) { 1501 synchronized (mInstallLock) { 1502 res.removedInfo.args.doPostDeleteLI(true); 1503 } 1504 } 1505 if (args.observer != null) { 1506 try { 1507 Bundle extras = extrasForInstallResult(res); 1508 args.observer.onPackageInstalled(res.name, res.returnCode, 1509 res.returnMsg, extras); 1510 } catch (RemoteException e) { 1511 Slog.i(TAG, "Observer no longer exists."); 1512 } 1513 } 1514 if (args.traceMethod != null) { 1515 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1516 args.traceCookie); 1517 } 1518 return; 1519 } else { 1520 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1521 } 1522 1523 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1524 } break; 1525 case UPDATED_MEDIA_STATUS: { 1526 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1527 boolean reportStatus = msg.arg1 == 1; 1528 boolean doGc = msg.arg2 == 1; 1529 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1530 if (doGc) { 1531 // Force a gc to clear up stale containers. 1532 Runtime.getRuntime().gc(); 1533 } 1534 if (msg.obj != null) { 1535 @SuppressWarnings("unchecked") 1536 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1537 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1538 // Unload containers 1539 unloadAllContainers(args); 1540 } 1541 if (reportStatus) { 1542 try { 1543 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1544 PackageHelper.getMountService().finishMediaUpdate(); 1545 } catch (RemoteException e) { 1546 Log.e(TAG, "MountService not running?"); 1547 } 1548 } 1549 } break; 1550 case WRITE_SETTINGS: { 1551 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1552 synchronized (mPackages) { 1553 removeMessages(WRITE_SETTINGS); 1554 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1555 mSettings.writeLPr(); 1556 mDirtyUsers.clear(); 1557 } 1558 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1559 } break; 1560 case WRITE_PACKAGE_RESTRICTIONS: { 1561 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1562 synchronized (mPackages) { 1563 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1564 for (int userId : mDirtyUsers) { 1565 mSettings.writePackageRestrictionsLPr(userId); 1566 } 1567 mDirtyUsers.clear(); 1568 } 1569 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1570 } break; 1571 case CHECK_PENDING_VERIFICATION: { 1572 final int verificationId = msg.arg1; 1573 final PackageVerificationState state = mPendingVerification.get(verificationId); 1574 1575 if ((state != null) && !state.timeoutExtended()) { 1576 final InstallArgs args = state.getInstallArgs(); 1577 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1578 1579 Slog.i(TAG, "Verification timed out for " + originUri); 1580 mPendingVerification.remove(verificationId); 1581 1582 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1583 1584 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1585 Slog.i(TAG, "Continuing with installation of " + originUri); 1586 state.setVerifierResponse(Binder.getCallingUid(), 1587 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1588 broadcastPackageVerified(verificationId, originUri, 1589 PackageManager.VERIFICATION_ALLOW, 1590 state.getInstallArgs().getUser()); 1591 try { 1592 ret = args.copyApk(mContainerService, true); 1593 } catch (RemoteException e) { 1594 Slog.e(TAG, "Could not contact the ContainerService"); 1595 } 1596 } else { 1597 broadcastPackageVerified(verificationId, originUri, 1598 PackageManager.VERIFICATION_REJECT, 1599 state.getInstallArgs().getUser()); 1600 } 1601 1602 Trace.asyncTraceEnd( 1603 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1604 1605 processPendingInstall(args, ret); 1606 mHandler.sendEmptyMessage(MCS_UNBIND); 1607 } 1608 break; 1609 } 1610 case PACKAGE_VERIFIED: { 1611 final int verificationId = msg.arg1; 1612 1613 final PackageVerificationState state = mPendingVerification.get(verificationId); 1614 if (state == null) { 1615 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1616 break; 1617 } 1618 1619 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1620 1621 state.setVerifierResponse(response.callerUid, response.code); 1622 1623 if (state.isVerificationComplete()) { 1624 mPendingVerification.remove(verificationId); 1625 1626 final InstallArgs args = state.getInstallArgs(); 1627 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1628 1629 int ret; 1630 if (state.isInstallAllowed()) { 1631 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1632 broadcastPackageVerified(verificationId, originUri, 1633 response.code, state.getInstallArgs().getUser()); 1634 try { 1635 ret = args.copyApk(mContainerService, true); 1636 } catch (RemoteException e) { 1637 Slog.e(TAG, "Could not contact the ContainerService"); 1638 } 1639 } else { 1640 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1641 } 1642 1643 Trace.asyncTraceEnd( 1644 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1645 1646 processPendingInstall(args, ret); 1647 mHandler.sendEmptyMessage(MCS_UNBIND); 1648 } 1649 1650 break; 1651 } 1652 case START_INTENT_FILTER_VERIFICATIONS: { 1653 IFVerificationParams params = (IFVerificationParams) msg.obj; 1654 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1655 params.replacing, params.pkg); 1656 break; 1657 } 1658 case INTENT_FILTER_VERIFIED: { 1659 final int verificationId = msg.arg1; 1660 1661 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1662 verificationId); 1663 if (state == null) { 1664 Slog.w(TAG, "Invalid IntentFilter verification token " 1665 + verificationId + " received"); 1666 break; 1667 } 1668 1669 final int userId = state.getUserId(); 1670 1671 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1672 "Processing IntentFilter verification with token:" 1673 + verificationId + " and userId:" + userId); 1674 1675 final IntentFilterVerificationResponse response = 1676 (IntentFilterVerificationResponse) msg.obj; 1677 1678 state.setVerifierResponse(response.callerUid, response.code); 1679 1680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1681 "IntentFilter verification with token:" + verificationId 1682 + " and userId:" + userId 1683 + " is settings verifier response with response code:" 1684 + response.code); 1685 1686 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1688 + response.getFailedDomainsString()); 1689 } 1690 1691 if (state.isVerificationComplete()) { 1692 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1693 } else { 1694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1695 "IntentFilter verification with token:" + verificationId 1696 + " was not said to be complete"); 1697 } 1698 1699 break; 1700 } 1701 } 1702 } 1703 } 1704 1705 private StorageEventListener mStorageListener = new StorageEventListener() { 1706 @Override 1707 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1708 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1709 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1710 final String volumeUuid = vol.getFsUuid(); 1711 1712 // Clean up any users or apps that were removed or recreated 1713 // while this volume was missing 1714 reconcileUsers(volumeUuid); 1715 reconcileApps(volumeUuid); 1716 1717 // Clean up any install sessions that expired or were 1718 // cancelled while this volume was missing 1719 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1720 1721 loadPrivatePackages(vol); 1722 1723 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1724 unloadPrivatePackages(vol); 1725 } 1726 } 1727 1728 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1729 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1730 updateExternalMediaStatus(true, false); 1731 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1732 updateExternalMediaStatus(false, false); 1733 } 1734 } 1735 } 1736 1737 @Override 1738 public void onVolumeForgotten(String fsUuid) { 1739 if (TextUtils.isEmpty(fsUuid)) { 1740 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1741 return; 1742 } 1743 1744 // Remove any apps installed on the forgotten volume 1745 synchronized (mPackages) { 1746 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1747 for (PackageSetting ps : packages) { 1748 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1749 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1750 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1751 } 1752 1753 mSettings.onVolumeForgotten(fsUuid); 1754 mSettings.writeLPr(); 1755 } 1756 } 1757 }; 1758 1759 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1760 String[] grantedPermissions) { 1761 if (userId >= UserHandle.USER_SYSTEM) { 1762 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1763 } else if (userId == UserHandle.USER_ALL) { 1764 final int[] userIds; 1765 synchronized (mPackages) { 1766 userIds = UserManagerService.getInstance().getUserIds(); 1767 } 1768 for (int someUserId : userIds) { 1769 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1770 } 1771 } 1772 1773 // We could have touched GID membership, so flush out packages.list 1774 synchronized (mPackages) { 1775 mSettings.writePackageListLPr(); 1776 } 1777 } 1778 1779 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1780 String[] grantedPermissions) { 1781 SettingBase sb = (SettingBase) pkg.mExtras; 1782 if (sb == null) { 1783 return; 1784 } 1785 1786 PermissionsState permissionsState = sb.getPermissionsState(); 1787 1788 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1789 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1790 1791 synchronized (mPackages) { 1792 for (String permission : pkg.requestedPermissions) { 1793 BasePermission bp = mSettings.mPermissions.get(permission); 1794 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1795 && (grantedPermissions == null 1796 || ArrayUtils.contains(grantedPermissions, permission))) { 1797 final int flags = permissionsState.getPermissionFlags(permission, userId); 1798 // Installer cannot change immutable permissions. 1799 if ((flags & immutableFlags) == 0) { 1800 grantRuntimePermission(pkg.packageName, permission, userId); 1801 } 1802 } 1803 } 1804 } 1805 } 1806 1807 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1808 Bundle extras = null; 1809 switch (res.returnCode) { 1810 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1811 extras = new Bundle(); 1812 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1813 res.origPermission); 1814 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1815 res.origPackage); 1816 break; 1817 } 1818 case PackageManager.INSTALL_SUCCEEDED: { 1819 extras = new Bundle(); 1820 extras.putBoolean(Intent.EXTRA_REPLACING, 1821 res.removedInfo != null && res.removedInfo.removedPackage != null); 1822 break; 1823 } 1824 } 1825 return extras; 1826 } 1827 1828 void scheduleWriteSettingsLocked() { 1829 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1830 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1831 } 1832 } 1833 1834 void scheduleWritePackageRestrictionsLocked(int userId) { 1835 if (!sUserManager.exists(userId)) return; 1836 mDirtyUsers.add(userId); 1837 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1838 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1839 } 1840 } 1841 1842 public static PackageManagerService main(Context context, Installer installer, 1843 boolean factoryTest, boolean onlyCore) { 1844 PackageManagerService m = new PackageManagerService(context, installer, 1845 factoryTest, onlyCore); 1846 m.enableSystemUserApps(); 1847 ServiceManager.addService("package", m); 1848 return m; 1849 } 1850 1851 private void enableSystemUserApps() { 1852 if (!UserManager.isSplitSystemUser()) { 1853 return; 1854 } 1855 // For system user, enable apps based on the following conditions: 1856 // - app is whitelisted or belong to one of these groups: 1857 // -- system app which has no launcher icons 1858 // -- system app which has INTERACT_ACROSS_USERS permission 1859 // -- system IME app 1860 // - app is not in the blacklist 1861 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1862 Set<String> enableApps = new ArraySet<>(); 1863 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1864 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1865 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1866 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1867 enableApps.addAll(wlApps); 1868 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1869 enableApps.removeAll(blApps); 1870 1871 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1872 UserHandle.SYSTEM); 1873 final int systemAppsSize = systemApps.size(); 1874 synchronized (mPackages) { 1875 for (int i = 0; i < systemAppsSize; i++) { 1876 String pName = systemApps.get(i); 1877 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1878 // Should not happen, but we shouldn't be failing if it does 1879 if (pkgSetting == null) { 1880 continue; 1881 } 1882 boolean installed = enableApps.contains(pName); 1883 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1884 } 1885 } 1886 } 1887 1888 static String[] splitString(String str, char sep) { 1889 int count = 1; 1890 int i = 0; 1891 while ((i=str.indexOf(sep, i)) >= 0) { 1892 count++; 1893 i++; 1894 } 1895 1896 String[] res = new String[count]; 1897 i=0; 1898 count = 0; 1899 int lastI=0; 1900 while ((i=str.indexOf(sep, i)) >= 0) { 1901 res[count] = str.substring(lastI, i); 1902 count++; 1903 i++; 1904 lastI = i; 1905 } 1906 res[count] = str.substring(lastI, str.length()); 1907 return res; 1908 } 1909 1910 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1911 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1912 Context.DISPLAY_SERVICE); 1913 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1914 } 1915 1916 public PackageManagerService(Context context, Installer installer, 1917 boolean factoryTest, boolean onlyCore) { 1918 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1919 SystemClock.uptimeMillis()); 1920 1921 if (mSdkVersion <= 0) { 1922 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1923 } 1924 1925 mContext = context; 1926 mFactoryTest = factoryTest; 1927 mOnlyCore = onlyCore; 1928 mMetrics = new DisplayMetrics(); 1929 mSettings = new Settings(mPackages); 1930 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1931 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1932 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1933 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1934 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1935 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1936 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1937 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1938 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1939 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1940 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1941 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1942 1943 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1944 if (separateProcesses != null && separateProcesses.length() > 0) { 1945 if ("*".equals(separateProcesses)) { 1946 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1947 mSeparateProcesses = null; 1948 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1949 } else { 1950 mDefParseFlags = 0; 1951 mSeparateProcesses = separateProcesses.split(","); 1952 Slog.w(TAG, "Running with debug.separate_processes: " 1953 + separateProcesses); 1954 } 1955 } else { 1956 mDefParseFlags = 0; 1957 mSeparateProcesses = null; 1958 } 1959 1960 mInstaller = installer; 1961 mPackageDexOptimizer = new PackageDexOptimizer(this); 1962 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1963 1964 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1965 FgThread.get().getLooper()); 1966 1967 getDefaultDisplayMetrics(context, mMetrics); 1968 1969 SystemConfig systemConfig = SystemConfig.getInstance(); 1970 mGlobalGids = systemConfig.getGlobalGids(); 1971 mSystemPermissions = systemConfig.getSystemPermissions(); 1972 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1973 1974 synchronized (mInstallLock) { 1975 // writer 1976 synchronized (mPackages) { 1977 mHandlerThread = new ServiceThread(TAG, 1978 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1979 mHandlerThread.start(); 1980 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1981 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1982 1983 File dataDir = Environment.getDataDirectory(); 1984 mAppInstallDir = new File(dataDir, "app"); 1985 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1986 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1987 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 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 2409 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2410 } // synchronized (mPackages) 2411 } // synchronized (mInstallLock) 2412 2413 // Now after opening every single application zip, make sure they 2414 // are all flushed. Not really needed, but keeps things nice and 2415 // tidy. 2416 Runtime.getRuntime().gc(); 2417 2418 // The initial scanning above does many calls into installd while 2419 // holding the mPackages lock, but we're mostly interested in yelling 2420 // once we have a booted system. 2421 mInstaller.setWarnIfHeld(mPackages); 2422 2423 // Expose private service for system components to use. 2424 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2425 } 2426 2427 @Override 2428 public boolean isFirstBoot() { 2429 return !mRestoredSettings; 2430 } 2431 2432 @Override 2433 public boolean isOnlyCoreApps() { 2434 return mOnlyCore; 2435 } 2436 2437 @Override 2438 public boolean isUpgrade() { 2439 return mIsUpgrade; 2440 } 2441 2442 private String getRequiredVerifierLPr() { 2443 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2444 // We only care about verifier that's installed under system user. 2445 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2446 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2447 2448 String requiredVerifier = null; 2449 2450 final int N = receivers.size(); 2451 for (int i = 0; i < N; i++) { 2452 final ResolveInfo info = receivers.get(i); 2453 2454 if (info.activityInfo == null) { 2455 continue; 2456 } 2457 2458 final String packageName = info.activityInfo.packageName; 2459 2460 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2461 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2462 continue; 2463 } 2464 2465 if (requiredVerifier != null) { 2466 throw new RuntimeException("There can be only one required verifier"); 2467 } 2468 2469 requiredVerifier = packageName; 2470 } 2471 2472 return requiredVerifier; 2473 } 2474 2475 private String getRequiredInstallerLPr() { 2476 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2477 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2478 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2479 2480 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2481 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2482 2483 String requiredInstaller = null; 2484 2485 final int N = installers.size(); 2486 for (int i = 0; i < N; i++) { 2487 final ResolveInfo info = installers.get(i); 2488 final String packageName = info.activityInfo.packageName; 2489 2490 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2491 continue; 2492 } 2493 2494 if (requiredInstaller != null) { 2495 throw new RuntimeException("There must be one required installer"); 2496 } 2497 2498 requiredInstaller = packageName; 2499 } 2500 2501 if (requiredInstaller == null) { 2502 throw new RuntimeException("There must be one required installer"); 2503 } 2504 2505 return requiredInstaller; 2506 } 2507 2508 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2509 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2510 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2511 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2512 2513 ComponentName verifierComponentName = null; 2514 2515 int priority = -1000; 2516 final int N = receivers.size(); 2517 for (int i = 0; i < N; i++) { 2518 final ResolveInfo info = receivers.get(i); 2519 2520 if (info.activityInfo == null) { 2521 continue; 2522 } 2523 2524 final String packageName = info.activityInfo.packageName; 2525 2526 final PackageSetting ps = mSettings.mPackages.get(packageName); 2527 if (ps == null) { 2528 continue; 2529 } 2530 2531 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2532 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2533 continue; 2534 } 2535 2536 // Select the IntentFilterVerifier with the highest priority 2537 if (priority < info.priority) { 2538 priority = info.priority; 2539 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2541 + verifierComponentName + " with priority: " + info.priority); 2542 } 2543 } 2544 2545 return verifierComponentName; 2546 } 2547 2548 private ComponentName getEphemeralResolverLPr() { 2549 final String[] packageArray = 2550 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2551 if (packageArray.length == 0) { 2552 if (DEBUG_EPHEMERAL) { 2553 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2554 } 2555 return null; 2556 } 2557 2558 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2559 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2560 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2561 2562 final int N = resolvers.size(); 2563 if (N == 0) { 2564 if (DEBUG_EPHEMERAL) { 2565 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2566 } 2567 return null; 2568 } 2569 2570 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2571 for (int i = 0; i < N; i++) { 2572 final ResolveInfo info = resolvers.get(i); 2573 2574 if (info.serviceInfo == null) { 2575 continue; 2576 } 2577 2578 final String packageName = info.serviceInfo.packageName; 2579 if (!possiblePackages.contains(packageName)) { 2580 if (DEBUG_EPHEMERAL) { 2581 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2582 + " pkg: " + packageName + ", info:" + info); 2583 } 2584 continue; 2585 } 2586 2587 if (DEBUG_EPHEMERAL) { 2588 Slog.v(TAG, "Ephemeral resolver found;" 2589 + " pkg: " + packageName + ", info:" + info); 2590 } 2591 return new ComponentName(packageName, info.serviceInfo.name); 2592 } 2593 if (DEBUG_EPHEMERAL) { 2594 Slog.v(TAG, "Ephemeral resolver NOT found"); 2595 } 2596 return null; 2597 } 2598 2599 private ComponentName getEphemeralInstallerLPr() { 2600 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2601 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2602 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2603 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2604 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2605 2606 ComponentName ephemeralInstaller = null; 2607 2608 final int N = installers.size(); 2609 for (int i = 0; i < N; i++) { 2610 final ResolveInfo info = installers.get(i); 2611 final String packageName = info.activityInfo.packageName; 2612 2613 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2614 if (DEBUG_EPHEMERAL) { 2615 Slog.d(TAG, "Ephemeral installer is not system app;" 2616 + " pkg: " + packageName + ", info:" + info); 2617 } 2618 continue; 2619 } 2620 2621 if (ephemeralInstaller != null) { 2622 throw new RuntimeException("There must only be one ephemeral installer"); 2623 } 2624 2625 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2626 } 2627 2628 return ephemeralInstaller; 2629 } 2630 2631 private void primeDomainVerificationsLPw(int userId) { 2632 if (DEBUG_DOMAIN_VERIFICATION) { 2633 Slog.d(TAG, "Priming domain verifications in user " + userId); 2634 } 2635 2636 SystemConfig systemConfig = SystemConfig.getInstance(); 2637 ArraySet<String> packages = systemConfig.getLinkedApps(); 2638 ArraySet<String> domains = new ArraySet<String>(); 2639 2640 for (String packageName : packages) { 2641 PackageParser.Package pkg = mPackages.get(packageName); 2642 if (pkg != null) { 2643 if (!pkg.isSystemApp()) { 2644 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2645 continue; 2646 } 2647 2648 domains.clear(); 2649 for (PackageParser.Activity a : pkg.activities) { 2650 for (ActivityIntentInfo filter : a.intents) { 2651 if (hasValidDomains(filter)) { 2652 domains.addAll(filter.getHostsList()); 2653 } 2654 } 2655 } 2656 2657 if (domains.size() > 0) { 2658 if (DEBUG_DOMAIN_VERIFICATION) { 2659 Slog.v(TAG, " + " + packageName); 2660 } 2661 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2662 // state w.r.t. the formal app-linkage "no verification attempted" state; 2663 // and then 'always' in the per-user state actually used for intent resolution. 2664 final IntentFilterVerificationInfo ivi; 2665 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2666 new ArrayList<String>(domains)); 2667 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2668 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2669 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2670 } else { 2671 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2672 + "' does not handle web links"); 2673 } 2674 } else { 2675 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2676 } 2677 } 2678 2679 scheduleWritePackageRestrictionsLocked(userId); 2680 scheduleWriteSettingsLocked(); 2681 } 2682 2683 private void applyFactoryDefaultBrowserLPw(int userId) { 2684 // The default browser app's package name is stored in a string resource, 2685 // with a product-specific overlay used for vendor customization. 2686 String browserPkg = mContext.getResources().getString( 2687 com.android.internal.R.string.default_browser); 2688 if (!TextUtils.isEmpty(browserPkg)) { 2689 // non-empty string => required to be a known package 2690 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2691 if (ps == null) { 2692 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2693 browserPkg = null; 2694 } else { 2695 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2696 } 2697 } 2698 2699 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2700 // default. If there's more than one, just leave everything alone. 2701 if (browserPkg == null) { 2702 calculateDefaultBrowserLPw(userId); 2703 } 2704 } 2705 2706 private void calculateDefaultBrowserLPw(int userId) { 2707 List<String> allBrowsers = resolveAllBrowserApps(userId); 2708 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2709 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2710 } 2711 2712 private List<String> resolveAllBrowserApps(int userId) { 2713 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2714 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2715 PackageManager.MATCH_ALL, userId); 2716 2717 final int count = list.size(); 2718 List<String> result = new ArrayList<String>(count); 2719 for (int i=0; i<count; i++) { 2720 ResolveInfo info = list.get(i); 2721 if (info.activityInfo == null 2722 || !info.handleAllWebDataURI 2723 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2724 || result.contains(info.activityInfo.packageName)) { 2725 continue; 2726 } 2727 result.add(info.activityInfo.packageName); 2728 } 2729 2730 return result; 2731 } 2732 2733 private boolean packageIsBrowser(String packageName, int userId) { 2734 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2735 PackageManager.MATCH_ALL, userId); 2736 final int N = list.size(); 2737 for (int i = 0; i < N; i++) { 2738 ResolveInfo info = list.get(i); 2739 if (packageName.equals(info.activityInfo.packageName)) { 2740 return true; 2741 } 2742 } 2743 return false; 2744 } 2745 2746 private void checkDefaultBrowser() { 2747 final int myUserId = UserHandle.myUserId(); 2748 final String packageName = getDefaultBrowserPackageName(myUserId); 2749 if (packageName != null) { 2750 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2751 if (info == null) { 2752 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2753 synchronized (mPackages) { 2754 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2755 } 2756 } 2757 } 2758 } 2759 2760 @Override 2761 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2762 throws RemoteException { 2763 try { 2764 return super.onTransact(code, data, reply, flags); 2765 } catch (RuntimeException e) { 2766 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2767 Slog.wtf(TAG, "Package Manager Crash", e); 2768 } 2769 throw e; 2770 } 2771 } 2772 2773 void cleanupInstallFailedPackage(PackageSetting ps) { 2774 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2775 2776 removeDataDirsLI(ps.volumeUuid, ps.name); 2777 if (ps.codePath != null) { 2778 if (ps.codePath.isDirectory()) { 2779 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2780 } else { 2781 ps.codePath.delete(); 2782 } 2783 } 2784 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2785 if (ps.resourcePath.isDirectory()) { 2786 FileUtils.deleteContents(ps.resourcePath); 2787 } 2788 ps.resourcePath.delete(); 2789 } 2790 mSettings.removePackageLPw(ps.name); 2791 } 2792 2793 static int[] appendInts(int[] cur, int[] add) { 2794 if (add == null) return cur; 2795 if (cur == null) return add; 2796 final int N = add.length; 2797 for (int i=0; i<N; i++) { 2798 cur = appendInt(cur, add[i]); 2799 } 2800 return cur; 2801 } 2802 2803 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2804 if (!sUserManager.exists(userId)) return null; 2805 final PackageSetting ps = (PackageSetting) p.mExtras; 2806 if (ps == null) { 2807 return null; 2808 } 2809 2810 final PermissionsState permissionsState = ps.getPermissionsState(); 2811 2812 final int[] gids = permissionsState.computeGids(userId); 2813 final Set<String> permissions = permissionsState.getPermissions(userId); 2814 final PackageUserState state = ps.readUserState(userId); 2815 2816 return PackageParser.generatePackageInfo(p, gids, flags, 2817 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2818 } 2819 2820 @Override 2821 public void checkPackageStartable(String packageName, int userId) { 2822 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2823 2824 synchronized (mPackages) { 2825 final PackageSetting ps = mSettings.mPackages.get(packageName); 2826 if (ps == null) { 2827 throw new SecurityException("Package " + packageName + " was not found!"); 2828 } 2829 2830 if (ps.frozen) { 2831 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2832 } 2833 2834 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2835 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2836 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2837 } 2838 } 2839 } 2840 2841 @Override 2842 public boolean isPackageAvailable(String packageName, int userId) { 2843 if (!sUserManager.exists(userId)) return false; 2844 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2845 synchronized (mPackages) { 2846 PackageParser.Package p = mPackages.get(packageName); 2847 if (p != null) { 2848 final PackageSetting ps = (PackageSetting) p.mExtras; 2849 if (ps != null) { 2850 final PackageUserState state = ps.readUserState(userId); 2851 if (state != null) { 2852 return PackageParser.isAvailable(state); 2853 } 2854 } 2855 } 2856 } 2857 return false; 2858 } 2859 2860 @Override 2861 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2862 if (!sUserManager.exists(userId)) return null; 2863 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2864 // reader 2865 synchronized (mPackages) { 2866 PackageParser.Package p = mPackages.get(packageName); 2867 if (DEBUG_PACKAGE_INFO) 2868 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2869 if (p != null) { 2870 return generatePackageInfo(p, flags, userId); 2871 } 2872 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2873 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2874 } 2875 } 2876 return null; 2877 } 2878 2879 @Override 2880 public String[] currentToCanonicalPackageNames(String[] names) { 2881 String[] out = new String[names.length]; 2882 // reader 2883 synchronized (mPackages) { 2884 for (int i=names.length-1; i>=0; i--) { 2885 PackageSetting ps = mSettings.mPackages.get(names[i]); 2886 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2887 } 2888 } 2889 return out; 2890 } 2891 2892 @Override 2893 public String[] canonicalToCurrentPackageNames(String[] names) { 2894 String[] out = new String[names.length]; 2895 // reader 2896 synchronized (mPackages) { 2897 for (int i=names.length-1; i>=0; i--) { 2898 String cur = mSettings.mRenamedPackages.get(names[i]); 2899 out[i] = cur != null ? cur : names[i]; 2900 } 2901 } 2902 return out; 2903 } 2904 2905 @Override 2906 public int getPackageUid(String packageName, int userId) { 2907 return getPackageUidEtc(packageName, 0, userId); 2908 } 2909 2910 @Override 2911 public int getPackageUidEtc(String packageName, int flags, int userId) { 2912 if (!sUserManager.exists(userId)) return -1; 2913 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2914 2915 // reader 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(packageName); 2918 if (p != null) { 2919 return UserHandle.getUid(userId, p.applicationInfo.uid); 2920 } 2921 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2922 final PackageSetting ps = mSettings.mPackages.get(packageName); 2923 if (ps != null) { 2924 return UserHandle.getUid(userId, ps.appId); 2925 } 2926 } 2927 } 2928 2929 return -1; 2930 } 2931 2932 @Override 2933 public int[] getPackageGids(String packageName, int userId) { 2934 return getPackageGidsEtc(packageName, 0, userId); 2935 } 2936 2937 @Override 2938 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2939 if (!sUserManager.exists(userId)) { 2940 return null; 2941 } 2942 2943 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2944 "getPackageGids"); 2945 2946 // reader 2947 synchronized (mPackages) { 2948 final PackageParser.Package p = mPackages.get(packageName); 2949 if (p != null) { 2950 PackageSetting ps = (PackageSetting) p.mExtras; 2951 return ps.getPermissionsState().computeGids(userId); 2952 } 2953 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2954 final PackageSetting ps = mSettings.mPackages.get(packageName); 2955 if (ps != null) { 2956 return ps.getPermissionsState().computeGids(userId); 2957 } 2958 } 2959 } 2960 2961 return null; 2962 } 2963 2964 static PermissionInfo generatePermissionInfo( 2965 BasePermission bp, int flags) { 2966 if (bp.perm != null) { 2967 return PackageParser.generatePermissionInfo(bp.perm, flags); 2968 } 2969 PermissionInfo pi = new PermissionInfo(); 2970 pi.name = bp.name; 2971 pi.packageName = bp.sourcePackage; 2972 pi.nonLocalizedLabel = bp.name; 2973 pi.protectionLevel = bp.protectionLevel; 2974 return pi; 2975 } 2976 2977 @Override 2978 public PermissionInfo getPermissionInfo(String name, int flags) { 2979 // reader 2980 synchronized (mPackages) { 2981 final BasePermission p = mSettings.mPermissions.get(name); 2982 if (p != null) { 2983 return generatePermissionInfo(p, flags); 2984 } 2985 return null; 2986 } 2987 } 2988 2989 @Override 2990 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2991 // reader 2992 synchronized (mPackages) { 2993 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2994 for (BasePermission p : mSettings.mPermissions.values()) { 2995 if (group == null) { 2996 if (p.perm == null || p.perm.info.group == null) { 2997 out.add(generatePermissionInfo(p, flags)); 2998 } 2999 } else { 3000 if (p.perm != null && group.equals(p.perm.info.group)) { 3001 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3002 } 3003 } 3004 } 3005 3006 if (out.size() > 0) { 3007 return out; 3008 } 3009 return mPermissionGroups.containsKey(group) ? out : null; 3010 } 3011 } 3012 3013 @Override 3014 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3015 // reader 3016 synchronized (mPackages) { 3017 return PackageParser.generatePermissionGroupInfo( 3018 mPermissionGroups.get(name), flags); 3019 } 3020 } 3021 3022 @Override 3023 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3024 // reader 3025 synchronized (mPackages) { 3026 final int N = mPermissionGroups.size(); 3027 ArrayList<PermissionGroupInfo> out 3028 = new ArrayList<PermissionGroupInfo>(N); 3029 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3030 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3031 } 3032 return out; 3033 } 3034 } 3035 3036 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3037 int userId) { 3038 if (!sUserManager.exists(userId)) return null; 3039 PackageSetting ps = mSettings.mPackages.get(packageName); 3040 if (ps != null) { 3041 if (ps.pkg == null) { 3042 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3043 flags, userId); 3044 if (pInfo != null) { 3045 return pInfo.applicationInfo; 3046 } 3047 return null; 3048 } 3049 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3050 ps.readUserState(userId), userId); 3051 } 3052 return null; 3053 } 3054 3055 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3056 int userId) { 3057 if (!sUserManager.exists(userId)) return null; 3058 PackageSetting ps = mSettings.mPackages.get(packageName); 3059 if (ps != null) { 3060 PackageParser.Package pkg = ps.pkg; 3061 if (pkg == null) { 3062 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3063 return null; 3064 } 3065 // Only data remains, so we aren't worried about code paths 3066 pkg = new PackageParser.Package(packageName); 3067 pkg.applicationInfo.packageName = packageName; 3068 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3069 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3070 pkg.applicationInfo.uid = ps.appId; 3071 pkg.applicationInfo.initForUser(userId); 3072 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3073 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3074 } 3075 return generatePackageInfo(pkg, flags, userId); 3076 } 3077 return null; 3078 } 3079 3080 @Override 3081 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3082 if (!sUserManager.exists(userId)) return null; 3083 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3084 // writer 3085 synchronized (mPackages) { 3086 PackageParser.Package p = mPackages.get(packageName); 3087 if (DEBUG_PACKAGE_INFO) Log.v( 3088 TAG, "getApplicationInfo " + packageName 3089 + ": " + p); 3090 if (p != null) { 3091 PackageSetting ps = mSettings.mPackages.get(packageName); 3092 if (ps == null) return null; 3093 // Note: isEnabledLP() does not apply here - always return info 3094 return PackageParser.generateApplicationInfo( 3095 p, flags, ps.readUserState(userId), userId); 3096 } 3097 if ("android".equals(packageName)||"system".equals(packageName)) { 3098 return mAndroidApplication; 3099 } 3100 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3101 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3102 } 3103 } 3104 return null; 3105 } 3106 3107 @Override 3108 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3109 final IPackageDataObserver observer) { 3110 mContext.enforceCallingOrSelfPermission( 3111 android.Manifest.permission.CLEAR_APP_CACHE, null); 3112 // Queue up an async operation since clearing cache may take a little while. 3113 mHandler.post(new Runnable() { 3114 public void run() { 3115 mHandler.removeCallbacks(this); 3116 int retCode = -1; 3117 synchronized (mInstallLock) { 3118 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3119 if (retCode < 0) { 3120 Slog.w(TAG, "Couldn't clear application caches"); 3121 } 3122 } 3123 if (observer != null) { 3124 try { 3125 observer.onRemoveCompleted(null, (retCode >= 0)); 3126 } catch (RemoteException e) { 3127 Slog.w(TAG, "RemoveException when invoking call back"); 3128 } 3129 } 3130 } 3131 }); 3132 } 3133 3134 @Override 3135 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3136 final IntentSender pi) { 3137 mContext.enforceCallingOrSelfPermission( 3138 android.Manifest.permission.CLEAR_APP_CACHE, null); 3139 // Queue up an async operation since clearing cache may take a little while. 3140 mHandler.post(new Runnable() { 3141 public void run() { 3142 mHandler.removeCallbacks(this); 3143 int retCode = -1; 3144 synchronized (mInstallLock) { 3145 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3146 if (retCode < 0) { 3147 Slog.w(TAG, "Couldn't clear application caches"); 3148 } 3149 } 3150 if(pi != null) { 3151 try { 3152 // Callback via pending intent 3153 int code = (retCode >= 0) ? 1 : 0; 3154 pi.sendIntent(null, code, null, 3155 null, null); 3156 } catch (SendIntentException e1) { 3157 Slog.i(TAG, "Failed to send pending intent"); 3158 } 3159 } 3160 } 3161 }); 3162 } 3163 3164 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3165 synchronized (mInstallLock) { 3166 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3167 throw new IOException("Failed to free enough space"); 3168 } 3169 } 3170 } 3171 3172 /** 3173 * Return if the user key is currently unlocked. 3174 */ 3175 private boolean isUserKeyUnlocked(int userId) { 3176 if (StorageManager.isFileBasedEncryptionEnabled()) { 3177 final IMountService mount = IMountService.Stub 3178 .asInterface(ServiceManager.getService("mount")); 3179 if (mount == null) { 3180 Slog.w(TAG, "Early during boot, assuming locked"); 3181 return false; 3182 } 3183 final long token = Binder.clearCallingIdentity(); 3184 try { 3185 return mount.isUserKeyUnlocked(userId); 3186 } catch (RemoteException e) { 3187 throw e.rethrowAsRuntimeException(); 3188 } finally { 3189 Binder.restoreCallingIdentity(token); 3190 } 3191 } else { 3192 return true; 3193 } 3194 } 3195 3196 /** 3197 * Augment the given flags depending on current user running state. This is 3198 * purposefully done before acquiring {@link #mPackages} lock. 3199 */ 3200 private int augmentFlagsForUser(int flags, int userId) { 3201 if (!isUserKeyUnlocked(userId)) { 3202 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3203 } 3204 return flags; 3205 } 3206 3207 @Override 3208 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return null; 3210 flags = augmentFlagsForUser(flags, userId); 3211 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3212 synchronized (mPackages) { 3213 PackageParser.Activity a = mActivities.mActivities.get(component); 3214 3215 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3216 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3217 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3218 if (ps == null) return null; 3219 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3220 userId); 3221 } 3222 if (mResolveComponentName.equals(component)) { 3223 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3224 new PackageUserState(), userId); 3225 } 3226 } 3227 return null; 3228 } 3229 3230 @Override 3231 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3232 String resolvedType) { 3233 synchronized (mPackages) { 3234 if (component.equals(mResolveComponentName)) { 3235 // The resolver supports EVERYTHING! 3236 return true; 3237 } 3238 PackageParser.Activity a = mActivities.mActivities.get(component); 3239 if (a == null) { 3240 return false; 3241 } 3242 for (int i=0; i<a.intents.size(); i++) { 3243 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3244 intent.getData(), intent.getCategories(), TAG) >= 0) { 3245 return true; 3246 } 3247 } 3248 return false; 3249 } 3250 } 3251 3252 @Override 3253 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return null; 3255 flags = augmentFlagsForUser(flags, userId); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3257 synchronized (mPackages) { 3258 PackageParser.Activity a = mReceivers.mActivities.get(component); 3259 if (DEBUG_PACKAGE_INFO) Log.v( 3260 TAG, "getReceiverInfo " + component + ": " + a); 3261 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3262 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3263 if (ps == null) return null; 3264 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3265 userId); 3266 } 3267 } 3268 return null; 3269 } 3270 3271 @Override 3272 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3273 if (!sUserManager.exists(userId)) return null; 3274 flags = augmentFlagsForUser(flags, userId); 3275 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3276 synchronized (mPackages) { 3277 PackageParser.Service s = mServices.mServices.get(component); 3278 if (DEBUG_PACKAGE_INFO) Log.v( 3279 TAG, "getServiceInfo " + component + ": " + s); 3280 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3281 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3282 if (ps == null) return null; 3283 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3284 userId); 3285 } 3286 } 3287 return null; 3288 } 3289 3290 @Override 3291 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3292 if (!sUserManager.exists(userId)) return null; 3293 flags = augmentFlagsForUser(flags, userId); 3294 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3295 synchronized (mPackages) { 3296 PackageParser.Provider p = mProviders.mProviders.get(component); 3297 if (DEBUG_PACKAGE_INFO) Log.v( 3298 TAG, "getProviderInfo " + component + ": " + p); 3299 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3300 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3301 if (ps == null) return null; 3302 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3303 userId); 3304 } 3305 } 3306 return null; 3307 } 3308 3309 @Override 3310 public String[] getSystemSharedLibraryNames() { 3311 Set<String> libSet; 3312 synchronized (mPackages) { 3313 libSet = mSharedLibraries.keySet(); 3314 int size = libSet.size(); 3315 if (size > 0) { 3316 String[] libs = new String[size]; 3317 libSet.toArray(libs); 3318 return libs; 3319 } 3320 } 3321 return null; 3322 } 3323 3324 /** 3325 * @hide 3326 */ 3327 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3328 synchronized (mPackages) { 3329 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3330 if (lib != null && lib.apk != null) { 3331 return mPackages.get(lib.apk); 3332 } 3333 } 3334 return null; 3335 } 3336 3337 @Override 3338 public FeatureInfo[] getSystemAvailableFeatures() { 3339 Collection<FeatureInfo> featSet; 3340 synchronized (mPackages) { 3341 featSet = mAvailableFeatures.values(); 3342 int size = featSet.size(); 3343 if (size > 0) { 3344 FeatureInfo[] features = new FeatureInfo[size+1]; 3345 featSet.toArray(features); 3346 FeatureInfo fi = new FeatureInfo(); 3347 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3348 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3349 features[size] = fi; 3350 return features; 3351 } 3352 } 3353 return null; 3354 } 3355 3356 @Override 3357 public boolean hasSystemFeature(String name) { 3358 synchronized (mPackages) { 3359 return mAvailableFeatures.containsKey(name); 3360 } 3361 } 3362 3363 @Override 3364 public int checkPermission(String permName, String pkgName, int userId) { 3365 if (!sUserManager.exists(userId)) { 3366 return PackageManager.PERMISSION_DENIED; 3367 } 3368 3369 synchronized (mPackages) { 3370 final PackageParser.Package p = mPackages.get(pkgName); 3371 if (p != null && p.mExtras != null) { 3372 final PackageSetting ps = (PackageSetting) p.mExtras; 3373 final PermissionsState permissionsState = ps.getPermissionsState(); 3374 if (permissionsState.hasPermission(permName, userId)) { 3375 return PackageManager.PERMISSION_GRANTED; 3376 } 3377 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3378 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3379 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3380 return PackageManager.PERMISSION_GRANTED; 3381 } 3382 } 3383 } 3384 3385 return PackageManager.PERMISSION_DENIED; 3386 } 3387 3388 @Override 3389 public int checkUidPermission(String permName, int uid) { 3390 final int userId = UserHandle.getUserId(uid); 3391 3392 if (!sUserManager.exists(userId)) { 3393 return PackageManager.PERMISSION_DENIED; 3394 } 3395 3396 synchronized (mPackages) { 3397 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3398 if (obj != null) { 3399 final SettingBase ps = (SettingBase) obj; 3400 final PermissionsState permissionsState = ps.getPermissionsState(); 3401 if (permissionsState.hasPermission(permName, userId)) { 3402 return PackageManager.PERMISSION_GRANTED; 3403 } 3404 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3405 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3406 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3407 return PackageManager.PERMISSION_GRANTED; 3408 } 3409 } else { 3410 ArraySet<String> perms = mSystemPermissions.get(uid); 3411 if (perms != null) { 3412 if (perms.contains(permName)) { 3413 return PackageManager.PERMISSION_GRANTED; 3414 } 3415 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3416 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3417 return PackageManager.PERMISSION_GRANTED; 3418 } 3419 } 3420 } 3421 } 3422 3423 return PackageManager.PERMISSION_DENIED; 3424 } 3425 3426 @Override 3427 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3428 if (UserHandle.getCallingUserId() != userId) { 3429 mContext.enforceCallingPermission( 3430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3431 "isPermissionRevokedByPolicy for user " + userId); 3432 } 3433 3434 if (checkPermission(permission, packageName, userId) 3435 == PackageManager.PERMISSION_GRANTED) { 3436 return false; 3437 } 3438 3439 final long identity = Binder.clearCallingIdentity(); 3440 try { 3441 final int flags = getPermissionFlags(permission, packageName, userId); 3442 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3443 } finally { 3444 Binder.restoreCallingIdentity(identity); 3445 } 3446 } 3447 3448 @Override 3449 public String getPermissionControllerPackageName() { 3450 synchronized (mPackages) { 3451 return mRequiredInstallerPackage; 3452 } 3453 } 3454 3455 /** 3456 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3457 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3458 * @param checkShell TODO(yamasani): 3459 * @param message the message to log on security exception 3460 */ 3461 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3462 boolean checkShell, String message) { 3463 if (userId < 0) { 3464 throw new IllegalArgumentException("Invalid userId " + userId); 3465 } 3466 if (checkShell) { 3467 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3468 } 3469 if (userId == UserHandle.getUserId(callingUid)) return; 3470 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3471 if (requireFullPermission) { 3472 mContext.enforceCallingOrSelfPermission( 3473 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3474 } else { 3475 try { 3476 mContext.enforceCallingOrSelfPermission( 3477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3478 } catch (SecurityException se) { 3479 mContext.enforceCallingOrSelfPermission( 3480 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3481 } 3482 } 3483 } 3484 } 3485 3486 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3487 if (callingUid == Process.SHELL_UID) { 3488 if (userHandle >= 0 3489 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3490 throw new SecurityException("Shell does not have permission to access user " 3491 + userHandle); 3492 } else if (userHandle < 0) { 3493 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3494 + Debug.getCallers(3)); 3495 } 3496 } 3497 } 3498 3499 private BasePermission findPermissionTreeLP(String permName) { 3500 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3501 if (permName.startsWith(bp.name) && 3502 permName.length() > bp.name.length() && 3503 permName.charAt(bp.name.length()) == '.') { 3504 return bp; 3505 } 3506 } 3507 return null; 3508 } 3509 3510 private BasePermission checkPermissionTreeLP(String permName) { 3511 if (permName != null) { 3512 BasePermission bp = findPermissionTreeLP(permName); 3513 if (bp != null) { 3514 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3515 return bp; 3516 } 3517 throw new SecurityException("Calling uid " 3518 + Binder.getCallingUid() 3519 + " is not allowed to add to permission tree " 3520 + bp.name + " owned by uid " + bp.uid); 3521 } 3522 } 3523 throw new SecurityException("No permission tree found for " + permName); 3524 } 3525 3526 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3527 if (s1 == null) { 3528 return s2 == null; 3529 } 3530 if (s2 == null) { 3531 return false; 3532 } 3533 if (s1.getClass() != s2.getClass()) { 3534 return false; 3535 } 3536 return s1.equals(s2); 3537 } 3538 3539 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3540 if (pi1.icon != pi2.icon) return false; 3541 if (pi1.logo != pi2.logo) return false; 3542 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3543 if (!compareStrings(pi1.name, pi2.name)) return false; 3544 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3545 // We'll take care of setting this one. 3546 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3547 // These are not currently stored in settings. 3548 //if (!compareStrings(pi1.group, pi2.group)) return false; 3549 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3550 //if (pi1.labelRes != pi2.labelRes) return false; 3551 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3552 return true; 3553 } 3554 3555 int permissionInfoFootprint(PermissionInfo info) { 3556 int size = info.name.length(); 3557 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3558 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3559 return size; 3560 } 3561 3562 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3563 int size = 0; 3564 for (BasePermission perm : mSettings.mPermissions.values()) { 3565 if (perm.uid == tree.uid) { 3566 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3567 } 3568 } 3569 return size; 3570 } 3571 3572 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3573 // We calculate the max size of permissions defined by this uid and throw 3574 // if that plus the size of 'info' would exceed our stated maximum. 3575 if (tree.uid != Process.SYSTEM_UID) { 3576 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3577 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3578 throw new SecurityException("Permission tree size cap exceeded"); 3579 } 3580 } 3581 } 3582 3583 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3584 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3585 throw new SecurityException("Label must be specified in permission"); 3586 } 3587 BasePermission tree = checkPermissionTreeLP(info.name); 3588 BasePermission bp = mSettings.mPermissions.get(info.name); 3589 boolean added = bp == null; 3590 boolean changed = true; 3591 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3592 if (added) { 3593 enforcePermissionCapLocked(info, tree); 3594 bp = new BasePermission(info.name, tree.sourcePackage, 3595 BasePermission.TYPE_DYNAMIC); 3596 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3597 throw new SecurityException( 3598 "Not allowed to modify non-dynamic permission " 3599 + info.name); 3600 } else { 3601 if (bp.protectionLevel == fixedLevel 3602 && bp.perm.owner.equals(tree.perm.owner) 3603 && bp.uid == tree.uid 3604 && comparePermissionInfos(bp.perm.info, info)) { 3605 changed = false; 3606 } 3607 } 3608 bp.protectionLevel = fixedLevel; 3609 info = new PermissionInfo(info); 3610 info.protectionLevel = fixedLevel; 3611 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3612 bp.perm.info.packageName = tree.perm.info.packageName; 3613 bp.uid = tree.uid; 3614 if (added) { 3615 mSettings.mPermissions.put(info.name, bp); 3616 } 3617 if (changed) { 3618 if (!async) { 3619 mSettings.writeLPr(); 3620 } else { 3621 scheduleWriteSettingsLocked(); 3622 } 3623 } 3624 return added; 3625 } 3626 3627 @Override 3628 public boolean addPermission(PermissionInfo info) { 3629 synchronized (mPackages) { 3630 return addPermissionLocked(info, false); 3631 } 3632 } 3633 3634 @Override 3635 public boolean addPermissionAsync(PermissionInfo info) { 3636 synchronized (mPackages) { 3637 return addPermissionLocked(info, true); 3638 } 3639 } 3640 3641 @Override 3642 public void removePermission(String name) { 3643 synchronized (mPackages) { 3644 checkPermissionTreeLP(name); 3645 BasePermission bp = mSettings.mPermissions.get(name); 3646 if (bp != null) { 3647 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3648 throw new SecurityException( 3649 "Not allowed to modify non-dynamic permission " 3650 + name); 3651 } 3652 mSettings.mPermissions.remove(name); 3653 mSettings.writeLPr(); 3654 } 3655 } 3656 } 3657 3658 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3659 BasePermission bp) { 3660 int index = pkg.requestedPermissions.indexOf(bp.name); 3661 if (index == -1) { 3662 throw new SecurityException("Package " + pkg.packageName 3663 + " has not requested permission " + bp.name); 3664 } 3665 if (!bp.isRuntime() && !bp.isDevelopment()) { 3666 throw new SecurityException("Permission " + bp.name 3667 + " is not a changeable permission type"); 3668 } 3669 } 3670 3671 @Override 3672 public void grantRuntimePermission(String packageName, String name, final int userId) { 3673 if (!sUserManager.exists(userId)) { 3674 Log.e(TAG, "No such user:" + userId); 3675 return; 3676 } 3677 3678 mContext.enforceCallingOrSelfPermission( 3679 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3680 "grantRuntimePermission"); 3681 3682 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3683 "grantRuntimePermission"); 3684 3685 final int uid; 3686 final SettingBase sb; 3687 3688 synchronized (mPackages) { 3689 final PackageParser.Package pkg = mPackages.get(packageName); 3690 if (pkg == null) { 3691 throw new IllegalArgumentException("Unknown package: " + packageName); 3692 } 3693 3694 final BasePermission bp = mSettings.mPermissions.get(name); 3695 if (bp == null) { 3696 throw new IllegalArgumentException("Unknown permission: " + name); 3697 } 3698 3699 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3700 3701 // If a permission review is required for legacy apps we represent 3702 // their permissions as always granted runtime ones since we need 3703 // to keep the review required permission flag per user while an 3704 // install permission's state is shared across all users. 3705 if (Build.PERMISSIONS_REVIEW_REQUIRED 3706 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3707 && bp.isRuntime()) { 3708 return; 3709 } 3710 3711 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3712 sb = (SettingBase) pkg.mExtras; 3713 if (sb == null) { 3714 throw new IllegalArgumentException("Unknown package: " + packageName); 3715 } 3716 3717 final PermissionsState permissionsState = sb.getPermissionsState(); 3718 3719 final int flags = permissionsState.getPermissionFlags(name, userId); 3720 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3721 throw new SecurityException("Cannot grant system fixed permission: " 3722 + name + " for package: " + packageName); 3723 } 3724 3725 if (bp.isDevelopment()) { 3726 // Development permissions must be handled specially, since they are not 3727 // normal runtime permissions. For now they apply to all users. 3728 if (permissionsState.grantInstallPermission(bp) != 3729 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3730 scheduleWriteSettingsLocked(); 3731 } 3732 return; 3733 } 3734 3735 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3736 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3737 return; 3738 } 3739 3740 final int result = permissionsState.grantRuntimePermission(bp, userId); 3741 switch (result) { 3742 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3743 return; 3744 } 3745 3746 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3747 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3748 mHandler.post(new Runnable() { 3749 @Override 3750 public void run() { 3751 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3752 } 3753 }); 3754 } 3755 break; 3756 } 3757 3758 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3759 3760 // Not critical if that is lost - app has to request again. 3761 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3762 } 3763 3764 // Only need to do this if user is initialized. Otherwise it's a new user 3765 // and there are no processes running as the user yet and there's no need 3766 // to make an expensive call to remount processes for the changed permissions. 3767 if (READ_EXTERNAL_STORAGE.equals(name) 3768 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3769 final long token = Binder.clearCallingIdentity(); 3770 try { 3771 if (sUserManager.isInitialized(userId)) { 3772 MountServiceInternal mountServiceInternal = LocalServices.getService( 3773 MountServiceInternal.class); 3774 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3775 } 3776 } finally { 3777 Binder.restoreCallingIdentity(token); 3778 } 3779 } 3780 } 3781 3782 @Override 3783 public void revokeRuntimePermission(String packageName, String name, int userId) { 3784 if (!sUserManager.exists(userId)) { 3785 Log.e(TAG, "No such user:" + userId); 3786 return; 3787 } 3788 3789 mContext.enforceCallingOrSelfPermission( 3790 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3791 "revokeRuntimePermission"); 3792 3793 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3794 "revokeRuntimePermission"); 3795 3796 final int appId; 3797 3798 synchronized (mPackages) { 3799 final PackageParser.Package pkg = mPackages.get(packageName); 3800 if (pkg == null) { 3801 throw new IllegalArgumentException("Unknown package: " + packageName); 3802 } 3803 3804 final BasePermission bp = mSettings.mPermissions.get(name); 3805 if (bp == null) { 3806 throw new IllegalArgumentException("Unknown permission: " + name); 3807 } 3808 3809 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3810 3811 // If a permission review is required for legacy apps we represent 3812 // their permissions as always granted runtime ones since we need 3813 // to keep the review required permission flag per user while an 3814 // install permission's state is shared across all users. 3815 if (Build.PERMISSIONS_REVIEW_REQUIRED 3816 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3817 && bp.isRuntime()) { 3818 return; 3819 } 3820 3821 SettingBase sb = (SettingBase) pkg.mExtras; 3822 if (sb == null) { 3823 throw new IllegalArgumentException("Unknown package: " + packageName); 3824 } 3825 3826 final PermissionsState permissionsState = sb.getPermissionsState(); 3827 3828 final int flags = permissionsState.getPermissionFlags(name, userId); 3829 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3830 throw new SecurityException("Cannot revoke system fixed permission: " 3831 + name + " for package: " + packageName); 3832 } 3833 3834 if (bp.isDevelopment()) { 3835 // Development permissions must be handled specially, since they are not 3836 // normal runtime permissions. For now they apply to all users. 3837 if (permissionsState.revokeInstallPermission(bp) != 3838 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3839 scheduleWriteSettingsLocked(); 3840 } 3841 return; 3842 } 3843 3844 if (permissionsState.revokeRuntimePermission(bp, userId) == 3845 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3846 return; 3847 } 3848 3849 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3850 3851 // Critical, after this call app should never have the permission. 3852 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3853 3854 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3855 } 3856 3857 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3858 } 3859 3860 @Override 3861 public void resetRuntimePermissions() { 3862 mContext.enforceCallingOrSelfPermission( 3863 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3864 "revokeRuntimePermission"); 3865 3866 int callingUid = Binder.getCallingUid(); 3867 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3868 mContext.enforceCallingOrSelfPermission( 3869 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3870 "resetRuntimePermissions"); 3871 } 3872 3873 synchronized (mPackages) { 3874 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3875 for (int userId : UserManagerService.getInstance().getUserIds()) { 3876 final int packageCount = mPackages.size(); 3877 for (int i = 0; i < packageCount; i++) { 3878 PackageParser.Package pkg = mPackages.valueAt(i); 3879 if (!(pkg.mExtras instanceof PackageSetting)) { 3880 continue; 3881 } 3882 PackageSetting ps = (PackageSetting) pkg.mExtras; 3883 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3884 } 3885 } 3886 } 3887 } 3888 3889 @Override 3890 public int getPermissionFlags(String name, String packageName, int userId) { 3891 if (!sUserManager.exists(userId)) { 3892 return 0; 3893 } 3894 3895 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3896 3897 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3898 "getPermissionFlags"); 3899 3900 synchronized (mPackages) { 3901 final PackageParser.Package pkg = mPackages.get(packageName); 3902 if (pkg == null) { 3903 throw new IllegalArgumentException("Unknown package: " + packageName); 3904 } 3905 3906 final BasePermission bp = mSettings.mPermissions.get(name); 3907 if (bp == null) { 3908 throw new IllegalArgumentException("Unknown permission: " + name); 3909 } 3910 3911 SettingBase sb = (SettingBase) pkg.mExtras; 3912 if (sb == null) { 3913 throw new IllegalArgumentException("Unknown package: " + packageName); 3914 } 3915 3916 PermissionsState permissionsState = sb.getPermissionsState(); 3917 return permissionsState.getPermissionFlags(name, userId); 3918 } 3919 } 3920 3921 @Override 3922 public void updatePermissionFlags(String name, String packageName, int flagMask, 3923 int flagValues, int userId) { 3924 if (!sUserManager.exists(userId)) { 3925 return; 3926 } 3927 3928 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3929 3930 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3931 "updatePermissionFlags"); 3932 3933 // Only the system can change these flags and nothing else. 3934 if (getCallingUid() != Process.SYSTEM_UID) { 3935 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3936 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3937 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3938 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3939 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3940 } 3941 3942 synchronized (mPackages) { 3943 final PackageParser.Package pkg = mPackages.get(packageName); 3944 if (pkg == null) { 3945 throw new IllegalArgumentException("Unknown package: " + packageName); 3946 } 3947 3948 final BasePermission bp = mSettings.mPermissions.get(name); 3949 if (bp == null) { 3950 throw new IllegalArgumentException("Unknown permission: " + name); 3951 } 3952 3953 SettingBase sb = (SettingBase) pkg.mExtras; 3954 if (sb == null) { 3955 throw new IllegalArgumentException("Unknown package: " + packageName); 3956 } 3957 3958 PermissionsState permissionsState = sb.getPermissionsState(); 3959 3960 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3961 3962 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3963 // Install and runtime permissions are stored in different places, 3964 // so figure out what permission changed and persist the change. 3965 if (permissionsState.getInstallPermissionState(name) != null) { 3966 scheduleWriteSettingsLocked(); 3967 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3968 || hadState) { 3969 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3970 } 3971 } 3972 } 3973 } 3974 3975 /** 3976 * Update the permission flags for all packages and runtime permissions of a user in order 3977 * to allow device or profile owner to remove POLICY_FIXED. 3978 */ 3979 @Override 3980 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3981 if (!sUserManager.exists(userId)) { 3982 return; 3983 } 3984 3985 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3986 3987 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3988 "updatePermissionFlagsForAllApps"); 3989 3990 // Only the system can change system fixed flags. 3991 if (getCallingUid() != Process.SYSTEM_UID) { 3992 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3993 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3994 } 3995 3996 synchronized (mPackages) { 3997 boolean changed = false; 3998 final int packageCount = mPackages.size(); 3999 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4000 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4001 SettingBase sb = (SettingBase) pkg.mExtras; 4002 if (sb == null) { 4003 continue; 4004 } 4005 PermissionsState permissionsState = sb.getPermissionsState(); 4006 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4007 userId, flagMask, flagValues); 4008 } 4009 if (changed) { 4010 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4011 } 4012 } 4013 } 4014 4015 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4016 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4017 != PackageManager.PERMISSION_GRANTED 4018 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4019 != PackageManager.PERMISSION_GRANTED) { 4020 throw new SecurityException(message + " requires " 4021 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4022 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4023 } 4024 } 4025 4026 @Override 4027 public boolean shouldShowRequestPermissionRationale(String permissionName, 4028 String packageName, int userId) { 4029 if (UserHandle.getCallingUserId() != userId) { 4030 mContext.enforceCallingPermission( 4031 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4032 "canShowRequestPermissionRationale for user " + userId); 4033 } 4034 4035 final int uid = getPackageUid(packageName, userId); 4036 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4037 return false; 4038 } 4039 4040 if (checkPermission(permissionName, packageName, userId) 4041 == PackageManager.PERMISSION_GRANTED) { 4042 return false; 4043 } 4044 4045 final int flags; 4046 4047 final long identity = Binder.clearCallingIdentity(); 4048 try { 4049 flags = getPermissionFlags(permissionName, 4050 packageName, userId); 4051 } finally { 4052 Binder.restoreCallingIdentity(identity); 4053 } 4054 4055 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4056 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4057 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4058 4059 if ((flags & fixedFlags) != 0) { 4060 return false; 4061 } 4062 4063 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4064 } 4065 4066 @Override 4067 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4068 mContext.enforceCallingOrSelfPermission( 4069 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4070 "addOnPermissionsChangeListener"); 4071 4072 synchronized (mPackages) { 4073 mOnPermissionChangeListeners.addListenerLocked(listener); 4074 } 4075 } 4076 4077 @Override 4078 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4079 synchronized (mPackages) { 4080 mOnPermissionChangeListeners.removeListenerLocked(listener); 4081 } 4082 } 4083 4084 @Override 4085 public boolean isProtectedBroadcast(String actionName) { 4086 synchronized (mPackages) { 4087 if (mProtectedBroadcasts.contains(actionName)) { 4088 return true; 4089 } else if (actionName != null 4090 && actionName.startsWith("android.net.netmon.lingerExpired")) { 4091 // TODO: remove this terrible hack 4092 return true; 4093 } 4094 } 4095 return false; 4096 } 4097 4098 @Override 4099 public int checkSignatures(String pkg1, String pkg2) { 4100 synchronized (mPackages) { 4101 final PackageParser.Package p1 = mPackages.get(pkg1); 4102 final PackageParser.Package p2 = mPackages.get(pkg2); 4103 if (p1 == null || p1.mExtras == null 4104 || p2 == null || p2.mExtras == null) { 4105 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4106 } 4107 return compareSignatures(p1.mSignatures, p2.mSignatures); 4108 } 4109 } 4110 4111 @Override 4112 public int checkUidSignatures(int uid1, int uid2) { 4113 // Map to base uids. 4114 uid1 = UserHandle.getAppId(uid1); 4115 uid2 = UserHandle.getAppId(uid2); 4116 // reader 4117 synchronized (mPackages) { 4118 Signature[] s1; 4119 Signature[] s2; 4120 Object obj = mSettings.getUserIdLPr(uid1); 4121 if (obj != null) { 4122 if (obj instanceof SharedUserSetting) { 4123 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4124 } else if (obj instanceof PackageSetting) { 4125 s1 = ((PackageSetting)obj).signatures.mSignatures; 4126 } else { 4127 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4128 } 4129 } else { 4130 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4131 } 4132 obj = mSettings.getUserIdLPr(uid2); 4133 if (obj != null) { 4134 if (obj instanceof SharedUserSetting) { 4135 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4136 } else if (obj instanceof PackageSetting) { 4137 s2 = ((PackageSetting)obj).signatures.mSignatures; 4138 } else { 4139 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4140 } 4141 } else { 4142 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4143 } 4144 return compareSignatures(s1, s2); 4145 } 4146 } 4147 4148 private void killUid(int appId, int userId, String reason) { 4149 final long identity = Binder.clearCallingIdentity(); 4150 try { 4151 IActivityManager am = ActivityManagerNative.getDefault(); 4152 if (am != null) { 4153 try { 4154 am.killUid(appId, userId, reason); 4155 } catch (RemoteException e) { 4156 /* ignore - same process */ 4157 } 4158 } 4159 } finally { 4160 Binder.restoreCallingIdentity(identity); 4161 } 4162 } 4163 4164 /** 4165 * Compares two sets of signatures. Returns: 4166 * <br /> 4167 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4168 * <br /> 4169 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4170 * <br /> 4171 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4176 */ 4177 static int compareSignatures(Signature[] s1, Signature[] s2) { 4178 if (s1 == null) { 4179 return s2 == null 4180 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4181 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4182 } 4183 4184 if (s2 == null) { 4185 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4186 } 4187 4188 if (s1.length != s2.length) { 4189 return PackageManager.SIGNATURE_NO_MATCH; 4190 } 4191 4192 // Since both signature sets are of size 1, we can compare without HashSets. 4193 if (s1.length == 1) { 4194 return s1[0].equals(s2[0]) ? 4195 PackageManager.SIGNATURE_MATCH : 4196 PackageManager.SIGNATURE_NO_MATCH; 4197 } 4198 4199 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4200 for (Signature sig : s1) { 4201 set1.add(sig); 4202 } 4203 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4204 for (Signature sig : s2) { 4205 set2.add(sig); 4206 } 4207 // Make sure s2 contains all signatures in s1. 4208 if (set1.equals(set2)) { 4209 return PackageManager.SIGNATURE_MATCH; 4210 } 4211 return PackageManager.SIGNATURE_NO_MATCH; 4212 } 4213 4214 /** 4215 * If the database version for this type of package (internal storage or 4216 * external storage) is less than the version where package signatures 4217 * were updated, return true. 4218 */ 4219 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4220 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4221 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4222 } 4223 4224 /** 4225 * Used for backward compatibility to make sure any packages with 4226 * certificate chains get upgraded to the new style. {@code existingSigs} 4227 * will be in the old format (since they were stored on disk from before the 4228 * system upgrade) and {@code scannedSigs} will be in the newer format. 4229 */ 4230 private int compareSignaturesCompat(PackageSignatures existingSigs, 4231 PackageParser.Package scannedPkg) { 4232 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4233 return PackageManager.SIGNATURE_NO_MATCH; 4234 } 4235 4236 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4237 for (Signature sig : existingSigs.mSignatures) { 4238 existingSet.add(sig); 4239 } 4240 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4241 for (Signature sig : scannedPkg.mSignatures) { 4242 try { 4243 Signature[] chainSignatures = sig.getChainSignatures(); 4244 for (Signature chainSig : chainSignatures) { 4245 scannedCompatSet.add(chainSig); 4246 } 4247 } catch (CertificateEncodingException e) { 4248 scannedCompatSet.add(sig); 4249 } 4250 } 4251 /* 4252 * Make sure the expanded scanned set contains all signatures in the 4253 * existing one. 4254 */ 4255 if (scannedCompatSet.equals(existingSet)) { 4256 // Migrate the old signatures to the new scheme. 4257 existingSigs.assignSignatures(scannedPkg.mSignatures); 4258 // The new KeySets will be re-added later in the scanning process. 4259 synchronized (mPackages) { 4260 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4261 } 4262 return PackageManager.SIGNATURE_MATCH; 4263 } 4264 return PackageManager.SIGNATURE_NO_MATCH; 4265 } 4266 4267 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4268 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4269 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4270 } 4271 4272 private int compareSignaturesRecover(PackageSignatures existingSigs, 4273 PackageParser.Package scannedPkg) { 4274 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4275 return PackageManager.SIGNATURE_NO_MATCH; 4276 } 4277 4278 String msg = null; 4279 try { 4280 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4281 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4282 + scannedPkg.packageName); 4283 return PackageManager.SIGNATURE_MATCH; 4284 } 4285 } catch (CertificateException e) { 4286 msg = e.getMessage(); 4287 } 4288 4289 logCriticalInfo(Log.INFO, 4290 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 @Override 4295 public String[] getPackagesForUid(int uid) { 4296 uid = UserHandle.getAppId(uid); 4297 // reader 4298 synchronized (mPackages) { 4299 Object obj = mSettings.getUserIdLPr(uid); 4300 if (obj instanceof SharedUserSetting) { 4301 final SharedUserSetting sus = (SharedUserSetting) obj; 4302 final int N = sus.packages.size(); 4303 final String[] res = new String[N]; 4304 final Iterator<PackageSetting> it = sus.packages.iterator(); 4305 int i = 0; 4306 while (it.hasNext()) { 4307 res[i++] = it.next().name; 4308 } 4309 return res; 4310 } else if (obj instanceof PackageSetting) { 4311 final PackageSetting ps = (PackageSetting) obj; 4312 return new String[] { ps.name }; 4313 } 4314 } 4315 return null; 4316 } 4317 4318 @Override 4319 public String getNameForUid(int uid) { 4320 // reader 4321 synchronized (mPackages) { 4322 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4323 if (obj instanceof SharedUserSetting) { 4324 final SharedUserSetting sus = (SharedUserSetting) obj; 4325 return sus.name + ":" + sus.userId; 4326 } else if (obj instanceof PackageSetting) { 4327 final PackageSetting ps = (PackageSetting) obj; 4328 return ps.name; 4329 } 4330 } 4331 return null; 4332 } 4333 4334 @Override 4335 public int getUidForSharedUser(String sharedUserName) { 4336 if(sharedUserName == null) { 4337 return -1; 4338 } 4339 // reader 4340 synchronized (mPackages) { 4341 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4342 if (suid == null) { 4343 return -1; 4344 } 4345 return suid.userId; 4346 } 4347 } 4348 4349 @Override 4350 public int getFlagsForUid(int uid) { 4351 synchronized (mPackages) { 4352 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4353 if (obj instanceof SharedUserSetting) { 4354 final SharedUserSetting sus = (SharedUserSetting) obj; 4355 return sus.pkgFlags; 4356 } else if (obj instanceof PackageSetting) { 4357 final PackageSetting ps = (PackageSetting) obj; 4358 return ps.pkgFlags; 4359 } 4360 } 4361 return 0; 4362 } 4363 4364 @Override 4365 public int getPrivateFlagsForUid(int uid) { 4366 synchronized (mPackages) { 4367 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4368 if (obj instanceof SharedUserSetting) { 4369 final SharedUserSetting sus = (SharedUserSetting) obj; 4370 return sus.pkgPrivateFlags; 4371 } else if (obj instanceof PackageSetting) { 4372 final PackageSetting ps = (PackageSetting) obj; 4373 return ps.pkgPrivateFlags; 4374 } 4375 } 4376 return 0; 4377 } 4378 4379 @Override 4380 public boolean isUidPrivileged(int uid) { 4381 uid = UserHandle.getAppId(uid); 4382 // reader 4383 synchronized (mPackages) { 4384 Object obj = mSettings.getUserIdLPr(uid); 4385 if (obj instanceof SharedUserSetting) { 4386 final SharedUserSetting sus = (SharedUserSetting) obj; 4387 final Iterator<PackageSetting> it = sus.packages.iterator(); 4388 while (it.hasNext()) { 4389 if (it.next().isPrivileged()) { 4390 return true; 4391 } 4392 } 4393 } else if (obj instanceof PackageSetting) { 4394 final PackageSetting ps = (PackageSetting) obj; 4395 return ps.isPrivileged(); 4396 } 4397 } 4398 return false; 4399 } 4400 4401 @Override 4402 public String[] getAppOpPermissionPackages(String permissionName) { 4403 synchronized (mPackages) { 4404 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4405 if (pkgs == null) { 4406 return null; 4407 } 4408 return pkgs.toArray(new String[pkgs.size()]); 4409 } 4410 } 4411 4412 @Override 4413 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4414 int flags, int userId) { 4415 if (!sUserManager.exists(userId)) return null; 4416 flags = augmentFlagsForUser(flags, userId); 4417 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4418 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4419 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4420 } 4421 4422 @Override 4423 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4424 IntentFilter filter, int match, ComponentName activity) { 4425 final int userId = UserHandle.getCallingUserId(); 4426 if (DEBUG_PREFERRED) { 4427 Log.v(TAG, "setLastChosenActivity intent=" + intent 4428 + " resolvedType=" + resolvedType 4429 + " flags=" + flags 4430 + " filter=" + filter 4431 + " match=" + match 4432 + " activity=" + activity); 4433 filter.dump(new PrintStreamPrinter(System.out), " "); 4434 } 4435 intent.setComponent(null); 4436 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4437 // Find any earlier preferred or last chosen entries and nuke them 4438 findPreferredActivity(intent, resolvedType, 4439 flags, query, 0, false, true, false, userId); 4440 // Add the new activity as the last chosen for this filter 4441 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4442 "Setting last chosen"); 4443 } 4444 4445 @Override 4446 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4447 final int userId = UserHandle.getCallingUserId(); 4448 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4449 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4450 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4451 false, false, false, userId); 4452 } 4453 4454 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4455 MessageDigest digest = null; 4456 try { 4457 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4458 } catch (NoSuchAlgorithmException e) { 4459 // If we can't create a digest, ignore ephemeral apps. 4460 return false; 4461 } 4462 4463 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4464 final byte[] digestBytes = digest.digest(hostBytes); 4465 int shaPrefix = 4466 digestBytes[0] << 24 4467 | digestBytes[1] << 16 4468 | digestBytes[2] << 8 4469 | digestBytes[3] << 0; 4470 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4471 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4472 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4473 // No hash prefix match; there are no ephemeral apps for this domain. 4474 return false; 4475 } 4476 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4477 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4478 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4479 continue; 4480 } 4481 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4482 // No filters; this should never happen. 4483 if (filters.isEmpty()) { 4484 continue; 4485 } 4486 // We have a domain match; resolve the filters to see if anything matches. 4487 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4488 for (int j = filters.size() - 1; j >= 0; --j) { 4489 ephemeralResolver.addFilter(filters.get(j)); 4490 } 4491 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4492 intent, resolvedType, false /*defaultOnly*/, userId); 4493 return !ephemeralResolveList.isEmpty(); 4494 } 4495 // Hash or filter mis-match; no ephemeral apps for this domain. 4496 return false; 4497 } 4498 4499 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4500 int flags, List<ResolveInfo> query, int userId) { 4501 final boolean isWebUri = hasWebURI(intent); 4502 // Check whether or not an ephemeral app exists to handle the URI. 4503 if (isWebUri && mEphemeralResolverConnection != null) { 4504 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4505 boolean hasAlwaysHandler = false; 4506 synchronized (mPackages) { 4507 final int count = query.size(); 4508 for (int n=0; n<count; n++) { 4509 ResolveInfo info = query.get(n); 4510 String packageName = info.activityInfo.packageName; 4511 PackageSetting ps = mSettings.mPackages.get(packageName); 4512 if (ps != null) { 4513 // Try to get the status from User settings first 4514 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4515 int status = (int) (packedStatus >> 32); 4516 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4517 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4518 hasAlwaysHandler = true; 4519 break; 4520 } 4521 } 4522 } 4523 } 4524 4525 // Only consider installing an ephemeral app if there isn't already a verified handler. 4526 // We've determined that there's an ephemeral app available for the URI, ignore any 4527 // ResolveInfo's and just return the ephemeral installer 4528 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4529 if (DEBUG_EPHEMERAL) { 4530 Slog.v(TAG, "Resolving to the ephemeral installer"); 4531 } 4532 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4533 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4534 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4535 // make a deep copy of the applicationInfo 4536 ri.activityInfo.applicationInfo = new ApplicationInfo( 4537 ri.activityInfo.applicationInfo); 4538 if (userId != 0) { 4539 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4540 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4541 } 4542 return ri; 4543 } 4544 } 4545 if (query != null) { 4546 final int N = query.size(); 4547 if (N == 1) { 4548 return query.get(0); 4549 } else if (N > 1) { 4550 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4551 // If there is more than one activity with the same priority, 4552 // then let the user decide between them. 4553 ResolveInfo r0 = query.get(0); 4554 ResolveInfo r1 = query.get(1); 4555 if (DEBUG_INTENT_MATCHING || debug) { 4556 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4557 + r1.activityInfo.name + "=" + r1.priority); 4558 } 4559 // If the first activity has a higher priority, or a different 4560 // default, then it is always desireable to pick it. 4561 if (r0.priority != r1.priority 4562 || r0.preferredOrder != r1.preferredOrder 4563 || r0.isDefault != r1.isDefault) { 4564 return query.get(0); 4565 } 4566 // If we have saved a preference for a preferred activity for 4567 // this Intent, use that. 4568 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4569 flags, query, r0.priority, true, false, debug, userId); 4570 if (ri != null) { 4571 return ri; 4572 } 4573 ri = new ResolveInfo(mResolveInfo); 4574 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4575 ri.activityInfo.applicationInfo = new ApplicationInfo( 4576 ri.activityInfo.applicationInfo); 4577 if (userId != 0) { 4578 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4579 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4580 } 4581 // Make sure that the resolver is displayable in car mode 4582 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4583 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4584 return ri; 4585 } 4586 } 4587 return null; 4588 } 4589 4590 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4591 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4592 final int N = query.size(); 4593 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4594 .get(userId); 4595 // Get the list of persistent preferred activities that handle the intent 4596 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4597 List<PersistentPreferredActivity> pprefs = ppir != null 4598 ? ppir.queryIntent(intent, resolvedType, 4599 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4600 : null; 4601 if (pprefs != null && pprefs.size() > 0) { 4602 final int M = pprefs.size(); 4603 for (int i=0; i<M; i++) { 4604 final PersistentPreferredActivity ppa = pprefs.get(i); 4605 if (DEBUG_PREFERRED || debug) { 4606 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4607 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4608 + "\n component=" + ppa.mComponent); 4609 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4610 } 4611 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4612 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4613 if (DEBUG_PREFERRED || debug) { 4614 Slog.v(TAG, "Found persistent preferred activity:"); 4615 if (ai != null) { 4616 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4617 } else { 4618 Slog.v(TAG, " null"); 4619 } 4620 } 4621 if (ai == null) { 4622 // This previously registered persistent preferred activity 4623 // component is no longer known. Ignore it and do NOT remove it. 4624 continue; 4625 } 4626 for (int j=0; j<N; j++) { 4627 final ResolveInfo ri = query.get(j); 4628 if (!ri.activityInfo.applicationInfo.packageName 4629 .equals(ai.applicationInfo.packageName)) { 4630 continue; 4631 } 4632 if (!ri.activityInfo.name.equals(ai.name)) { 4633 continue; 4634 } 4635 // Found a persistent preference that can handle the intent. 4636 if (DEBUG_PREFERRED || debug) { 4637 Slog.v(TAG, "Returning persistent preferred activity: " + 4638 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4639 } 4640 return ri; 4641 } 4642 } 4643 } 4644 return null; 4645 } 4646 4647 // TODO: handle preferred activities missing while user has amnesia 4648 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4649 List<ResolveInfo> query, int priority, boolean always, 4650 boolean removeMatches, boolean debug, int userId) { 4651 if (!sUserManager.exists(userId)) return null; 4652 flags = augmentFlagsForUser(flags, userId); 4653 // writer 4654 synchronized (mPackages) { 4655 if (intent.getSelector() != null) { 4656 intent = intent.getSelector(); 4657 } 4658 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4659 4660 // Try to find a matching persistent preferred activity. 4661 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4662 debug, userId); 4663 4664 // If a persistent preferred activity matched, use it. 4665 if (pri != null) { 4666 return pri; 4667 } 4668 4669 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4670 // Get the list of preferred activities that handle the intent 4671 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4672 List<PreferredActivity> prefs = pir != null 4673 ? pir.queryIntent(intent, resolvedType, 4674 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4675 : null; 4676 if (prefs != null && prefs.size() > 0) { 4677 boolean changed = false; 4678 try { 4679 // First figure out how good the original match set is. 4680 // We will only allow preferred activities that came 4681 // from the same match quality. 4682 int match = 0; 4683 4684 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4685 4686 final int N = query.size(); 4687 for (int j=0; j<N; j++) { 4688 final ResolveInfo ri = query.get(j); 4689 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4690 + ": 0x" + Integer.toHexString(match)); 4691 if (ri.match > match) { 4692 match = ri.match; 4693 } 4694 } 4695 4696 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4697 + Integer.toHexString(match)); 4698 4699 match &= IntentFilter.MATCH_CATEGORY_MASK; 4700 final int M = prefs.size(); 4701 for (int i=0; i<M; i++) { 4702 final PreferredActivity pa = prefs.get(i); 4703 if (DEBUG_PREFERRED || debug) { 4704 Slog.v(TAG, "Checking PreferredActivity ds=" 4705 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4706 + "\n component=" + pa.mPref.mComponent); 4707 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4708 } 4709 if (pa.mPref.mMatch != match) { 4710 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4711 + Integer.toHexString(pa.mPref.mMatch)); 4712 continue; 4713 } 4714 // If it's not an "always" type preferred activity and that's what we're 4715 // looking for, skip it. 4716 if (always && !pa.mPref.mAlways) { 4717 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4718 continue; 4719 } 4720 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4721 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4722 if (DEBUG_PREFERRED || debug) { 4723 Slog.v(TAG, "Found preferred activity:"); 4724 if (ai != null) { 4725 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4726 } else { 4727 Slog.v(TAG, " null"); 4728 } 4729 } 4730 if (ai == null) { 4731 // This previously registered preferred activity 4732 // component is no longer known. Most likely an update 4733 // to the app was installed and in the new version this 4734 // component no longer exists. Clean it up by removing 4735 // it from the preferred activities list, and skip it. 4736 Slog.w(TAG, "Removing dangling preferred activity: " 4737 + pa.mPref.mComponent); 4738 pir.removeFilter(pa); 4739 changed = true; 4740 continue; 4741 } 4742 for (int j=0; j<N; j++) { 4743 final ResolveInfo ri = query.get(j); 4744 if (!ri.activityInfo.applicationInfo.packageName 4745 .equals(ai.applicationInfo.packageName)) { 4746 continue; 4747 } 4748 if (!ri.activityInfo.name.equals(ai.name)) { 4749 continue; 4750 } 4751 4752 if (removeMatches) { 4753 pir.removeFilter(pa); 4754 changed = true; 4755 if (DEBUG_PREFERRED) { 4756 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4757 } 4758 break; 4759 } 4760 4761 // Okay we found a previously set preferred or last chosen app. 4762 // If the result set is different from when this 4763 // was created, we need to clear it and re-ask the 4764 // user their preference, if we're looking for an "always" type entry. 4765 if (always && !pa.mPref.sameSet(query)) { 4766 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4767 + intent + " type " + resolvedType); 4768 if (DEBUG_PREFERRED) { 4769 Slog.v(TAG, "Removing preferred activity since set changed " 4770 + pa.mPref.mComponent); 4771 } 4772 pir.removeFilter(pa); 4773 // Re-add the filter as a "last chosen" entry (!always) 4774 PreferredActivity lastChosen = new PreferredActivity( 4775 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4776 pir.addFilter(lastChosen); 4777 changed = true; 4778 return null; 4779 } 4780 4781 // Yay! Either the set matched or we're looking for the last chosen 4782 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4783 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4784 return ri; 4785 } 4786 } 4787 } finally { 4788 if (changed) { 4789 if (DEBUG_PREFERRED) { 4790 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4791 } 4792 scheduleWritePackageRestrictionsLocked(userId); 4793 } 4794 } 4795 } 4796 } 4797 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4798 return null; 4799 } 4800 4801 /* 4802 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4803 */ 4804 @Override 4805 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4806 int targetUserId) { 4807 mContext.enforceCallingOrSelfPermission( 4808 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4809 List<CrossProfileIntentFilter> matches = 4810 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4811 if (matches != null) { 4812 int size = matches.size(); 4813 for (int i = 0; i < size; i++) { 4814 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4815 } 4816 } 4817 if (hasWebURI(intent)) { 4818 // cross-profile app linking works only towards the parent. 4819 final UserInfo parent = getProfileParent(sourceUserId); 4820 synchronized(mPackages) { 4821 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4822 intent, resolvedType, 0, sourceUserId, parent.id); 4823 return xpDomainInfo != null; 4824 } 4825 } 4826 return false; 4827 } 4828 4829 private UserInfo getProfileParent(int userId) { 4830 final long identity = Binder.clearCallingIdentity(); 4831 try { 4832 return sUserManager.getProfileParent(userId); 4833 } finally { 4834 Binder.restoreCallingIdentity(identity); 4835 } 4836 } 4837 4838 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4839 String resolvedType, int userId) { 4840 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4841 if (resolver != null) { 4842 return resolver.queryIntent(intent, resolvedType, false, userId); 4843 } 4844 return null; 4845 } 4846 4847 @Override 4848 public List<ResolveInfo> queryIntentActivities(Intent intent, 4849 String resolvedType, int flags, int userId) { 4850 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4851 flags = augmentFlagsForUser(flags, userId); 4852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4853 ComponentName comp = intent.getComponent(); 4854 if (comp == null) { 4855 if (intent.getSelector() != null) { 4856 intent = intent.getSelector(); 4857 comp = intent.getComponent(); 4858 } 4859 } 4860 4861 if (comp != null) { 4862 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4863 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4864 if (ai != null) { 4865 final ResolveInfo ri = new ResolveInfo(); 4866 ri.activityInfo = ai; 4867 list.add(ri); 4868 } 4869 return list; 4870 } 4871 4872 // reader 4873 synchronized (mPackages) { 4874 final String pkgName = intent.getPackage(); 4875 if (pkgName == null) { 4876 List<CrossProfileIntentFilter> matchingFilters = 4877 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4878 // Check for results that need to skip the current profile. 4879 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4880 resolvedType, flags, userId); 4881 if (xpResolveInfo != null) { 4882 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4883 result.add(xpResolveInfo); 4884 return filterIfNotSystemUser(result, userId); 4885 } 4886 4887 // Check for results in the current profile. 4888 List<ResolveInfo> result = mActivities.queryIntent( 4889 intent, resolvedType, flags, userId); 4890 result = filterIfNotSystemUser(result, userId); 4891 4892 // Check for cross profile results. 4893 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4894 xpResolveInfo = queryCrossProfileIntents( 4895 matchingFilters, intent, resolvedType, flags, userId, 4896 hasNonNegativePriorityResult); 4897 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4898 boolean isVisibleToUser = filterIfNotSystemUser( 4899 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4900 if (isVisibleToUser) { 4901 result.add(xpResolveInfo); 4902 Collections.sort(result, mResolvePrioritySorter); 4903 } 4904 } 4905 if (hasWebURI(intent)) { 4906 CrossProfileDomainInfo xpDomainInfo = null; 4907 final UserInfo parent = getProfileParent(userId); 4908 if (parent != null) { 4909 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4910 flags, userId, parent.id); 4911 } 4912 if (xpDomainInfo != null) { 4913 if (xpResolveInfo != null) { 4914 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4915 // in the result. 4916 result.remove(xpResolveInfo); 4917 } 4918 if (result.size() == 0) { 4919 result.add(xpDomainInfo.resolveInfo); 4920 return result; 4921 } 4922 } else if (result.size() <= 1) { 4923 return result; 4924 } 4925 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4926 xpDomainInfo, userId); 4927 Collections.sort(result, mResolvePrioritySorter); 4928 } 4929 return result; 4930 } 4931 final PackageParser.Package pkg = mPackages.get(pkgName); 4932 if (pkg != null) { 4933 return filterIfNotSystemUser( 4934 mActivities.queryIntentForPackage( 4935 intent, resolvedType, flags, pkg.activities, userId), 4936 userId); 4937 } 4938 return new ArrayList<ResolveInfo>(); 4939 } 4940 } 4941 4942 private static class CrossProfileDomainInfo { 4943 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4944 ResolveInfo resolveInfo; 4945 /* Best domain verification status of the activities found in the other profile */ 4946 int bestDomainVerificationStatus; 4947 } 4948 4949 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4950 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4951 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4952 sourceUserId)) { 4953 return null; 4954 } 4955 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4956 resolvedType, flags, parentUserId); 4957 4958 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4959 return null; 4960 } 4961 CrossProfileDomainInfo result = null; 4962 int size = resultTargetUser.size(); 4963 for (int i = 0; i < size; i++) { 4964 ResolveInfo riTargetUser = resultTargetUser.get(i); 4965 // Intent filter verification is only for filters that specify a host. So don't return 4966 // those that handle all web uris. 4967 if (riTargetUser.handleAllWebDataURI) { 4968 continue; 4969 } 4970 String packageName = riTargetUser.activityInfo.packageName; 4971 PackageSetting ps = mSettings.mPackages.get(packageName); 4972 if (ps == null) { 4973 continue; 4974 } 4975 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4976 int status = (int)(verificationState >> 32); 4977 if (result == null) { 4978 result = new CrossProfileDomainInfo(); 4979 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4980 sourceUserId, parentUserId); 4981 result.bestDomainVerificationStatus = status; 4982 } else { 4983 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4984 result.bestDomainVerificationStatus); 4985 } 4986 } 4987 // Don't consider matches with status NEVER across profiles. 4988 if (result != null && result.bestDomainVerificationStatus 4989 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4990 return null; 4991 } 4992 return result; 4993 } 4994 4995 /** 4996 * Verification statuses are ordered from the worse to the best, except for 4997 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4998 */ 4999 private int bestDomainVerificationStatus(int status1, int status2) { 5000 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5001 return status2; 5002 } 5003 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5004 return status1; 5005 } 5006 return (int) MathUtils.max(status1, status2); 5007 } 5008 5009 private boolean isUserEnabled(int userId) { 5010 long callingId = Binder.clearCallingIdentity(); 5011 try { 5012 UserInfo userInfo = sUserManager.getUserInfo(userId); 5013 return userInfo != null && userInfo.isEnabled(); 5014 } finally { 5015 Binder.restoreCallingIdentity(callingId); 5016 } 5017 } 5018 5019 /** 5020 * Filter out activities with systemUserOnly flag set, when current user is not System. 5021 * 5022 * @return filtered list 5023 */ 5024 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5025 if (userId == UserHandle.USER_SYSTEM) { 5026 return resolveInfos; 5027 } 5028 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5029 ResolveInfo info = resolveInfos.get(i); 5030 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5031 resolveInfos.remove(i); 5032 } 5033 } 5034 return resolveInfos; 5035 } 5036 5037 /** 5038 * @param resolveInfos list of resolve infos in descending priority order 5039 * @return if the list contains a resolve info with non-negative priority 5040 */ 5041 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5042 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5043 } 5044 5045 private static boolean hasWebURI(Intent intent) { 5046 if (intent.getData() == null) { 5047 return false; 5048 } 5049 final String scheme = intent.getScheme(); 5050 if (TextUtils.isEmpty(scheme)) { 5051 return false; 5052 } 5053 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5054 } 5055 5056 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5057 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5058 int userId) { 5059 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5060 5061 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5062 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5063 candidates.size()); 5064 } 5065 5066 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5067 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5068 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5069 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5070 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5071 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5072 5073 synchronized (mPackages) { 5074 final int count = candidates.size(); 5075 // First, try to use linked apps. Partition the candidates into four lists: 5076 // one for the final results, one for the "do not use ever", one for "undefined status" 5077 // and finally one for "browser app type". 5078 for (int n=0; n<count; n++) { 5079 ResolveInfo info = candidates.get(n); 5080 String packageName = info.activityInfo.packageName; 5081 PackageSetting ps = mSettings.mPackages.get(packageName); 5082 if (ps != null) { 5083 // Add to the special match all list (Browser use case) 5084 if (info.handleAllWebDataURI) { 5085 matchAllList.add(info); 5086 continue; 5087 } 5088 // Try to get the status from User settings first 5089 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5090 int status = (int)(packedStatus >> 32); 5091 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5092 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5093 if (DEBUG_DOMAIN_VERIFICATION) { 5094 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5095 + " : linkgen=" + linkGeneration); 5096 } 5097 // Use link-enabled generation as preferredOrder, i.e. 5098 // prefer newly-enabled over earlier-enabled. 5099 info.preferredOrder = linkGeneration; 5100 alwaysList.add(info); 5101 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5102 if (DEBUG_DOMAIN_VERIFICATION) { 5103 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5104 } 5105 neverList.add(info); 5106 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5107 if (DEBUG_DOMAIN_VERIFICATION) { 5108 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5109 } 5110 alwaysAskList.add(info); 5111 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5112 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5113 if (DEBUG_DOMAIN_VERIFICATION) { 5114 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5115 } 5116 undefinedList.add(info); 5117 } 5118 } 5119 } 5120 5121 // We'll want to include browser possibilities in a few cases 5122 boolean includeBrowser = false; 5123 5124 // First try to add the "always" resolution(s) for the current user, if any 5125 if (alwaysList.size() > 0) { 5126 result.addAll(alwaysList); 5127 } else { 5128 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5129 result.addAll(undefinedList); 5130 // Maybe add one for the other profile. 5131 if (xpDomainInfo != null && ( 5132 xpDomainInfo.bestDomainVerificationStatus 5133 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5134 result.add(xpDomainInfo.resolveInfo); 5135 } 5136 includeBrowser = true; 5137 } 5138 5139 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5140 // If there were 'always' entries their preferred order has been set, so we also 5141 // back that off to make the alternatives equivalent 5142 if (alwaysAskList.size() > 0) { 5143 for (ResolveInfo i : result) { 5144 i.preferredOrder = 0; 5145 } 5146 result.addAll(alwaysAskList); 5147 includeBrowser = true; 5148 } 5149 5150 if (includeBrowser) { 5151 // Also add browsers (all of them or only the default one) 5152 if (DEBUG_DOMAIN_VERIFICATION) { 5153 Slog.v(TAG, " ...including browsers in candidate set"); 5154 } 5155 if ((matchFlags & MATCH_ALL) != 0) { 5156 result.addAll(matchAllList); 5157 } else { 5158 // Browser/generic handling case. If there's a default browser, go straight 5159 // to that (but only if there is no other higher-priority match). 5160 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5161 int maxMatchPrio = 0; 5162 ResolveInfo defaultBrowserMatch = null; 5163 final int numCandidates = matchAllList.size(); 5164 for (int n = 0; n < numCandidates; n++) { 5165 ResolveInfo info = matchAllList.get(n); 5166 // track the highest overall match priority... 5167 if (info.priority > maxMatchPrio) { 5168 maxMatchPrio = info.priority; 5169 } 5170 // ...and the highest-priority default browser match 5171 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5172 if (defaultBrowserMatch == null 5173 || (defaultBrowserMatch.priority < info.priority)) { 5174 if (debug) { 5175 Slog.v(TAG, "Considering default browser match " + info); 5176 } 5177 defaultBrowserMatch = info; 5178 } 5179 } 5180 } 5181 if (defaultBrowserMatch != null 5182 && defaultBrowserMatch.priority >= maxMatchPrio 5183 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5184 { 5185 if (debug) { 5186 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5187 } 5188 result.add(defaultBrowserMatch); 5189 } else { 5190 result.addAll(matchAllList); 5191 } 5192 } 5193 5194 // If there is nothing selected, add all candidates and remove the ones that the user 5195 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5196 if (result.size() == 0) { 5197 result.addAll(candidates); 5198 result.removeAll(neverList); 5199 } 5200 } 5201 } 5202 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5203 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5204 result.size()); 5205 for (ResolveInfo info : result) { 5206 Slog.v(TAG, " + " + info.activityInfo); 5207 } 5208 } 5209 return result; 5210 } 5211 5212 // Returns a packed value as a long: 5213 // 5214 // high 'int'-sized word: link status: undefined/ask/never/always. 5215 // low 'int'-sized word: relative priority among 'always' results. 5216 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5217 long result = ps.getDomainVerificationStatusForUser(userId); 5218 // if none available, get the master status 5219 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5220 if (ps.getIntentFilterVerificationInfo() != null) { 5221 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5222 } 5223 } 5224 return result; 5225 } 5226 5227 private ResolveInfo querySkipCurrentProfileIntents( 5228 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5229 int flags, int sourceUserId) { 5230 if (matchingFilters != null) { 5231 int size = matchingFilters.size(); 5232 for (int i = 0; i < size; i ++) { 5233 CrossProfileIntentFilter filter = matchingFilters.get(i); 5234 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5235 // Checking if there are activities in the target user that can handle the 5236 // intent. 5237 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5238 resolvedType, flags, sourceUserId); 5239 if (resolveInfo != null) { 5240 return resolveInfo; 5241 } 5242 } 5243 } 5244 } 5245 return null; 5246 } 5247 5248 // Return matching ResolveInfo in target user if any. 5249 private ResolveInfo queryCrossProfileIntents( 5250 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5251 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5252 if (matchingFilters != null) { 5253 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5254 // match the same intent. For performance reasons, it is better not to 5255 // run queryIntent twice for the same userId 5256 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5257 int size = matchingFilters.size(); 5258 for (int i = 0; i < size; i++) { 5259 CrossProfileIntentFilter filter = matchingFilters.get(i); 5260 int targetUserId = filter.getTargetUserId(); 5261 boolean skipCurrentProfile = 5262 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5263 boolean skipCurrentProfileIfNoMatchFound = 5264 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5265 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5266 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5267 // Checking if there are activities in the target user that can handle the 5268 // intent. 5269 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5270 resolvedType, flags, sourceUserId); 5271 if (resolveInfo != null) return resolveInfo; 5272 alreadyTriedUserIds.put(targetUserId, true); 5273 } 5274 } 5275 } 5276 return null; 5277 } 5278 5279 /** 5280 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5281 * will forward the intent to the filter's target user. 5282 * Otherwise, returns null. 5283 */ 5284 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5285 String resolvedType, int flags, int sourceUserId) { 5286 int targetUserId = filter.getTargetUserId(); 5287 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5288 resolvedType, flags, targetUserId); 5289 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5290 && isUserEnabled(targetUserId)) { 5291 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5292 } 5293 return null; 5294 } 5295 5296 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5297 int sourceUserId, int targetUserId) { 5298 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5299 long ident = Binder.clearCallingIdentity(); 5300 boolean targetIsProfile; 5301 try { 5302 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5303 } finally { 5304 Binder.restoreCallingIdentity(ident); 5305 } 5306 String className; 5307 if (targetIsProfile) { 5308 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5309 } else { 5310 className = FORWARD_INTENT_TO_PARENT; 5311 } 5312 ComponentName forwardingActivityComponentName = new ComponentName( 5313 mAndroidApplication.packageName, className); 5314 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5315 sourceUserId); 5316 if (!targetIsProfile) { 5317 forwardingActivityInfo.showUserIcon = targetUserId; 5318 forwardingResolveInfo.noResourceId = true; 5319 } 5320 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5321 forwardingResolveInfo.priority = 0; 5322 forwardingResolveInfo.preferredOrder = 0; 5323 forwardingResolveInfo.match = 0; 5324 forwardingResolveInfo.isDefault = true; 5325 forwardingResolveInfo.filter = filter; 5326 forwardingResolveInfo.targetUserId = targetUserId; 5327 return forwardingResolveInfo; 5328 } 5329 5330 @Override 5331 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5332 Intent[] specifics, String[] specificTypes, Intent intent, 5333 String resolvedType, int flags, int userId) { 5334 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5335 flags = augmentFlagsForUser(flags, userId); 5336 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5337 false, "query intent activity options"); 5338 final String resultsAction = intent.getAction(); 5339 5340 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5341 | PackageManager.GET_RESOLVED_FILTER, userId); 5342 5343 if (DEBUG_INTENT_MATCHING) { 5344 Log.v(TAG, "Query " + intent + ": " + results); 5345 } 5346 5347 int specificsPos = 0; 5348 int N; 5349 5350 // todo: note that the algorithm used here is O(N^2). This 5351 // isn't a problem in our current environment, but if we start running 5352 // into situations where we have more than 5 or 10 matches then this 5353 // should probably be changed to something smarter... 5354 5355 // First we go through and resolve each of the specific items 5356 // that were supplied, taking care of removing any corresponding 5357 // duplicate items in the generic resolve list. 5358 if (specifics != null) { 5359 for (int i=0; i<specifics.length; i++) { 5360 final Intent sintent = specifics[i]; 5361 if (sintent == null) { 5362 continue; 5363 } 5364 5365 if (DEBUG_INTENT_MATCHING) { 5366 Log.v(TAG, "Specific #" + i + ": " + sintent); 5367 } 5368 5369 String action = sintent.getAction(); 5370 if (resultsAction != null && resultsAction.equals(action)) { 5371 // If this action was explicitly requested, then don't 5372 // remove things that have it. 5373 action = null; 5374 } 5375 5376 ResolveInfo ri = null; 5377 ActivityInfo ai = null; 5378 5379 ComponentName comp = sintent.getComponent(); 5380 if (comp == null) { 5381 ri = resolveIntent( 5382 sintent, 5383 specificTypes != null ? specificTypes[i] : null, 5384 flags, userId); 5385 if (ri == null) { 5386 continue; 5387 } 5388 if (ri == mResolveInfo) { 5389 // ACK! Must do something better with this. 5390 } 5391 ai = ri.activityInfo; 5392 comp = new ComponentName(ai.applicationInfo.packageName, 5393 ai.name); 5394 } else { 5395 ai = getActivityInfo(comp, flags, userId); 5396 if (ai == null) { 5397 continue; 5398 } 5399 } 5400 5401 // Look for any generic query activities that are duplicates 5402 // of this specific one, and remove them from the results. 5403 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5404 N = results.size(); 5405 int j; 5406 for (j=specificsPos; j<N; j++) { 5407 ResolveInfo sri = results.get(j); 5408 if ((sri.activityInfo.name.equals(comp.getClassName()) 5409 && sri.activityInfo.applicationInfo.packageName.equals( 5410 comp.getPackageName())) 5411 || (action != null && sri.filter.matchAction(action))) { 5412 results.remove(j); 5413 if (DEBUG_INTENT_MATCHING) Log.v( 5414 TAG, "Removing duplicate item from " + j 5415 + " due to specific " + specificsPos); 5416 if (ri == null) { 5417 ri = sri; 5418 } 5419 j--; 5420 N--; 5421 } 5422 } 5423 5424 // Add this specific item to its proper place. 5425 if (ri == null) { 5426 ri = new ResolveInfo(); 5427 ri.activityInfo = ai; 5428 } 5429 results.add(specificsPos, ri); 5430 ri.specificIndex = i; 5431 specificsPos++; 5432 } 5433 } 5434 5435 // Now we go through the remaining generic results and remove any 5436 // duplicate actions that are found here. 5437 N = results.size(); 5438 for (int i=specificsPos; i<N-1; i++) { 5439 final ResolveInfo rii = results.get(i); 5440 if (rii.filter == null) { 5441 continue; 5442 } 5443 5444 // Iterate over all of the actions of this result's intent 5445 // filter... typically this should be just one. 5446 final Iterator<String> it = rii.filter.actionsIterator(); 5447 if (it == null) { 5448 continue; 5449 } 5450 while (it.hasNext()) { 5451 final String action = it.next(); 5452 if (resultsAction != null && resultsAction.equals(action)) { 5453 // If this action was explicitly requested, then don't 5454 // remove things that have it. 5455 continue; 5456 } 5457 for (int j=i+1; j<N; j++) { 5458 final ResolveInfo rij = results.get(j); 5459 if (rij.filter != null && rij.filter.hasAction(action)) { 5460 results.remove(j); 5461 if (DEBUG_INTENT_MATCHING) Log.v( 5462 TAG, "Removing duplicate item from " + j 5463 + " due to action " + action + " at " + i); 5464 j--; 5465 N--; 5466 } 5467 } 5468 } 5469 5470 // If the caller didn't request filter information, drop it now 5471 // so we don't have to marshall/unmarshall it. 5472 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5473 rii.filter = null; 5474 } 5475 } 5476 5477 // Filter out the caller activity if so requested. 5478 if (caller != null) { 5479 N = results.size(); 5480 for (int i=0; i<N; i++) { 5481 ActivityInfo ainfo = results.get(i).activityInfo; 5482 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5483 && caller.getClassName().equals(ainfo.name)) { 5484 results.remove(i); 5485 break; 5486 } 5487 } 5488 } 5489 5490 // If the caller didn't request filter information, 5491 // drop them now so we don't have to 5492 // marshall/unmarshall it. 5493 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5494 N = results.size(); 5495 for (int i=0; i<N; i++) { 5496 results.get(i).filter = null; 5497 } 5498 } 5499 5500 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5501 return results; 5502 } 5503 5504 @Override 5505 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5506 int userId) { 5507 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5508 flags = augmentFlagsForUser(flags, userId); 5509 ComponentName comp = intent.getComponent(); 5510 if (comp == null) { 5511 if (intent.getSelector() != null) { 5512 intent = intent.getSelector(); 5513 comp = intent.getComponent(); 5514 } 5515 } 5516 if (comp != null) { 5517 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5518 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5519 if (ai != null) { 5520 ResolveInfo ri = new ResolveInfo(); 5521 ri.activityInfo = ai; 5522 list.add(ri); 5523 } 5524 return list; 5525 } 5526 5527 // reader 5528 synchronized (mPackages) { 5529 String pkgName = intent.getPackage(); 5530 if (pkgName == null) { 5531 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5532 } 5533 final PackageParser.Package pkg = mPackages.get(pkgName); 5534 if (pkg != null) { 5535 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5536 userId); 5537 } 5538 return null; 5539 } 5540 } 5541 5542 @Override 5543 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5544 if (!sUserManager.exists(userId)) return null; 5545 flags = augmentFlagsForUser(flags, userId); 5546 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5547 if (query != null) { 5548 if (query.size() >= 1) { 5549 // If there is more than one service with the same priority, 5550 // just arbitrarily pick the first one. 5551 return query.get(0); 5552 } 5553 } 5554 return null; 5555 } 5556 5557 @Override 5558 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5559 int userId) { 5560 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5561 flags = augmentFlagsForUser(flags, userId); 5562 ComponentName comp = intent.getComponent(); 5563 if (comp == null) { 5564 if (intent.getSelector() != null) { 5565 intent = intent.getSelector(); 5566 comp = intent.getComponent(); 5567 } 5568 } 5569 if (comp != null) { 5570 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5571 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5572 if (si != null) { 5573 final ResolveInfo ri = new ResolveInfo(); 5574 ri.serviceInfo = si; 5575 list.add(ri); 5576 } 5577 return list; 5578 } 5579 5580 // reader 5581 synchronized (mPackages) { 5582 String pkgName = intent.getPackage(); 5583 if (pkgName == null) { 5584 return mServices.queryIntent(intent, resolvedType, flags, userId); 5585 } 5586 final PackageParser.Package pkg = mPackages.get(pkgName); 5587 if (pkg != null) { 5588 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5589 userId); 5590 } 5591 return null; 5592 } 5593 } 5594 5595 @Override 5596 public List<ResolveInfo> queryIntentContentProviders( 5597 Intent intent, String resolvedType, int flags, int userId) { 5598 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5599 flags = augmentFlagsForUser(flags, userId); 5600 ComponentName comp = intent.getComponent(); 5601 if (comp == null) { 5602 if (intent.getSelector() != null) { 5603 intent = intent.getSelector(); 5604 comp = intent.getComponent(); 5605 } 5606 } 5607 if (comp != null) { 5608 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5609 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5610 if (pi != null) { 5611 final ResolveInfo ri = new ResolveInfo(); 5612 ri.providerInfo = pi; 5613 list.add(ri); 5614 } 5615 return list; 5616 } 5617 5618 // reader 5619 synchronized (mPackages) { 5620 String pkgName = intent.getPackage(); 5621 if (pkgName == null) { 5622 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5623 } 5624 final PackageParser.Package pkg = mPackages.get(pkgName); 5625 if (pkg != null) { 5626 return mProviders.queryIntentForPackage( 5627 intent, resolvedType, flags, pkg.providers, userId); 5628 } 5629 return null; 5630 } 5631 } 5632 5633 @Override 5634 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5635 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5636 5637 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5638 5639 // writer 5640 synchronized (mPackages) { 5641 ArrayList<PackageInfo> list; 5642 if (listUninstalled) { 5643 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5644 for (PackageSetting ps : mSettings.mPackages.values()) { 5645 PackageInfo pi; 5646 if (ps.pkg != null) { 5647 pi = generatePackageInfo(ps.pkg, flags, userId); 5648 } else { 5649 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5650 } 5651 if (pi != null) { 5652 list.add(pi); 5653 } 5654 } 5655 } else { 5656 list = new ArrayList<PackageInfo>(mPackages.size()); 5657 for (PackageParser.Package p : mPackages.values()) { 5658 PackageInfo pi = generatePackageInfo(p, flags, userId); 5659 if (pi != null) { 5660 list.add(pi); 5661 } 5662 } 5663 } 5664 5665 return new ParceledListSlice<PackageInfo>(list); 5666 } 5667 } 5668 5669 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5670 String[] permissions, boolean[] tmp, int flags, int userId) { 5671 int numMatch = 0; 5672 final PermissionsState permissionsState = ps.getPermissionsState(); 5673 for (int i=0; i<permissions.length; i++) { 5674 final String permission = permissions[i]; 5675 if (permissionsState.hasPermission(permission, userId)) { 5676 tmp[i] = true; 5677 numMatch++; 5678 } else { 5679 tmp[i] = false; 5680 } 5681 } 5682 if (numMatch == 0) { 5683 return; 5684 } 5685 PackageInfo pi; 5686 if (ps.pkg != null) { 5687 pi = generatePackageInfo(ps.pkg, flags, userId); 5688 } else { 5689 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5690 } 5691 // The above might return null in cases of uninstalled apps or install-state 5692 // skew across users/profiles. 5693 if (pi != null) { 5694 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5695 if (numMatch == permissions.length) { 5696 pi.requestedPermissions = permissions; 5697 } else { 5698 pi.requestedPermissions = new String[numMatch]; 5699 numMatch = 0; 5700 for (int i=0; i<permissions.length; i++) { 5701 if (tmp[i]) { 5702 pi.requestedPermissions[numMatch] = permissions[i]; 5703 numMatch++; 5704 } 5705 } 5706 } 5707 } 5708 list.add(pi); 5709 } 5710 } 5711 5712 @Override 5713 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5714 String[] permissions, int flags, int userId) { 5715 if (!sUserManager.exists(userId)) return null; 5716 flags = augmentFlagsForUser(flags, userId); 5717 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5718 5719 // writer 5720 synchronized (mPackages) { 5721 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5722 boolean[] tmpBools = new boolean[permissions.length]; 5723 if (listUninstalled) { 5724 for (PackageSetting ps : mSettings.mPackages.values()) { 5725 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5726 } 5727 } else { 5728 for (PackageParser.Package pkg : mPackages.values()) { 5729 PackageSetting ps = (PackageSetting)pkg.mExtras; 5730 if (ps != null) { 5731 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5732 userId); 5733 } 5734 } 5735 } 5736 5737 return new ParceledListSlice<PackageInfo>(list); 5738 } 5739 } 5740 5741 @Override 5742 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5743 if (!sUserManager.exists(userId)) return null; 5744 flags = augmentFlagsForUser(flags, userId); 5745 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5746 5747 // writer 5748 synchronized (mPackages) { 5749 ArrayList<ApplicationInfo> list; 5750 if (listUninstalled) { 5751 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5752 for (PackageSetting ps : mSettings.mPackages.values()) { 5753 ApplicationInfo ai; 5754 if (ps.pkg != null) { 5755 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5756 ps.readUserState(userId), userId); 5757 } else { 5758 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5759 } 5760 if (ai != null) { 5761 list.add(ai); 5762 } 5763 } 5764 } else { 5765 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5766 for (PackageParser.Package p : mPackages.values()) { 5767 if (p.mExtras != null) { 5768 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5769 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5770 if (ai != null) { 5771 list.add(ai); 5772 } 5773 } 5774 } 5775 } 5776 5777 return new ParceledListSlice<ApplicationInfo>(list); 5778 } 5779 } 5780 5781 @Override 5782 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5783 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5784 "getEphemeralApplications"); 5785 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5786 "getEphemeralApplications"); 5787 synchronized (mPackages) { 5788 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5789 .getEphemeralApplicationsLPw(userId); 5790 if (ephemeralApps != null) { 5791 return new ParceledListSlice<>(ephemeralApps); 5792 } 5793 } 5794 return null; 5795 } 5796 5797 @Override 5798 public boolean isEphemeralApplication(String packageName, int userId) { 5799 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5800 "isEphemeral"); 5801 if (!isCallerSameApp(packageName)) { 5802 return false; 5803 } 5804 synchronized (mPackages) { 5805 PackageParser.Package pkg = mPackages.get(packageName); 5806 if (pkg != null) { 5807 return pkg.applicationInfo.isEphemeralApp(); 5808 } 5809 } 5810 return false; 5811 } 5812 5813 @Override 5814 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5815 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5816 "getCookie"); 5817 if (!isCallerSameApp(packageName)) { 5818 return null; 5819 } 5820 synchronized (mPackages) { 5821 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5822 packageName, userId); 5823 } 5824 } 5825 5826 @Override 5827 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5828 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5829 "setCookie"); 5830 if (!isCallerSameApp(packageName)) { 5831 return false; 5832 } 5833 synchronized (mPackages) { 5834 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5835 packageName, cookie, userId); 5836 } 5837 } 5838 5839 @Override 5840 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5841 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5842 "getEphemeralApplicationIcon"); 5843 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5844 "getEphemeralApplicationIcon"); 5845 synchronized (mPackages) { 5846 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5847 packageName, userId); 5848 } 5849 } 5850 5851 private boolean isCallerSameApp(String packageName) { 5852 PackageParser.Package pkg = mPackages.get(packageName); 5853 return pkg != null 5854 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5855 } 5856 5857 public List<ApplicationInfo> getPersistentApplications(int flags) { 5858 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5859 5860 // reader 5861 synchronized (mPackages) { 5862 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5863 final int userId = UserHandle.getCallingUserId(); 5864 while (i.hasNext()) { 5865 final PackageParser.Package p = i.next(); 5866 if (p.applicationInfo != null 5867 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5868 && (!mSafeMode || isSystemApp(p))) { 5869 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5870 if (ps != null) { 5871 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5872 ps.readUserState(userId), userId); 5873 if (ai != null) { 5874 finalList.add(ai); 5875 } 5876 } 5877 } 5878 } 5879 } 5880 5881 return finalList; 5882 } 5883 5884 @Override 5885 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5886 if (!sUserManager.exists(userId)) return null; 5887 flags = augmentFlagsForUser(flags, userId); 5888 // reader 5889 synchronized (mPackages) { 5890 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5891 PackageSetting ps = provider != null 5892 ? mSettings.mPackages.get(provider.owner.packageName) 5893 : null; 5894 return ps != null 5895 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5896 && (!mSafeMode || (provider.info.applicationInfo.flags 5897 &ApplicationInfo.FLAG_SYSTEM) != 0) 5898 ? PackageParser.generateProviderInfo(provider, flags, 5899 ps.readUserState(userId), userId) 5900 : null; 5901 } 5902 } 5903 5904 /** 5905 * @deprecated 5906 */ 5907 @Deprecated 5908 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5909 // reader 5910 synchronized (mPackages) { 5911 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5912 .entrySet().iterator(); 5913 final int userId = UserHandle.getCallingUserId(); 5914 while (i.hasNext()) { 5915 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5916 PackageParser.Provider p = entry.getValue(); 5917 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5918 5919 if (ps != null && p.syncable 5920 && (!mSafeMode || (p.info.applicationInfo.flags 5921 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5922 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5923 ps.readUserState(userId), userId); 5924 if (info != null) { 5925 outNames.add(entry.getKey()); 5926 outInfo.add(info); 5927 } 5928 } 5929 } 5930 } 5931 } 5932 5933 @Override 5934 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5935 int uid, int flags) { 5936 final int userId = processName != null ? UserHandle.getUserId(uid) 5937 : UserHandle.getCallingUserId(); 5938 if (!sUserManager.exists(userId)) return null; 5939 flags = augmentFlagsForUser(flags, userId); 5940 5941 ArrayList<ProviderInfo> finalList = null; 5942 // reader 5943 synchronized (mPackages) { 5944 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5945 while (i.hasNext()) { 5946 final PackageParser.Provider p = i.next(); 5947 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5948 if (ps != null && p.info.authority != null 5949 && (processName == null 5950 || (p.info.processName.equals(processName) 5951 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5952 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5953 && (!mSafeMode 5954 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5955 if (finalList == null) { 5956 finalList = new ArrayList<ProviderInfo>(3); 5957 } 5958 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5959 ps.readUserState(userId), userId); 5960 if (info != null) { 5961 finalList.add(info); 5962 } 5963 } 5964 } 5965 } 5966 5967 if (finalList != null) { 5968 Collections.sort(finalList, mProviderInitOrderSorter); 5969 return new ParceledListSlice<ProviderInfo>(finalList); 5970 } 5971 5972 return null; 5973 } 5974 5975 @Override 5976 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5977 int flags) { 5978 // reader 5979 synchronized (mPackages) { 5980 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5981 return PackageParser.generateInstrumentationInfo(i, flags); 5982 } 5983 } 5984 5985 @Override 5986 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5987 int flags) { 5988 ArrayList<InstrumentationInfo> finalList = 5989 new ArrayList<InstrumentationInfo>(); 5990 5991 // reader 5992 synchronized (mPackages) { 5993 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5994 while (i.hasNext()) { 5995 final PackageParser.Instrumentation p = i.next(); 5996 if (targetPackage == null 5997 || targetPackage.equals(p.info.targetPackage)) { 5998 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5999 flags); 6000 if (ii != null) { 6001 finalList.add(ii); 6002 } 6003 } 6004 } 6005 } 6006 6007 return finalList; 6008 } 6009 6010 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6011 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6012 if (overlays == null) { 6013 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6014 return; 6015 } 6016 for (PackageParser.Package opkg : overlays.values()) { 6017 // Not much to do if idmap fails: we already logged the error 6018 // and we certainly don't want to abort installation of pkg simply 6019 // because an overlay didn't fit properly. For these reasons, 6020 // ignore the return value of createIdmapForPackagePairLI. 6021 createIdmapForPackagePairLI(pkg, opkg); 6022 } 6023 } 6024 6025 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6026 PackageParser.Package opkg) { 6027 if (!opkg.mTrustedOverlay) { 6028 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6029 opkg.baseCodePath + ": overlay not trusted"); 6030 return false; 6031 } 6032 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6033 if (overlaySet == null) { 6034 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6035 opkg.baseCodePath + " but target package has no known overlays"); 6036 return false; 6037 } 6038 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6039 // TODO: generate idmap for split APKs 6040 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6041 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6042 + opkg.baseCodePath); 6043 return false; 6044 } 6045 PackageParser.Package[] overlayArray = 6046 overlaySet.values().toArray(new PackageParser.Package[0]); 6047 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6048 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6049 return p1.mOverlayPriority - p2.mOverlayPriority; 6050 } 6051 }; 6052 Arrays.sort(overlayArray, cmp); 6053 6054 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6055 int i = 0; 6056 for (PackageParser.Package p : overlayArray) { 6057 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6058 } 6059 return true; 6060 } 6061 6062 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6064 try { 6065 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6066 } finally { 6067 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6068 } 6069 } 6070 6071 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6072 final File[] files = dir.listFiles(); 6073 if (ArrayUtils.isEmpty(files)) { 6074 Log.d(TAG, "No files in app dir " + dir); 6075 return; 6076 } 6077 6078 if (DEBUG_PACKAGE_SCANNING) { 6079 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6080 + " flags=0x" + Integer.toHexString(parseFlags)); 6081 } 6082 6083 for (File file : files) { 6084 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6085 && !PackageInstallerService.isStageName(file.getName()); 6086 if (!isPackage) { 6087 // Ignore entries which are not packages 6088 continue; 6089 } 6090 try { 6091 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6092 scanFlags, currentTime, null); 6093 } catch (PackageManagerException e) { 6094 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6095 6096 // Delete invalid userdata apps 6097 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6098 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6099 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6100 if (file.isDirectory()) { 6101 mInstaller.rmPackageDir(file.getAbsolutePath()); 6102 } else { 6103 file.delete(); 6104 } 6105 } 6106 } 6107 } 6108 } 6109 6110 private static File getSettingsProblemFile() { 6111 File dataDir = Environment.getDataDirectory(); 6112 File systemDir = new File(dataDir, "system"); 6113 File fname = new File(systemDir, "uiderrors.txt"); 6114 return fname; 6115 } 6116 6117 static void reportSettingsProblem(int priority, String msg) { 6118 logCriticalInfo(priority, msg); 6119 } 6120 6121 static void logCriticalInfo(int priority, String msg) { 6122 Slog.println(priority, TAG, msg); 6123 EventLogTags.writePmCriticalInfo(msg); 6124 try { 6125 File fname = getSettingsProblemFile(); 6126 FileOutputStream out = new FileOutputStream(fname, true); 6127 PrintWriter pw = new FastPrintWriter(out); 6128 SimpleDateFormat formatter = new SimpleDateFormat(); 6129 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6130 pw.println(dateString + ": " + msg); 6131 pw.close(); 6132 FileUtils.setPermissions( 6133 fname.toString(), 6134 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6135 -1, -1); 6136 } catch (java.io.IOException e) { 6137 } 6138 } 6139 6140 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6141 PackageParser.Package pkg, File srcFile, int parseFlags) 6142 throws PackageManagerException { 6143 if (ps != null 6144 && ps.codePath.equals(srcFile) 6145 && ps.timeStamp == srcFile.lastModified() 6146 && !isCompatSignatureUpdateNeeded(pkg) 6147 && !isRecoverSignatureUpdateNeeded(pkg)) { 6148 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6149 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6150 ArraySet<PublicKey> signingKs; 6151 synchronized (mPackages) { 6152 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6153 } 6154 if (ps.signatures.mSignatures != null 6155 && ps.signatures.mSignatures.length != 0 6156 && signingKs != null) { 6157 // Optimization: reuse the existing cached certificates 6158 // if the package appears to be unchanged. 6159 pkg.mSignatures = ps.signatures.mSignatures; 6160 pkg.mSigningKeys = signingKs; 6161 return; 6162 } 6163 6164 Slog.w(TAG, "PackageSetting for " + ps.name 6165 + " is missing signatures. Collecting certs again to recover them."); 6166 } else { 6167 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6168 } 6169 6170 try { 6171 pp.collectCertificates(pkg, parseFlags); 6172 pp.collectManifestDigest(pkg); 6173 } catch (PackageParserException e) { 6174 throw PackageManagerException.from(e); 6175 } 6176 } 6177 6178 /** 6179 * Traces a package scan. 6180 * @see #scanPackageLI(File, int, int, long, UserHandle) 6181 */ 6182 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6183 long currentTime, UserHandle user) throws PackageManagerException { 6184 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6185 try { 6186 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6187 } finally { 6188 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6189 } 6190 } 6191 6192 /** 6193 * Scans a package and returns the newly parsed package. 6194 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6195 */ 6196 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6197 long currentTime, UserHandle user) throws PackageManagerException { 6198 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6199 parseFlags |= mDefParseFlags; 6200 PackageParser pp = new PackageParser(); 6201 pp.setSeparateProcesses(mSeparateProcesses); 6202 pp.setOnlyCoreApps(mOnlyCore); 6203 pp.setDisplayMetrics(mMetrics); 6204 6205 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6206 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6207 } 6208 6209 final PackageParser.Package pkg; 6210 try { 6211 pkg = pp.parsePackage(scanFile, parseFlags); 6212 } catch (PackageParserException e) { 6213 throw PackageManagerException.from(e); 6214 } 6215 6216 PackageSetting ps = null; 6217 PackageSetting updatedPkg; 6218 // reader 6219 synchronized (mPackages) { 6220 // Look to see if we already know about this package. 6221 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6222 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6223 // This package has been renamed to its original name. Let's 6224 // use that. 6225 ps = mSettings.peekPackageLPr(oldName); 6226 } 6227 // If there was no original package, see one for the real package name. 6228 if (ps == null) { 6229 ps = mSettings.peekPackageLPr(pkg.packageName); 6230 } 6231 // Check to see if this package could be hiding/updating a system 6232 // package. Must look for it either under the original or real 6233 // package name depending on our state. 6234 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6235 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6236 } 6237 boolean updatedPkgBetter = false; 6238 // First check if this is a system package that may involve an update 6239 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6240 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6241 // it needs to drop FLAG_PRIVILEGED. 6242 if (locationIsPrivileged(scanFile)) { 6243 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6244 } else { 6245 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6246 } 6247 6248 if (ps != null && !ps.codePath.equals(scanFile)) { 6249 // The path has changed from what was last scanned... check the 6250 // version of the new path against what we have stored to determine 6251 // what to do. 6252 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6253 if (pkg.mVersionCode <= ps.versionCode) { 6254 // The system package has been updated and the code path does not match 6255 // Ignore entry. Skip it. 6256 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6257 + " ignored: updated version " + ps.versionCode 6258 + " better than this " + pkg.mVersionCode); 6259 if (!updatedPkg.codePath.equals(scanFile)) { 6260 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6261 + ps.name + " changing from " + updatedPkg.codePathString 6262 + " to " + scanFile); 6263 updatedPkg.codePath = scanFile; 6264 updatedPkg.codePathString = scanFile.toString(); 6265 updatedPkg.resourcePath = scanFile; 6266 updatedPkg.resourcePathString = scanFile.toString(); 6267 } 6268 updatedPkg.pkg = pkg; 6269 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6270 "Package " + ps.name + " at " + scanFile 6271 + " ignored: updated version " + ps.versionCode 6272 + " better than this " + pkg.mVersionCode); 6273 } else { 6274 // The current app on the system partition is better than 6275 // what we have updated to on the data partition; switch 6276 // back to the system partition version. 6277 // At this point, its safely assumed that package installation for 6278 // apps in system partition will go through. If not there won't be a working 6279 // version of the app 6280 // writer 6281 synchronized (mPackages) { 6282 // Just remove the loaded entries from package lists. 6283 mPackages.remove(ps.name); 6284 } 6285 6286 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6287 + " reverting from " + ps.codePathString 6288 + ": new version " + pkg.mVersionCode 6289 + " better than installed " + ps.versionCode); 6290 6291 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6292 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6293 synchronized (mInstallLock) { 6294 args.cleanUpResourcesLI(); 6295 } 6296 synchronized (mPackages) { 6297 mSettings.enableSystemPackageLPw(ps.name); 6298 } 6299 updatedPkgBetter = true; 6300 } 6301 } 6302 } 6303 6304 if (updatedPkg != null) { 6305 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6306 // initially 6307 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6308 6309 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6310 // flag set initially 6311 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6312 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6313 } 6314 } 6315 6316 // Verify certificates against what was last scanned 6317 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6318 6319 /* 6320 * A new system app appeared, but we already had a non-system one of the 6321 * same name installed earlier. 6322 */ 6323 boolean shouldHideSystemApp = false; 6324 if (updatedPkg == null && ps != null 6325 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6326 /* 6327 * Check to make sure the signatures match first. If they don't, 6328 * wipe the installed application and its data. 6329 */ 6330 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6331 != PackageManager.SIGNATURE_MATCH) { 6332 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6333 + " signatures don't match existing userdata copy; removing"); 6334 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6335 ps = null; 6336 } else { 6337 /* 6338 * If the newly-added system app is an older version than the 6339 * already installed version, hide it. It will be scanned later 6340 * and re-added like an update. 6341 */ 6342 if (pkg.mVersionCode <= ps.versionCode) { 6343 shouldHideSystemApp = true; 6344 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6345 + " but new version " + pkg.mVersionCode + " better than installed " 6346 + ps.versionCode + "; hiding system"); 6347 } else { 6348 /* 6349 * The newly found system app is a newer version that the 6350 * one previously installed. Simply remove the 6351 * already-installed application and replace it with our own 6352 * while keeping the application data. 6353 */ 6354 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6355 + " reverting from " + ps.codePathString + ": new version " 6356 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6357 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6358 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6359 synchronized (mInstallLock) { 6360 args.cleanUpResourcesLI(); 6361 } 6362 } 6363 } 6364 } 6365 6366 // The apk is forward locked (not public) if its code and resources 6367 // are kept in different files. (except for app in either system or 6368 // vendor path). 6369 // TODO grab this value from PackageSettings 6370 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6371 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6372 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6373 } 6374 } 6375 6376 // TODO: extend to support forward-locked splits 6377 String resourcePath = null; 6378 String baseResourcePath = null; 6379 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6380 if (ps != null && ps.resourcePathString != null) { 6381 resourcePath = ps.resourcePathString; 6382 baseResourcePath = ps.resourcePathString; 6383 } else { 6384 // Should not happen at all. Just log an error. 6385 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6386 } 6387 } else { 6388 resourcePath = pkg.codePath; 6389 baseResourcePath = pkg.baseCodePath; 6390 } 6391 6392 // Set application objects path explicitly. 6393 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6394 pkg.applicationInfo.setCodePath(pkg.codePath); 6395 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6396 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6397 pkg.applicationInfo.setResourcePath(resourcePath); 6398 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6399 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6400 6401 // Note that we invoke the following method only if we are about to unpack an application 6402 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6403 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6404 6405 /* 6406 * If the system app should be overridden by a previously installed 6407 * data, hide the system app now and let the /data/app scan pick it up 6408 * again. 6409 */ 6410 if (shouldHideSystemApp) { 6411 synchronized (mPackages) { 6412 mSettings.disableSystemPackageLPw(pkg.packageName); 6413 } 6414 } 6415 6416 return scannedPkg; 6417 } 6418 6419 private static String fixProcessName(String defProcessName, 6420 String processName, int uid) { 6421 if (processName == null) { 6422 return defProcessName; 6423 } 6424 return processName; 6425 } 6426 6427 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6428 throws PackageManagerException { 6429 if (pkgSetting.signatures.mSignatures != null) { 6430 // Already existing package. Make sure signatures match 6431 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6432 == PackageManager.SIGNATURE_MATCH; 6433 if (!match) { 6434 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6435 == PackageManager.SIGNATURE_MATCH; 6436 } 6437 if (!match) { 6438 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6439 == PackageManager.SIGNATURE_MATCH; 6440 } 6441 if (!match) { 6442 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6443 + pkg.packageName + " signatures do not match the " 6444 + "previously installed version; ignoring!"); 6445 } 6446 } 6447 6448 // Check for shared user signatures 6449 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6450 // Already existing package. Make sure signatures match 6451 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6452 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6453 if (!match) { 6454 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6455 == PackageManager.SIGNATURE_MATCH; 6456 } 6457 if (!match) { 6458 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6459 == PackageManager.SIGNATURE_MATCH; 6460 } 6461 if (!match) { 6462 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6463 "Package " + pkg.packageName 6464 + " has no signatures that match those in shared user " 6465 + pkgSetting.sharedUser.name + "; ignoring!"); 6466 } 6467 } 6468 } 6469 6470 /** 6471 * Enforces that only the system UID or root's UID can call a method exposed 6472 * via Binder. 6473 * 6474 * @param message used as message if SecurityException is thrown 6475 * @throws SecurityException if the caller is not system or root 6476 */ 6477 private static final void enforceSystemOrRoot(String message) { 6478 final int uid = Binder.getCallingUid(); 6479 if (uid != Process.SYSTEM_UID && uid != 0) { 6480 throw new SecurityException(message); 6481 } 6482 } 6483 6484 @Override 6485 public void performFstrimIfNeeded() { 6486 enforceSystemOrRoot("Only the system can request fstrim"); 6487 6488 // Before everything else, see whether we need to fstrim. 6489 try { 6490 IMountService ms = PackageHelper.getMountService(); 6491 if (ms != null) { 6492 final boolean isUpgrade = isUpgrade(); 6493 boolean doTrim = isUpgrade; 6494 if (doTrim) { 6495 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6496 } else { 6497 final long interval = android.provider.Settings.Global.getLong( 6498 mContext.getContentResolver(), 6499 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6500 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6501 if (interval > 0) { 6502 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6503 if (timeSinceLast > interval) { 6504 doTrim = true; 6505 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6506 + "; running immediately"); 6507 } 6508 } 6509 } 6510 if (doTrim) { 6511 if (!isFirstBoot()) { 6512 try { 6513 ActivityManagerNative.getDefault().showBootMessage( 6514 mContext.getResources().getString( 6515 R.string.android_upgrading_fstrim), true); 6516 } catch (RemoteException e) { 6517 } 6518 } 6519 ms.runMaintenance(); 6520 } 6521 } else { 6522 Slog.e(TAG, "Mount service unavailable!"); 6523 } 6524 } catch (RemoteException e) { 6525 // Can't happen; MountService is local 6526 } 6527 } 6528 6529 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6530 List<ResolveInfo> ris = null; 6531 try { 6532 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6533 intent, null, 0, userId); 6534 } catch (RemoteException e) { 6535 } 6536 ArraySet<String> pkgNames = new ArraySet<String>(); 6537 if (ris != null) { 6538 for (ResolveInfo ri : ris) { 6539 pkgNames.add(ri.activityInfo.packageName); 6540 } 6541 } 6542 return pkgNames; 6543 } 6544 6545 @Override 6546 public void notifyPackageUse(String packageName) { 6547 synchronized (mPackages) { 6548 PackageParser.Package p = mPackages.get(packageName); 6549 if (p == null) { 6550 return; 6551 } 6552 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6553 } 6554 } 6555 6556 @Override 6557 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6558 return performDexOptTraced(packageName, instructionSet); 6559 } 6560 6561 public boolean performDexOpt(String packageName, String instructionSet) { 6562 return performDexOptTraced(packageName, instructionSet); 6563 } 6564 6565 private boolean performDexOptTraced(String packageName, String instructionSet) { 6566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6567 try { 6568 return performDexOptInternal(packageName, instructionSet); 6569 } finally { 6570 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6571 } 6572 } 6573 6574 private boolean performDexOptInternal(String packageName, String instructionSet) { 6575 PackageParser.Package p; 6576 final String targetInstructionSet; 6577 synchronized (mPackages) { 6578 p = mPackages.get(packageName); 6579 if (p == null) { 6580 return false; 6581 } 6582 mPackageUsage.write(false); 6583 6584 targetInstructionSet = instructionSet != null ? instructionSet : 6585 getPrimaryInstructionSet(p.applicationInfo); 6586 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6587 return false; 6588 } 6589 } 6590 long callingId = Binder.clearCallingIdentity(); 6591 try { 6592 synchronized (mInstallLock) { 6593 final String[] instructionSets = new String[] { targetInstructionSet }; 6594 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6595 true /* inclDependencies */); 6596 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6597 } 6598 } finally { 6599 Binder.restoreCallingIdentity(callingId); 6600 } 6601 } 6602 6603 public ArraySet<String> getPackagesThatNeedDexOpt() { 6604 ArraySet<String> pkgs = null; 6605 synchronized (mPackages) { 6606 for (PackageParser.Package p : mPackages.values()) { 6607 if (DEBUG_DEXOPT) { 6608 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6609 } 6610 if (!p.mDexOptPerformed.isEmpty()) { 6611 continue; 6612 } 6613 if (pkgs == null) { 6614 pkgs = new ArraySet<String>(); 6615 } 6616 pkgs.add(p.packageName); 6617 } 6618 } 6619 return pkgs; 6620 } 6621 6622 public void shutdown() { 6623 mPackageUsage.write(true); 6624 } 6625 6626 @Override 6627 public void forceDexOpt(String packageName) { 6628 enforceSystemOrRoot("forceDexOpt"); 6629 6630 PackageParser.Package pkg; 6631 synchronized (mPackages) { 6632 pkg = mPackages.get(packageName); 6633 if (pkg == null) { 6634 throw new IllegalArgumentException("Missing package: " + packageName); 6635 } 6636 } 6637 6638 synchronized (mInstallLock) { 6639 final String[] instructionSets = new String[] { 6640 getPrimaryInstructionSet(pkg.applicationInfo) }; 6641 6642 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6643 6644 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6645 true /* inclDependencies */); 6646 6647 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6648 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6649 throw new IllegalStateException("Failed to dexopt: " + res); 6650 } 6651 } 6652 } 6653 6654 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6655 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6656 Slog.w(TAG, "Unable to update from " + oldPkg.name 6657 + " to " + newPkg.packageName 6658 + ": old package not in system partition"); 6659 return false; 6660 } else if (mPackages.get(oldPkg.name) != null) { 6661 Slog.w(TAG, "Unable to update from " + oldPkg.name 6662 + " to " + newPkg.packageName 6663 + ": old package still exists"); 6664 return false; 6665 } 6666 return true; 6667 } 6668 6669 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6670 throws PackageManagerException { 6671 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6672 if (res != 0) { 6673 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6674 "Failed to install " + packageName + ": " + res); 6675 } 6676 6677 final int[] users = sUserManager.getUserIds(); 6678 for (int user : users) { 6679 if (user != 0) { 6680 res = mInstaller.createUserData(volumeUuid, packageName, 6681 UserHandle.getUid(user, uid), user, seinfo); 6682 if (res != 0) { 6683 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6684 "Failed to createUserData " + packageName + ": " + res); 6685 } 6686 } 6687 } 6688 } 6689 6690 private int removeDataDirsLI(String volumeUuid, String packageName) { 6691 int[] users = sUserManager.getUserIds(); 6692 int res = 0; 6693 for (int user : users) { 6694 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6695 if (resInner < 0) { 6696 res = resInner; 6697 } 6698 } 6699 6700 return res; 6701 } 6702 6703 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6704 int[] users = sUserManager.getUserIds(); 6705 int res = 0; 6706 for (int user : users) { 6707 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6708 if (resInner < 0) { 6709 res = resInner; 6710 } 6711 } 6712 return res; 6713 } 6714 6715 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6716 PackageParser.Package changingLib) { 6717 if (file.path != null) { 6718 usesLibraryFiles.add(file.path); 6719 return; 6720 } 6721 PackageParser.Package p = mPackages.get(file.apk); 6722 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6723 // If we are doing this while in the middle of updating a library apk, 6724 // then we need to make sure to use that new apk for determining the 6725 // dependencies here. (We haven't yet finished committing the new apk 6726 // to the package manager state.) 6727 if (p == null || p.packageName.equals(changingLib.packageName)) { 6728 p = changingLib; 6729 } 6730 } 6731 if (p != null) { 6732 usesLibraryFiles.addAll(p.getAllCodePaths()); 6733 } 6734 } 6735 6736 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6737 PackageParser.Package changingLib) throws PackageManagerException { 6738 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6739 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6740 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6741 for (int i=0; i<N; i++) { 6742 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6743 if (file == null) { 6744 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6745 "Package " + pkg.packageName + " requires unavailable shared library " 6746 + pkg.usesLibraries.get(i) + "; failing!"); 6747 } 6748 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6749 } 6750 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6751 for (int i=0; i<N; i++) { 6752 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6753 if (file == null) { 6754 Slog.w(TAG, "Package " + pkg.packageName 6755 + " desires unavailable shared library " 6756 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6757 } else { 6758 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6759 } 6760 } 6761 N = usesLibraryFiles.size(); 6762 if (N > 0) { 6763 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6764 } else { 6765 pkg.usesLibraryFiles = null; 6766 } 6767 } 6768 } 6769 6770 private static boolean hasString(List<String> list, List<String> which) { 6771 if (list == null) { 6772 return false; 6773 } 6774 for (int i=list.size()-1; i>=0; i--) { 6775 for (int j=which.size()-1; j>=0; j--) { 6776 if (which.get(j).equals(list.get(i))) { 6777 return true; 6778 } 6779 } 6780 } 6781 return false; 6782 } 6783 6784 private void updateAllSharedLibrariesLPw() { 6785 for (PackageParser.Package pkg : mPackages.values()) { 6786 try { 6787 updateSharedLibrariesLPw(pkg, null); 6788 } catch (PackageManagerException e) { 6789 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6790 } 6791 } 6792 } 6793 6794 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6795 PackageParser.Package changingPkg) { 6796 ArrayList<PackageParser.Package> res = null; 6797 for (PackageParser.Package pkg : mPackages.values()) { 6798 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6799 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6800 if (res == null) { 6801 res = new ArrayList<PackageParser.Package>(); 6802 } 6803 res.add(pkg); 6804 try { 6805 updateSharedLibrariesLPw(pkg, changingPkg); 6806 } catch (PackageManagerException e) { 6807 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6808 } 6809 } 6810 } 6811 return res; 6812 } 6813 6814 /** 6815 * Derive the value of the {@code cpuAbiOverride} based on the provided 6816 * value and an optional stored value from the package settings. 6817 */ 6818 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6819 String cpuAbiOverride = null; 6820 6821 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6822 cpuAbiOverride = null; 6823 } else if (abiOverride != null) { 6824 cpuAbiOverride = abiOverride; 6825 } else if (settings != null) { 6826 cpuAbiOverride = settings.cpuAbiOverrideString; 6827 } 6828 6829 return cpuAbiOverride; 6830 } 6831 6832 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6833 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6835 try { 6836 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6837 } finally { 6838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6839 } 6840 } 6841 6842 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6843 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6844 boolean success = false; 6845 try { 6846 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6847 currentTime, user); 6848 success = true; 6849 return res; 6850 } finally { 6851 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6852 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6853 } 6854 } 6855 } 6856 6857 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6858 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6859 final File scanFile = new File(pkg.codePath); 6860 if (pkg.applicationInfo.getCodePath() == null || 6861 pkg.applicationInfo.getResourcePath() == null) { 6862 // Bail out. The resource and code paths haven't been set. 6863 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6864 "Code and resource paths haven't been set correctly"); 6865 } 6866 6867 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6868 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6869 } else { 6870 // Only allow system apps to be flagged as core apps. 6871 pkg.coreApp = false; 6872 } 6873 6874 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6875 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6876 } 6877 6878 if (mCustomResolverComponentName != null && 6879 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6880 setUpCustomResolverActivity(pkg); 6881 } 6882 6883 if (pkg.packageName.equals("android")) { 6884 synchronized (mPackages) { 6885 if (mAndroidApplication != null) { 6886 Slog.w(TAG, "*************************************************"); 6887 Slog.w(TAG, "Core android package being redefined. Skipping."); 6888 Slog.w(TAG, " file=" + scanFile); 6889 Slog.w(TAG, "*************************************************"); 6890 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6891 "Core android package being redefined. Skipping."); 6892 } 6893 6894 // Set up information for our fall-back user intent resolution activity. 6895 mPlatformPackage = pkg; 6896 pkg.mVersionCode = mSdkVersion; 6897 mAndroidApplication = pkg.applicationInfo; 6898 6899 if (!mResolverReplaced) { 6900 mResolveActivity.applicationInfo = mAndroidApplication; 6901 mResolveActivity.name = ResolverActivity.class.getName(); 6902 mResolveActivity.packageName = mAndroidApplication.packageName; 6903 mResolveActivity.processName = "system:ui"; 6904 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6905 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6906 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6907 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6908 mResolveActivity.exported = true; 6909 mResolveActivity.enabled = true; 6910 mResolveInfo.activityInfo = mResolveActivity; 6911 mResolveInfo.priority = 0; 6912 mResolveInfo.preferredOrder = 0; 6913 mResolveInfo.match = 0; 6914 mResolveComponentName = new ComponentName( 6915 mAndroidApplication.packageName, mResolveActivity.name); 6916 } 6917 } 6918 } 6919 6920 if (DEBUG_PACKAGE_SCANNING) { 6921 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6922 Log.d(TAG, "Scanning package " + pkg.packageName); 6923 } 6924 6925 if (mPackages.containsKey(pkg.packageName) 6926 || mSharedLibraries.containsKey(pkg.packageName)) { 6927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6928 "Application package " + pkg.packageName 6929 + " already installed. Skipping duplicate."); 6930 } 6931 6932 // If we're only installing presumed-existing packages, require that the 6933 // scanned APK is both already known and at the path previously established 6934 // for it. Previously unknown packages we pick up normally, but if we have an 6935 // a priori expectation about this package's install presence, enforce it. 6936 // With a singular exception for new system packages. When an OTA contains 6937 // a new system package, we allow the codepath to change from a system location 6938 // to the user-installed location. If we don't allow this change, any newer, 6939 // user-installed version of the application will be ignored. 6940 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6941 if (mExpectingBetter.containsKey(pkg.packageName)) { 6942 logCriticalInfo(Log.WARN, 6943 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6944 } else { 6945 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6946 if (known != null) { 6947 if (DEBUG_PACKAGE_SCANNING) { 6948 Log.d(TAG, "Examining " + pkg.codePath 6949 + " and requiring known paths " + known.codePathString 6950 + " & " + known.resourcePathString); 6951 } 6952 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6953 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6954 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6955 "Application package " + pkg.packageName 6956 + " found at " + pkg.applicationInfo.getCodePath() 6957 + " but expected at " + known.codePathString + "; ignoring."); 6958 } 6959 } 6960 } 6961 } 6962 6963 // Initialize package source and resource directories 6964 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6965 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6966 6967 SharedUserSetting suid = null; 6968 PackageSetting pkgSetting = null; 6969 6970 if (!isSystemApp(pkg)) { 6971 // Only system apps can use these features. 6972 pkg.mOriginalPackages = null; 6973 pkg.mRealPackage = null; 6974 pkg.mAdoptPermissions = null; 6975 } 6976 6977 // writer 6978 synchronized (mPackages) { 6979 if (pkg.mSharedUserId != null) { 6980 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6981 if (suid == null) { 6982 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6983 "Creating application package " + pkg.packageName 6984 + " for shared user failed"); 6985 } 6986 if (DEBUG_PACKAGE_SCANNING) { 6987 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6988 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6989 + "): packages=" + suid.packages); 6990 } 6991 } 6992 6993 // Check if we are renaming from an original package name. 6994 PackageSetting origPackage = null; 6995 String realName = null; 6996 if (pkg.mOriginalPackages != null) { 6997 // This package may need to be renamed to a previously 6998 // installed name. Let's check on that... 6999 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7000 if (pkg.mOriginalPackages.contains(renamed)) { 7001 // This package had originally been installed as the 7002 // original name, and we have already taken care of 7003 // transitioning to the new one. Just update the new 7004 // one to continue using the old name. 7005 realName = pkg.mRealPackage; 7006 if (!pkg.packageName.equals(renamed)) { 7007 // Callers into this function may have already taken 7008 // care of renaming the package; only do it here if 7009 // it is not already done. 7010 pkg.setPackageName(renamed); 7011 } 7012 7013 } else { 7014 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7015 if ((origPackage = mSettings.peekPackageLPr( 7016 pkg.mOriginalPackages.get(i))) != null) { 7017 // We do have the package already installed under its 7018 // original name... should we use it? 7019 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7020 // New package is not compatible with original. 7021 origPackage = null; 7022 continue; 7023 } else if (origPackage.sharedUser != null) { 7024 // Make sure uid is compatible between packages. 7025 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7026 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7027 + " to " + pkg.packageName + ": old uid " 7028 + origPackage.sharedUser.name 7029 + " differs from " + pkg.mSharedUserId); 7030 origPackage = null; 7031 continue; 7032 } 7033 } else { 7034 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7035 + pkg.packageName + " to old name " + origPackage.name); 7036 } 7037 break; 7038 } 7039 } 7040 } 7041 } 7042 7043 if (mTransferedPackages.contains(pkg.packageName)) { 7044 Slog.w(TAG, "Package " + pkg.packageName 7045 + " was transferred to another, but its .apk remains"); 7046 } 7047 7048 // Just create the setting, don't add it yet. For already existing packages 7049 // the PkgSetting exists already and doesn't have to be created. 7050 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7051 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7052 pkg.applicationInfo.primaryCpuAbi, 7053 pkg.applicationInfo.secondaryCpuAbi, 7054 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7055 user, false); 7056 if (pkgSetting == null) { 7057 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7058 "Creating application package " + pkg.packageName + " failed"); 7059 } 7060 7061 if (pkgSetting.origPackage != null) { 7062 // If we are first transitioning from an original package, 7063 // fix up the new package's name now. We need to do this after 7064 // looking up the package under its new name, so getPackageLP 7065 // can take care of fiddling things correctly. 7066 pkg.setPackageName(origPackage.name); 7067 7068 // File a report about this. 7069 String msg = "New package " + pkgSetting.realName 7070 + " renamed to replace old package " + pkgSetting.name; 7071 reportSettingsProblem(Log.WARN, msg); 7072 7073 // Make a note of it. 7074 mTransferedPackages.add(origPackage.name); 7075 7076 // No longer need to retain this. 7077 pkgSetting.origPackage = null; 7078 } 7079 7080 if (realName != null) { 7081 // Make a note of it. 7082 mTransferedPackages.add(pkg.packageName); 7083 } 7084 7085 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7086 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7087 } 7088 7089 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7090 // Check all shared libraries and map to their actual file path. 7091 // We only do this here for apps not on a system dir, because those 7092 // are the only ones that can fail an install due to this. We 7093 // will take care of the system apps by updating all of their 7094 // library paths after the scan is done. 7095 updateSharedLibrariesLPw(pkg, null); 7096 } 7097 7098 if (mFoundPolicyFile) { 7099 SELinuxMMAC.assignSeinfoValue(pkg); 7100 } 7101 7102 pkg.applicationInfo.uid = pkgSetting.appId; 7103 pkg.mExtras = pkgSetting; 7104 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7105 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7106 // We just determined the app is signed correctly, so bring 7107 // over the latest parsed certs. 7108 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7109 } else { 7110 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7111 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7112 "Package " + pkg.packageName + " upgrade keys do not match the " 7113 + "previously installed version"); 7114 } else { 7115 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7116 String msg = "System package " + pkg.packageName 7117 + " signature changed; retaining data."; 7118 reportSettingsProblem(Log.WARN, msg); 7119 } 7120 } 7121 } else { 7122 try { 7123 verifySignaturesLP(pkgSetting, pkg); 7124 // We just determined the app is signed correctly, so bring 7125 // over the latest parsed certs. 7126 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7127 } catch (PackageManagerException e) { 7128 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7129 throw e; 7130 } 7131 // The signature has changed, but this package is in the system 7132 // image... let's recover! 7133 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7134 // However... if this package is part of a shared user, but it 7135 // doesn't match the signature of the shared user, let's fail. 7136 // What this means is that you can't change the signatures 7137 // associated with an overall shared user, which doesn't seem all 7138 // that unreasonable. 7139 if (pkgSetting.sharedUser != null) { 7140 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7141 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7142 throw new PackageManagerException( 7143 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7144 "Signature mismatch for shared user : " 7145 + pkgSetting.sharedUser); 7146 } 7147 } 7148 // File a report about this. 7149 String msg = "System package " + pkg.packageName 7150 + " signature changed; retaining data."; 7151 reportSettingsProblem(Log.WARN, msg); 7152 } 7153 } 7154 // Verify that this new package doesn't have any content providers 7155 // that conflict with existing packages. Only do this if the 7156 // package isn't already installed, since we don't want to break 7157 // things that are installed. 7158 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7159 final int N = pkg.providers.size(); 7160 int i; 7161 for (i=0; i<N; i++) { 7162 PackageParser.Provider p = pkg.providers.get(i); 7163 if (p.info.authority != null) { 7164 String names[] = p.info.authority.split(";"); 7165 for (int j = 0; j < names.length; j++) { 7166 if (mProvidersByAuthority.containsKey(names[j])) { 7167 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7168 final String otherPackageName = 7169 ((other != null && other.getComponentName() != null) ? 7170 other.getComponentName().getPackageName() : "?"); 7171 throw new PackageManagerException( 7172 INSTALL_FAILED_CONFLICTING_PROVIDER, 7173 "Can't install because provider name " + names[j] 7174 + " (in package " + pkg.applicationInfo.packageName 7175 + ") is already used by " + otherPackageName); 7176 } 7177 } 7178 } 7179 } 7180 } 7181 7182 if (pkg.mAdoptPermissions != null) { 7183 // This package wants to adopt ownership of permissions from 7184 // another package. 7185 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7186 final String origName = pkg.mAdoptPermissions.get(i); 7187 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7188 if (orig != null) { 7189 if (verifyPackageUpdateLPr(orig, pkg)) { 7190 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7191 + pkg.packageName); 7192 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7193 } 7194 } 7195 } 7196 } 7197 } 7198 7199 final String pkgName = pkg.packageName; 7200 7201 final long scanFileTime = scanFile.lastModified(); 7202 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7203 pkg.applicationInfo.processName = fixProcessName( 7204 pkg.applicationInfo.packageName, 7205 pkg.applicationInfo.processName, 7206 pkg.applicationInfo.uid); 7207 7208 if (pkg != mPlatformPackage) { 7209 // This is a normal package, need to make its data directory. 7210 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7211 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7212 7213 boolean uidError = false; 7214 if (dataPath.exists()) { 7215 int currentUid = 0; 7216 try { 7217 StructStat stat = Os.stat(dataPath.getPath()); 7218 currentUid = stat.st_uid; 7219 } catch (ErrnoException e) { 7220 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7221 } 7222 7223 // If we have mismatched owners for the data path, we have a problem. 7224 if (currentUid != pkg.applicationInfo.uid) { 7225 boolean recovered = false; 7226 if (currentUid == 0) { 7227 // The directory somehow became owned by root. Wow. 7228 // This is probably because the system was stopped while 7229 // installd was in the middle of messing with its libs 7230 // directory. Ask installd to fix that. 7231 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7232 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7233 if (ret >= 0) { 7234 recovered = true; 7235 String msg = "Package " + pkg.packageName 7236 + " unexpectedly changed to uid 0; recovered to " + 7237 + pkg.applicationInfo.uid; 7238 reportSettingsProblem(Log.WARN, msg); 7239 } 7240 } 7241 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7242 || (scanFlags&SCAN_BOOTING) != 0)) { 7243 // If this is a system app, we can at least delete its 7244 // current data so the application will still work. 7245 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7246 if (ret >= 0) { 7247 // TODO: Kill the processes first 7248 // Old data gone! 7249 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7250 ? "System package " : "Third party package "; 7251 String msg = prefix + pkg.packageName 7252 + " has changed from uid: " 7253 + currentUid + " to " 7254 + pkg.applicationInfo.uid + "; old data erased"; 7255 reportSettingsProblem(Log.WARN, msg); 7256 recovered = true; 7257 } 7258 if (!recovered) { 7259 mHasSystemUidErrors = true; 7260 } 7261 } else if (!recovered) { 7262 // If we allow this install to proceed, we will be broken. 7263 // Abort, abort! 7264 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7265 "scanPackageLI"); 7266 } 7267 if (!recovered) { 7268 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7269 + pkg.applicationInfo.uid + "/fs_" 7270 + currentUid; 7271 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7272 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7273 String msg = "Package " + pkg.packageName 7274 + " has mismatched uid: " 7275 + currentUid + " on disk, " 7276 + pkg.applicationInfo.uid + " in settings"; 7277 // writer 7278 synchronized (mPackages) { 7279 mSettings.mReadMessages.append(msg); 7280 mSettings.mReadMessages.append('\n'); 7281 uidError = true; 7282 if (!pkgSetting.uidError) { 7283 reportSettingsProblem(Log.ERROR, msg); 7284 } 7285 } 7286 } 7287 } 7288 7289 // Ensure that directories are prepared 7290 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7291 pkg.applicationInfo.seinfo); 7292 7293 if (mShouldRestoreconData) { 7294 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7295 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7296 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7297 } 7298 } else { 7299 if (DEBUG_PACKAGE_SCANNING) { 7300 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7301 Log.v(TAG, "Want this data dir: " + dataPath); 7302 } 7303 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7304 pkg.applicationInfo.seinfo); 7305 } 7306 7307 // Get all of our default paths setup 7308 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7309 7310 pkgSetting.uidError = uidError; 7311 } 7312 7313 final String path = scanFile.getPath(); 7314 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7315 7316 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7317 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7318 7319 // Some system apps still use directory structure for native libraries 7320 // in which case we might end up not detecting abi solely based on apk 7321 // structure. Try to detect abi based on directory structure. 7322 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7323 pkg.applicationInfo.primaryCpuAbi == null) { 7324 setBundledAppAbisAndRoots(pkg, pkgSetting); 7325 setNativeLibraryPaths(pkg); 7326 } 7327 7328 } else { 7329 if ((scanFlags & SCAN_MOVE) != 0) { 7330 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7331 // but we already have this packages package info in the PackageSetting. We just 7332 // use that and derive the native library path based on the new codepath. 7333 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7334 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7335 } 7336 7337 // Set native library paths again. For moves, the path will be updated based on the 7338 // ABIs we've determined above. For non-moves, the path will be updated based on the 7339 // ABIs we determined during compilation, but the path will depend on the final 7340 // package path (after the rename away from the stage path). 7341 setNativeLibraryPaths(pkg); 7342 } 7343 7344 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7345 final int[] userIds = sUserManager.getUserIds(); 7346 synchronized (mInstallLock) { 7347 // Make sure all user data directories are ready to roll; we're okay 7348 // if they already exist 7349 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7350 for (int userId : userIds) { 7351 if (userId != UserHandle.USER_SYSTEM) { 7352 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7353 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7354 pkg.applicationInfo.seinfo); 7355 } 7356 } 7357 } 7358 7359 // Create a native library symlink only if we have native libraries 7360 // and if the native libraries are 32 bit libraries. We do not provide 7361 // this symlink for 64 bit libraries. 7362 if (pkg.applicationInfo.primaryCpuAbi != null && 7363 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7365 try { 7366 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7367 for (int userId : userIds) { 7368 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7369 nativeLibPath, userId) < 0) { 7370 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7371 "Failed linking native library dir (user=" + userId + ")"); 7372 } 7373 } 7374 } finally { 7375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7376 } 7377 } 7378 } 7379 7380 // This is a special case for the "system" package, where the ABI is 7381 // dictated by the zygote configuration (and init.rc). We should keep track 7382 // of this ABI so that we can deal with "normal" applications that run under 7383 // the same UID correctly. 7384 if (mPlatformPackage == pkg) { 7385 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7386 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7387 } 7388 7389 // If there's a mismatch between the abi-override in the package setting 7390 // and the abiOverride specified for the install. Warn about this because we 7391 // would've already compiled the app without taking the package setting into 7392 // account. 7393 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7394 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7395 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7396 " for package: " + pkg.packageName); 7397 } 7398 } 7399 7400 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7401 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7402 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7403 7404 // Copy the derived override back to the parsed package, so that we can 7405 // update the package settings accordingly. 7406 pkg.cpuAbiOverride = cpuAbiOverride; 7407 7408 if (DEBUG_ABI_SELECTION) { 7409 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7410 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7411 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7412 } 7413 7414 // Push the derived path down into PackageSettings so we know what to 7415 // clean up at uninstall time. 7416 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7417 7418 if (DEBUG_ABI_SELECTION) { 7419 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7420 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7421 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7422 } 7423 7424 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7425 // We don't do this here during boot because we can do it all 7426 // at once after scanning all existing packages. 7427 // 7428 // We also do this *before* we perform dexopt on this package, so that 7429 // we can avoid redundant dexopts, and also to make sure we've got the 7430 // code and package path correct. 7431 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7432 pkg, true /* boot complete */); 7433 } 7434 7435 if (mFactoryTest && pkg.requestedPermissions.contains( 7436 android.Manifest.permission.FACTORY_TEST)) { 7437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7438 } 7439 7440 ArrayList<PackageParser.Package> clientLibPkgs = null; 7441 7442 // writer 7443 synchronized (mPackages) { 7444 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7445 // Only system apps can add new shared libraries. 7446 if (pkg.libraryNames != null) { 7447 for (int i=0; i<pkg.libraryNames.size(); i++) { 7448 String name = pkg.libraryNames.get(i); 7449 boolean allowed = false; 7450 if (pkg.isUpdatedSystemApp()) { 7451 // New library entries can only be added through the 7452 // system image. This is important to get rid of a lot 7453 // of nasty edge cases: for example if we allowed a non- 7454 // system update of the app to add a library, then uninstalling 7455 // the update would make the library go away, and assumptions 7456 // we made such as through app install filtering would now 7457 // have allowed apps on the device which aren't compatible 7458 // with it. Better to just have the restriction here, be 7459 // conservative, and create many fewer cases that can negatively 7460 // impact the user experience. 7461 final PackageSetting sysPs = mSettings 7462 .getDisabledSystemPkgLPr(pkg.packageName); 7463 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7464 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7465 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7466 allowed = true; 7467 break; 7468 } 7469 } 7470 } 7471 } else { 7472 allowed = true; 7473 } 7474 if (allowed) { 7475 if (!mSharedLibraries.containsKey(name)) { 7476 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7477 } else if (!name.equals(pkg.packageName)) { 7478 Slog.w(TAG, "Package " + pkg.packageName + " library " 7479 + name + " already exists; skipping"); 7480 } 7481 } else { 7482 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7483 + name + " that is not declared on system image; skipping"); 7484 } 7485 } 7486 if ((scanFlags & SCAN_BOOTING) == 0) { 7487 // If we are not booting, we need to update any applications 7488 // that are clients of our shared library. If we are booting, 7489 // this will all be done once the scan is complete. 7490 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7491 } 7492 } 7493 } 7494 } 7495 7496 // Request the ActivityManager to kill the process(only for existing packages) 7497 // so that we do not end up in a confused state while the user is still using the older 7498 // version of the application while the new one gets installed. 7499 if ((scanFlags & SCAN_REPLACING) != 0) { 7500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7501 7502 killApplication(pkg.applicationInfo.packageName, 7503 pkg.applicationInfo.uid, "replace pkg"); 7504 7505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7506 } 7507 7508 // Also need to kill any apps that are dependent on the library. 7509 if (clientLibPkgs != null) { 7510 for (int i=0; i<clientLibPkgs.size(); i++) { 7511 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7512 killApplication(clientPkg.applicationInfo.packageName, 7513 clientPkg.applicationInfo.uid, "update lib"); 7514 } 7515 } 7516 7517 // Make sure we're not adding any bogus keyset info 7518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7519 ksms.assertScannedPackageValid(pkg); 7520 7521 // writer 7522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7523 7524 boolean createIdmapFailed = false; 7525 synchronized (mPackages) { 7526 // We don't expect installation to fail beyond this point 7527 7528 // Add the new setting to mSettings 7529 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7530 // Add the new setting to mPackages 7531 mPackages.put(pkg.applicationInfo.packageName, pkg); 7532 // Make sure we don't accidentally delete its data. 7533 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7534 while (iter.hasNext()) { 7535 PackageCleanItem item = iter.next(); 7536 if (pkgName.equals(item.packageName)) { 7537 iter.remove(); 7538 } 7539 } 7540 7541 // Take care of first install / last update times. 7542 if (currentTime != 0) { 7543 if (pkgSetting.firstInstallTime == 0) { 7544 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7545 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7546 pkgSetting.lastUpdateTime = currentTime; 7547 } 7548 } else if (pkgSetting.firstInstallTime == 0) { 7549 // We need *something*. Take time time stamp of the file. 7550 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7551 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7552 if (scanFileTime != pkgSetting.timeStamp) { 7553 // A package on the system image has changed; consider this 7554 // to be an update. 7555 pkgSetting.lastUpdateTime = scanFileTime; 7556 } 7557 } 7558 7559 // Add the package's KeySets to the global KeySetManagerService 7560 ksms.addScannedPackageLPw(pkg); 7561 7562 int N = pkg.providers.size(); 7563 StringBuilder r = null; 7564 int i; 7565 for (i=0; i<N; i++) { 7566 PackageParser.Provider p = pkg.providers.get(i); 7567 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7568 p.info.processName, pkg.applicationInfo.uid); 7569 mProviders.addProvider(p); 7570 p.syncable = p.info.isSyncable; 7571 if (p.info.authority != null) { 7572 String names[] = p.info.authority.split(";"); 7573 p.info.authority = null; 7574 for (int j = 0; j < names.length; j++) { 7575 if (j == 1 && p.syncable) { 7576 // We only want the first authority for a provider to possibly be 7577 // syncable, so if we already added this provider using a different 7578 // authority clear the syncable flag. We copy the provider before 7579 // changing it because the mProviders object contains a reference 7580 // to a provider that we don't want to change. 7581 // Only do this for the second authority since the resulting provider 7582 // object can be the same for all future authorities for this provider. 7583 p = new PackageParser.Provider(p); 7584 p.syncable = false; 7585 } 7586 if (!mProvidersByAuthority.containsKey(names[j])) { 7587 mProvidersByAuthority.put(names[j], p); 7588 if (p.info.authority == null) { 7589 p.info.authority = names[j]; 7590 } else { 7591 p.info.authority = p.info.authority + ";" + names[j]; 7592 } 7593 if (DEBUG_PACKAGE_SCANNING) { 7594 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7595 Log.d(TAG, "Registered content provider: " + names[j] 7596 + ", className = " + p.info.name + ", isSyncable = " 7597 + p.info.isSyncable); 7598 } 7599 } else { 7600 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7601 Slog.w(TAG, "Skipping provider name " + names[j] + 7602 " (in package " + pkg.applicationInfo.packageName + 7603 "): name already used by " 7604 + ((other != null && other.getComponentName() != null) 7605 ? other.getComponentName().getPackageName() : "?")); 7606 } 7607 } 7608 } 7609 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7610 if (r == null) { 7611 r = new StringBuilder(256); 7612 } else { 7613 r.append(' '); 7614 } 7615 r.append(p.info.name); 7616 } 7617 } 7618 if (r != null) { 7619 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7620 } 7621 7622 N = pkg.services.size(); 7623 r = null; 7624 for (i=0; i<N; i++) { 7625 PackageParser.Service s = pkg.services.get(i); 7626 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7627 s.info.processName, pkg.applicationInfo.uid); 7628 mServices.addService(s); 7629 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7630 if (r == null) { 7631 r = new StringBuilder(256); 7632 } else { 7633 r.append(' '); 7634 } 7635 r.append(s.info.name); 7636 } 7637 } 7638 if (r != null) { 7639 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7640 } 7641 7642 N = pkg.receivers.size(); 7643 r = null; 7644 for (i=0; i<N; i++) { 7645 PackageParser.Activity a = pkg.receivers.get(i); 7646 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7647 a.info.processName, pkg.applicationInfo.uid); 7648 mReceivers.addActivity(a, "receiver"); 7649 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7650 if (r == null) { 7651 r = new StringBuilder(256); 7652 } else { 7653 r.append(' '); 7654 } 7655 r.append(a.info.name); 7656 } 7657 } 7658 if (r != null) { 7659 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7660 } 7661 7662 N = pkg.activities.size(); 7663 r = null; 7664 for (i=0; i<N; i++) { 7665 PackageParser.Activity a = pkg.activities.get(i); 7666 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7667 a.info.processName, pkg.applicationInfo.uid); 7668 mActivities.addActivity(a, "activity"); 7669 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7670 if (r == null) { 7671 r = new StringBuilder(256); 7672 } else { 7673 r.append(' '); 7674 } 7675 r.append(a.info.name); 7676 } 7677 } 7678 if (r != null) { 7679 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7680 } 7681 7682 N = pkg.permissionGroups.size(); 7683 r = null; 7684 for (i=0; i<N; i++) { 7685 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7686 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7687 if (cur == null) { 7688 mPermissionGroups.put(pg.info.name, pg); 7689 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7690 if (r == null) { 7691 r = new StringBuilder(256); 7692 } else { 7693 r.append(' '); 7694 } 7695 r.append(pg.info.name); 7696 } 7697 } else { 7698 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7699 + pg.info.packageName + " ignored: original from " 7700 + cur.info.packageName); 7701 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7702 if (r == null) { 7703 r = new StringBuilder(256); 7704 } else { 7705 r.append(' '); 7706 } 7707 r.append("DUP:"); 7708 r.append(pg.info.name); 7709 } 7710 } 7711 } 7712 if (r != null) { 7713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7714 } 7715 7716 N = pkg.permissions.size(); 7717 r = null; 7718 for (i=0; i<N; i++) { 7719 PackageParser.Permission p = pkg.permissions.get(i); 7720 7721 // Assume by default that we did not install this permission into the system. 7722 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7723 7724 // Now that permission groups have a special meaning, we ignore permission 7725 // groups for legacy apps to prevent unexpected behavior. In particular, 7726 // permissions for one app being granted to someone just becuase they happen 7727 // to be in a group defined by another app (before this had no implications). 7728 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7729 p.group = mPermissionGroups.get(p.info.group); 7730 // Warn for a permission in an unknown group. 7731 if (p.info.group != null && p.group == null) { 7732 Slog.w(TAG, "Permission " + p.info.name + " from package " 7733 + p.info.packageName + " in an unknown group " + p.info.group); 7734 } 7735 } 7736 7737 ArrayMap<String, BasePermission> permissionMap = 7738 p.tree ? mSettings.mPermissionTrees 7739 : mSettings.mPermissions; 7740 BasePermission bp = permissionMap.get(p.info.name); 7741 7742 // Allow system apps to redefine non-system permissions 7743 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7744 final boolean currentOwnerIsSystem = (bp.perm != null 7745 && isSystemApp(bp.perm.owner)); 7746 if (isSystemApp(p.owner)) { 7747 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7748 // It's a built-in permission and no owner, take ownership now 7749 bp.packageSetting = pkgSetting; 7750 bp.perm = p; 7751 bp.uid = pkg.applicationInfo.uid; 7752 bp.sourcePackage = p.info.packageName; 7753 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7754 } else if (!currentOwnerIsSystem) { 7755 String msg = "New decl " + p.owner + " of permission " 7756 + p.info.name + " is system; overriding " + bp.sourcePackage; 7757 reportSettingsProblem(Log.WARN, msg); 7758 bp = null; 7759 } 7760 } 7761 } 7762 7763 if (bp == null) { 7764 bp = new BasePermission(p.info.name, p.info.packageName, 7765 BasePermission.TYPE_NORMAL); 7766 permissionMap.put(p.info.name, bp); 7767 } 7768 7769 if (bp.perm == null) { 7770 if (bp.sourcePackage == null 7771 || bp.sourcePackage.equals(p.info.packageName)) { 7772 BasePermission tree = findPermissionTreeLP(p.info.name); 7773 if (tree == null 7774 || tree.sourcePackage.equals(p.info.packageName)) { 7775 bp.packageSetting = pkgSetting; 7776 bp.perm = p; 7777 bp.uid = pkg.applicationInfo.uid; 7778 bp.sourcePackage = p.info.packageName; 7779 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7780 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7781 if (r == null) { 7782 r = new StringBuilder(256); 7783 } else { 7784 r.append(' '); 7785 } 7786 r.append(p.info.name); 7787 } 7788 } else { 7789 Slog.w(TAG, "Permission " + p.info.name + " from package " 7790 + p.info.packageName + " ignored: base tree " 7791 + tree.name + " is from package " 7792 + tree.sourcePackage); 7793 } 7794 } else { 7795 Slog.w(TAG, "Permission " + p.info.name + " from package " 7796 + p.info.packageName + " ignored: original from " 7797 + bp.sourcePackage); 7798 } 7799 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7800 if (r == null) { 7801 r = new StringBuilder(256); 7802 } else { 7803 r.append(' '); 7804 } 7805 r.append("DUP:"); 7806 r.append(p.info.name); 7807 } 7808 if (bp.perm == p) { 7809 bp.protectionLevel = p.info.protectionLevel; 7810 } 7811 } 7812 7813 if (r != null) { 7814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7815 } 7816 7817 N = pkg.instrumentation.size(); 7818 r = null; 7819 for (i=0; i<N; i++) { 7820 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7821 a.info.packageName = pkg.applicationInfo.packageName; 7822 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7823 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7824 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7825 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7826 a.info.dataDir = pkg.applicationInfo.dataDir; 7827 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7828 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7829 7830 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7831 // need other information about the application, like the ABI and what not ? 7832 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7833 mInstrumentation.put(a.getComponentName(), a); 7834 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7835 if (r == null) { 7836 r = new StringBuilder(256); 7837 } else { 7838 r.append(' '); 7839 } 7840 r.append(a.info.name); 7841 } 7842 } 7843 if (r != null) { 7844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7845 } 7846 7847 if (pkg.protectedBroadcasts != null) { 7848 N = pkg.protectedBroadcasts.size(); 7849 for (i=0; i<N; i++) { 7850 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7851 } 7852 } 7853 7854 pkgSetting.setTimeStamp(scanFileTime); 7855 7856 // Create idmap files for pairs of (packages, overlay packages). 7857 // Note: "android", ie framework-res.apk, is handled by native layers. 7858 if (pkg.mOverlayTarget != null) { 7859 // This is an overlay package. 7860 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7861 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7862 mOverlays.put(pkg.mOverlayTarget, 7863 new ArrayMap<String, PackageParser.Package>()); 7864 } 7865 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7866 map.put(pkg.packageName, pkg); 7867 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7868 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7869 createIdmapFailed = true; 7870 } 7871 } 7872 } else if (mOverlays.containsKey(pkg.packageName) && 7873 !pkg.packageName.equals("android")) { 7874 // This is a regular package, with one or more known overlay packages. 7875 createIdmapsForPackageLI(pkg); 7876 } 7877 } 7878 7879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7880 7881 if (createIdmapFailed) { 7882 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7883 "scanPackageLI failed to createIdmap"); 7884 } 7885 return pkg; 7886 } 7887 7888 /** 7889 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7890 * is derived purely on the basis of the contents of {@code scanFile} and 7891 * {@code cpuAbiOverride}. 7892 * 7893 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7894 */ 7895 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7896 String cpuAbiOverride, boolean extractLibs) 7897 throws PackageManagerException { 7898 // TODO: We can probably be smarter about this stuff. For installed apps, 7899 // we can calculate this information at install time once and for all. For 7900 // system apps, we can probably assume that this information doesn't change 7901 // after the first boot scan. As things stand, we do lots of unnecessary work. 7902 7903 // Give ourselves some initial paths; we'll come back for another 7904 // pass once we've determined ABI below. 7905 setNativeLibraryPaths(pkg); 7906 7907 // We would never need to extract libs for forward-locked and external packages, 7908 // since the container service will do it for us. We shouldn't attempt to 7909 // extract libs from system app when it was not updated. 7910 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7911 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7912 extractLibs = false; 7913 } 7914 7915 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7916 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7917 7918 NativeLibraryHelper.Handle handle = null; 7919 try { 7920 handle = NativeLibraryHelper.Handle.create(pkg); 7921 // TODO(multiArch): This can be null for apps that didn't go through the 7922 // usual installation process. We can calculate it again, like we 7923 // do during install time. 7924 // 7925 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7926 // unnecessary. 7927 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7928 7929 // Null out the abis so that they can be recalculated. 7930 pkg.applicationInfo.primaryCpuAbi = null; 7931 pkg.applicationInfo.secondaryCpuAbi = null; 7932 if (isMultiArch(pkg.applicationInfo)) { 7933 // Warn if we've set an abiOverride for multi-lib packages.. 7934 // By definition, we need to copy both 32 and 64 bit libraries for 7935 // such packages. 7936 if (pkg.cpuAbiOverride != null 7937 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7938 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7939 } 7940 7941 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7942 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7943 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7944 if (extractLibs) { 7945 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7946 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7947 useIsaSpecificSubdirs); 7948 } else { 7949 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7950 } 7951 } 7952 7953 maybeThrowExceptionForMultiArchCopy( 7954 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7955 7956 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7957 if (extractLibs) { 7958 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7959 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7960 useIsaSpecificSubdirs); 7961 } else { 7962 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7963 } 7964 } 7965 7966 maybeThrowExceptionForMultiArchCopy( 7967 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7968 7969 if (abi64 >= 0) { 7970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7971 } 7972 7973 if (abi32 >= 0) { 7974 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7975 if (abi64 >= 0) { 7976 pkg.applicationInfo.secondaryCpuAbi = abi; 7977 } else { 7978 pkg.applicationInfo.primaryCpuAbi = abi; 7979 } 7980 } 7981 } else { 7982 String[] abiList = (cpuAbiOverride != null) ? 7983 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7984 7985 // Enable gross and lame hacks for apps that are built with old 7986 // SDK tools. We must scan their APKs for renderscript bitcode and 7987 // not launch them if it's present. Don't bother checking on devices 7988 // that don't have 64 bit support. 7989 boolean needsRenderScriptOverride = false; 7990 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7991 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7992 abiList = Build.SUPPORTED_32_BIT_ABIS; 7993 needsRenderScriptOverride = true; 7994 } 7995 7996 final int copyRet; 7997 if (extractLibs) { 7998 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7999 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8000 } else { 8001 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8002 } 8003 8004 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8005 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8006 "Error unpackaging native libs for app, errorCode=" + copyRet); 8007 } 8008 8009 if (copyRet >= 0) { 8010 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8011 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8012 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8013 } else if (needsRenderScriptOverride) { 8014 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8015 } 8016 } 8017 } catch (IOException ioe) { 8018 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8019 } finally { 8020 IoUtils.closeQuietly(handle); 8021 } 8022 8023 // Now that we've calculated the ABIs and determined if it's an internal app, 8024 // we will go ahead and populate the nativeLibraryPath. 8025 setNativeLibraryPaths(pkg); 8026 } 8027 8028 /** 8029 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8030 * i.e, so that all packages can be run inside a single process if required. 8031 * 8032 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8033 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8034 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8035 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8036 * updating a package that belongs to a shared user. 8037 * 8038 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8039 * adds unnecessary complexity. 8040 */ 8041 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8042 PackageParser.Package scannedPackage, boolean bootComplete) { 8043 String requiredInstructionSet = null; 8044 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8045 requiredInstructionSet = VMRuntime.getInstructionSet( 8046 scannedPackage.applicationInfo.primaryCpuAbi); 8047 } 8048 8049 PackageSetting requirer = null; 8050 for (PackageSetting ps : packagesForUser) { 8051 // If packagesForUser contains scannedPackage, we skip it. This will happen 8052 // when scannedPackage is an update of an existing package. Without this check, 8053 // we will never be able to change the ABI of any package belonging to a shared 8054 // user, even if it's compatible with other packages. 8055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8056 if (ps.primaryCpuAbiString == null) { 8057 continue; 8058 } 8059 8060 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8061 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8062 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8063 // this but there's not much we can do. 8064 String errorMessage = "Instruction set mismatch, " 8065 + ((requirer == null) ? "[caller]" : requirer) 8066 + " requires " + requiredInstructionSet + " whereas " + ps 8067 + " requires " + instructionSet; 8068 Slog.w(TAG, errorMessage); 8069 } 8070 8071 if (requiredInstructionSet == null) { 8072 requiredInstructionSet = instructionSet; 8073 requirer = ps; 8074 } 8075 } 8076 } 8077 8078 if (requiredInstructionSet != null) { 8079 String adjustedAbi; 8080 if (requirer != null) { 8081 // requirer != null implies that either scannedPackage was null or that scannedPackage 8082 // did not require an ABI, in which case we have to adjust scannedPackage to match 8083 // the ABI of the set (which is the same as requirer's ABI) 8084 adjustedAbi = requirer.primaryCpuAbiString; 8085 if (scannedPackage != null) { 8086 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8087 } 8088 } else { 8089 // requirer == null implies that we're updating all ABIs in the set to 8090 // match scannedPackage. 8091 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8092 } 8093 8094 for (PackageSetting ps : packagesForUser) { 8095 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8096 if (ps.primaryCpuAbiString != null) { 8097 continue; 8098 } 8099 8100 ps.primaryCpuAbiString = adjustedAbi; 8101 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8102 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8103 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 8104 mInstaller.rmdex(ps.codePathString, 8105 getDexCodeInstructionSet(getPreferredInstructionSet())); 8106 } 8107 } 8108 } 8109 } 8110 } 8111 8112 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8113 synchronized (mPackages) { 8114 mResolverReplaced = true; 8115 // Set up information for custom user intent resolution activity. 8116 mResolveActivity.applicationInfo = pkg.applicationInfo; 8117 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8118 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8119 mResolveActivity.processName = pkg.applicationInfo.packageName; 8120 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8121 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8122 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8123 mResolveActivity.theme = 0; 8124 mResolveActivity.exported = true; 8125 mResolveActivity.enabled = true; 8126 mResolveInfo.activityInfo = mResolveActivity; 8127 mResolveInfo.priority = 0; 8128 mResolveInfo.preferredOrder = 0; 8129 mResolveInfo.match = 0; 8130 mResolveComponentName = mCustomResolverComponentName; 8131 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8132 mResolveComponentName); 8133 } 8134 } 8135 8136 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8137 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8138 8139 // Set up information for ephemeral installer activity 8140 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8141 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8142 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8143 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8144 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8145 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8146 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8147 mEphemeralInstallerActivity.theme = 0; 8148 mEphemeralInstallerActivity.exported = true; 8149 mEphemeralInstallerActivity.enabled = true; 8150 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8151 mEphemeralInstallerInfo.priority = 0; 8152 mEphemeralInstallerInfo.preferredOrder = 0; 8153 mEphemeralInstallerInfo.match = 0; 8154 8155 if (DEBUG_EPHEMERAL) { 8156 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8157 } 8158 } 8159 8160 private static String calculateBundledApkRoot(final String codePathString) { 8161 final File codePath = new File(codePathString); 8162 final File codeRoot; 8163 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8164 codeRoot = Environment.getRootDirectory(); 8165 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8166 codeRoot = Environment.getOemDirectory(); 8167 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8168 codeRoot = Environment.getVendorDirectory(); 8169 } else { 8170 // Unrecognized code path; take its top real segment as the apk root: 8171 // e.g. /something/app/blah.apk => /something 8172 try { 8173 File f = codePath.getCanonicalFile(); 8174 File parent = f.getParentFile(); // non-null because codePath is a file 8175 File tmp; 8176 while ((tmp = parent.getParentFile()) != null) { 8177 f = parent; 8178 parent = tmp; 8179 } 8180 codeRoot = f; 8181 Slog.w(TAG, "Unrecognized code path " 8182 + codePath + " - using " + codeRoot); 8183 } catch (IOException e) { 8184 // Can't canonicalize the code path -- shenanigans? 8185 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8186 return Environment.getRootDirectory().getPath(); 8187 } 8188 } 8189 return codeRoot.getPath(); 8190 } 8191 8192 /** 8193 * Derive and set the location of native libraries for the given package, 8194 * which varies depending on where and how the package was installed. 8195 */ 8196 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8197 final ApplicationInfo info = pkg.applicationInfo; 8198 final String codePath = pkg.codePath; 8199 final File codeFile = new File(codePath); 8200 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8201 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8202 8203 info.nativeLibraryRootDir = null; 8204 info.nativeLibraryRootRequiresIsa = false; 8205 info.nativeLibraryDir = null; 8206 info.secondaryNativeLibraryDir = null; 8207 8208 if (isApkFile(codeFile)) { 8209 // Monolithic install 8210 if (bundledApp) { 8211 // If "/system/lib64/apkname" exists, assume that is the per-package 8212 // native library directory to use; otherwise use "/system/lib/apkname". 8213 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8214 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8215 getPrimaryInstructionSet(info)); 8216 8217 // This is a bundled system app so choose the path based on the ABI. 8218 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8219 // is just the default path. 8220 final String apkName = deriveCodePathName(codePath); 8221 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8222 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8223 apkName).getAbsolutePath(); 8224 8225 if (info.secondaryCpuAbi != null) { 8226 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8227 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8228 secondaryLibDir, apkName).getAbsolutePath(); 8229 } 8230 } else if (asecApp) { 8231 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8232 .getAbsolutePath(); 8233 } else { 8234 final String apkName = deriveCodePathName(codePath); 8235 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8236 .getAbsolutePath(); 8237 } 8238 8239 info.nativeLibraryRootRequiresIsa = false; 8240 info.nativeLibraryDir = info.nativeLibraryRootDir; 8241 } else { 8242 // Cluster install 8243 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8244 info.nativeLibraryRootRequiresIsa = true; 8245 8246 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8247 getPrimaryInstructionSet(info)).getAbsolutePath(); 8248 8249 if (info.secondaryCpuAbi != null) { 8250 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8251 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8252 } 8253 } 8254 } 8255 8256 /** 8257 * Calculate the abis and roots for a bundled app. These can uniquely 8258 * be determined from the contents of the system partition, i.e whether 8259 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8260 * of this information, and instead assume that the system was built 8261 * sensibly. 8262 */ 8263 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8264 PackageSetting pkgSetting) { 8265 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8266 8267 // If "/system/lib64/apkname" exists, assume that is the per-package 8268 // native library directory to use; otherwise use "/system/lib/apkname". 8269 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8270 setBundledAppAbi(pkg, apkRoot, apkName); 8271 // pkgSetting might be null during rescan following uninstall of updates 8272 // to a bundled app, so accommodate that possibility. The settings in 8273 // that case will be established later from the parsed package. 8274 // 8275 // If the settings aren't null, sync them up with what we've just derived. 8276 // note that apkRoot isn't stored in the package settings. 8277 if (pkgSetting != null) { 8278 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8279 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8280 } 8281 } 8282 8283 /** 8284 * Deduces the ABI of a bundled app and sets the relevant fields on the 8285 * parsed pkg object. 8286 * 8287 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8288 * under which system libraries are installed. 8289 * @param apkName the name of the installed package. 8290 */ 8291 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8292 final File codeFile = new File(pkg.codePath); 8293 8294 final boolean has64BitLibs; 8295 final boolean has32BitLibs; 8296 if (isApkFile(codeFile)) { 8297 // Monolithic install 8298 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8299 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8300 } else { 8301 // Cluster install 8302 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8303 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8304 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8305 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8306 has64BitLibs = (new File(rootDir, isa)).exists(); 8307 } else { 8308 has64BitLibs = false; 8309 } 8310 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8311 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8312 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8313 has32BitLibs = (new File(rootDir, isa)).exists(); 8314 } else { 8315 has32BitLibs = false; 8316 } 8317 } 8318 8319 if (has64BitLibs && !has32BitLibs) { 8320 // The package has 64 bit libs, but not 32 bit libs. Its primary 8321 // ABI should be 64 bit. We can safely assume here that the bundled 8322 // native libraries correspond to the most preferred ABI in the list. 8323 8324 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8325 pkg.applicationInfo.secondaryCpuAbi = null; 8326 } else if (has32BitLibs && !has64BitLibs) { 8327 // The package has 32 bit libs but not 64 bit libs. Its primary 8328 // ABI should be 32 bit. 8329 8330 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8331 pkg.applicationInfo.secondaryCpuAbi = null; 8332 } else if (has32BitLibs && has64BitLibs) { 8333 // The application has both 64 and 32 bit bundled libraries. We check 8334 // here that the app declares multiArch support, and warn if it doesn't. 8335 // 8336 // We will be lenient here and record both ABIs. The primary will be the 8337 // ABI that's higher on the list, i.e, a device that's configured to prefer 8338 // 64 bit apps will see a 64 bit primary ABI, 8339 8340 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8341 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8342 } 8343 8344 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8346 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8347 } else { 8348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8349 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8350 } 8351 } else { 8352 pkg.applicationInfo.primaryCpuAbi = null; 8353 pkg.applicationInfo.secondaryCpuAbi = null; 8354 } 8355 } 8356 8357 private void killApplication(String pkgName, int appId, String reason) { 8358 // Request the ActivityManager to kill the process(only for existing packages) 8359 // so that we do not end up in a confused state while the user is still using the older 8360 // version of the application while the new one gets installed. 8361 IActivityManager am = ActivityManagerNative.getDefault(); 8362 if (am != null) { 8363 try { 8364 am.killApplicationWithAppId(pkgName, appId, reason); 8365 } catch (RemoteException e) { 8366 } 8367 } 8368 } 8369 8370 void removePackageLI(PackageSetting ps, boolean chatty) { 8371 if (DEBUG_INSTALL) { 8372 if (chatty) 8373 Log.d(TAG, "Removing package " + ps.name); 8374 } 8375 8376 // writer 8377 synchronized (mPackages) { 8378 mPackages.remove(ps.name); 8379 final PackageParser.Package pkg = ps.pkg; 8380 if (pkg != null) { 8381 cleanPackageDataStructuresLILPw(pkg, chatty); 8382 } 8383 } 8384 } 8385 8386 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8387 if (DEBUG_INSTALL) { 8388 if (chatty) 8389 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8390 } 8391 8392 // writer 8393 synchronized (mPackages) { 8394 mPackages.remove(pkg.applicationInfo.packageName); 8395 cleanPackageDataStructuresLILPw(pkg, chatty); 8396 } 8397 } 8398 8399 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8400 int N = pkg.providers.size(); 8401 StringBuilder r = null; 8402 int i; 8403 for (i=0; i<N; i++) { 8404 PackageParser.Provider p = pkg.providers.get(i); 8405 mProviders.removeProvider(p); 8406 if (p.info.authority == null) { 8407 8408 /* There was another ContentProvider with this authority when 8409 * this app was installed so this authority is null, 8410 * Ignore it as we don't have to unregister the provider. 8411 */ 8412 continue; 8413 } 8414 String names[] = p.info.authority.split(";"); 8415 for (int j = 0; j < names.length; j++) { 8416 if (mProvidersByAuthority.get(names[j]) == p) { 8417 mProvidersByAuthority.remove(names[j]); 8418 if (DEBUG_REMOVE) { 8419 if (chatty) 8420 Log.d(TAG, "Unregistered content provider: " + names[j] 8421 + ", className = " + p.info.name + ", isSyncable = " 8422 + p.info.isSyncable); 8423 } 8424 } 8425 } 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 (r != null) { 8436 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8437 } 8438 8439 N = pkg.services.size(); 8440 r = null; 8441 for (i=0; i<N; i++) { 8442 PackageParser.Service s = pkg.services.get(i); 8443 mServices.removeService(s); 8444 if (chatty) { 8445 if (r == null) { 8446 r = new StringBuilder(256); 8447 } else { 8448 r.append(' '); 8449 } 8450 r.append(s.info.name); 8451 } 8452 } 8453 if (r != null) { 8454 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8455 } 8456 8457 N = pkg.receivers.size(); 8458 r = null; 8459 for (i=0; i<N; i++) { 8460 PackageParser.Activity a = pkg.receivers.get(i); 8461 mReceivers.removeActivity(a, "receiver"); 8462 if (DEBUG_REMOVE && chatty) { 8463 if (r == null) { 8464 r = new StringBuilder(256); 8465 } else { 8466 r.append(' '); 8467 } 8468 r.append(a.info.name); 8469 } 8470 } 8471 if (r != null) { 8472 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8473 } 8474 8475 N = pkg.activities.size(); 8476 r = null; 8477 for (i=0; i<N; i++) { 8478 PackageParser.Activity a = pkg.activities.get(i); 8479 mActivities.removeActivity(a, "activity"); 8480 if (DEBUG_REMOVE && chatty) { 8481 if (r == null) { 8482 r = new StringBuilder(256); 8483 } else { 8484 r.append(' '); 8485 } 8486 r.append(a.info.name); 8487 } 8488 } 8489 if (r != null) { 8490 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8491 } 8492 8493 N = pkg.permissions.size(); 8494 r = null; 8495 for (i=0; i<N; i++) { 8496 PackageParser.Permission p = pkg.permissions.get(i); 8497 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8498 if (bp == null) { 8499 bp = mSettings.mPermissionTrees.get(p.info.name); 8500 } 8501 if (bp != null && bp.perm == p) { 8502 bp.perm = null; 8503 if (DEBUG_REMOVE && chatty) { 8504 if (r == null) { 8505 r = new StringBuilder(256); 8506 } else { 8507 r.append(' '); 8508 } 8509 r.append(p.info.name); 8510 } 8511 } 8512 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8513 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8514 if (appOpPkgs != null) { 8515 appOpPkgs.remove(pkg.packageName); 8516 } 8517 } 8518 } 8519 if (r != null) { 8520 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8521 } 8522 8523 N = pkg.requestedPermissions.size(); 8524 r = null; 8525 for (i=0; i<N; i++) { 8526 String perm = pkg.requestedPermissions.get(i); 8527 BasePermission bp = mSettings.mPermissions.get(perm); 8528 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8529 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8530 if (appOpPkgs != null) { 8531 appOpPkgs.remove(pkg.packageName); 8532 if (appOpPkgs.isEmpty()) { 8533 mAppOpPermissionPackages.remove(perm); 8534 } 8535 } 8536 } 8537 } 8538 if (r != null) { 8539 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8540 } 8541 8542 N = pkg.instrumentation.size(); 8543 r = null; 8544 for (i=0; i<N; i++) { 8545 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8546 mInstrumentation.remove(a.getComponentName()); 8547 if (DEBUG_REMOVE && chatty) { 8548 if (r == null) { 8549 r = new StringBuilder(256); 8550 } else { 8551 r.append(' '); 8552 } 8553 r.append(a.info.name); 8554 } 8555 } 8556 if (r != null) { 8557 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8558 } 8559 8560 r = null; 8561 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8562 // Only system apps can hold shared libraries. 8563 if (pkg.libraryNames != null) { 8564 for (i=0; i<pkg.libraryNames.size(); i++) { 8565 String name = pkg.libraryNames.get(i); 8566 SharedLibraryEntry cur = mSharedLibraries.get(name); 8567 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8568 mSharedLibraries.remove(name); 8569 if (DEBUG_REMOVE && chatty) { 8570 if (r == null) { 8571 r = new StringBuilder(256); 8572 } else { 8573 r.append(' '); 8574 } 8575 r.append(name); 8576 } 8577 } 8578 } 8579 } 8580 } 8581 if (r != null) { 8582 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8583 } 8584 } 8585 8586 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8587 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8588 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8589 return true; 8590 } 8591 } 8592 return false; 8593 } 8594 8595 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8596 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8597 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8598 8599 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8600 int flags) { 8601 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8602 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8603 } 8604 8605 private void updatePermissionsLPw(String changingPkg, 8606 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8607 // Make sure there are no dangling permission trees. 8608 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8609 while (it.hasNext()) { 8610 final BasePermission bp = it.next(); 8611 if (bp.packageSetting == null) { 8612 // We may not yet have parsed the package, so just see if 8613 // we still know about its settings. 8614 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8615 } 8616 if (bp.packageSetting == null) { 8617 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8618 + " from package " + bp.sourcePackage); 8619 it.remove(); 8620 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8621 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8622 Slog.i(TAG, "Removing old permission tree: " + bp.name 8623 + " from package " + bp.sourcePackage); 8624 flags |= UPDATE_PERMISSIONS_ALL; 8625 it.remove(); 8626 } 8627 } 8628 } 8629 8630 // Make sure all dynamic permissions have been assigned to a package, 8631 // and make sure there are no dangling permissions. 8632 it = mSettings.mPermissions.values().iterator(); 8633 while (it.hasNext()) { 8634 final BasePermission bp = it.next(); 8635 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8636 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8637 + bp.name + " pkg=" + bp.sourcePackage 8638 + " info=" + bp.pendingInfo); 8639 if (bp.packageSetting == null && bp.pendingInfo != null) { 8640 final BasePermission tree = findPermissionTreeLP(bp.name); 8641 if (tree != null && tree.perm != null) { 8642 bp.packageSetting = tree.packageSetting; 8643 bp.perm = new PackageParser.Permission(tree.perm.owner, 8644 new PermissionInfo(bp.pendingInfo)); 8645 bp.perm.info.packageName = tree.perm.info.packageName; 8646 bp.perm.info.name = bp.name; 8647 bp.uid = tree.uid; 8648 } 8649 } 8650 } 8651 if (bp.packageSetting == null) { 8652 // We may not yet have parsed the package, so just see if 8653 // we still know about its settings. 8654 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8655 } 8656 if (bp.packageSetting == null) { 8657 Slog.w(TAG, "Removing dangling permission: " + bp.name 8658 + " from package " + bp.sourcePackage); 8659 it.remove(); 8660 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8661 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8662 Slog.i(TAG, "Removing old permission: " + bp.name 8663 + " from package " + bp.sourcePackage); 8664 flags |= UPDATE_PERMISSIONS_ALL; 8665 it.remove(); 8666 } 8667 } 8668 } 8669 8670 // Now update the permissions for all packages, in particular 8671 // replace the granted permissions of the system packages. 8672 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8673 for (PackageParser.Package pkg : mPackages.values()) { 8674 if (pkg != pkgInfo) { 8675 // Only replace for packages on requested volume 8676 final String volumeUuid = getVolumeUuidForPackage(pkg); 8677 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8678 && Objects.equals(replaceVolumeUuid, volumeUuid); 8679 grantPermissionsLPw(pkg, replace, changingPkg); 8680 } 8681 } 8682 } 8683 8684 if (pkgInfo != null) { 8685 // Only replace for packages on requested volume 8686 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8687 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8688 && Objects.equals(replaceVolumeUuid, volumeUuid); 8689 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8690 } 8691 } 8692 8693 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8694 String packageOfInterest) { 8695 // IMPORTANT: There are two types of permissions: install and runtime. 8696 // Install time permissions are granted when the app is installed to 8697 // all device users and users added in the future. Runtime permissions 8698 // are granted at runtime explicitly to specific users. Normal and signature 8699 // protected permissions are install time permissions. Dangerous permissions 8700 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8701 // otherwise they are runtime permissions. This function does not manage 8702 // runtime permissions except for the case an app targeting Lollipop MR1 8703 // being upgraded to target a newer SDK, in which case dangerous permissions 8704 // are transformed from install time to runtime ones. 8705 8706 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8707 if (ps == null) { 8708 return; 8709 } 8710 8711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8712 8713 PermissionsState permissionsState = ps.getPermissionsState(); 8714 PermissionsState origPermissions = permissionsState; 8715 8716 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8717 8718 boolean runtimePermissionsRevoked = false; 8719 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8720 8721 boolean changedInstallPermission = false; 8722 8723 if (replace) { 8724 ps.installPermissionsFixed = false; 8725 if (!ps.isSharedUser()) { 8726 origPermissions = new PermissionsState(permissionsState); 8727 permissionsState.reset(); 8728 } else { 8729 // We need to know only about runtime permission changes since the 8730 // calling code always writes the install permissions state but 8731 // the runtime ones are written only if changed. The only cases of 8732 // changed runtime permissions here are promotion of an install to 8733 // runtime and revocation of a runtime from a shared user. 8734 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8735 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8736 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8737 runtimePermissionsRevoked = true; 8738 } 8739 } 8740 } 8741 8742 permissionsState.setGlobalGids(mGlobalGids); 8743 8744 final int N = pkg.requestedPermissions.size(); 8745 for (int i=0; i<N; i++) { 8746 final String name = pkg.requestedPermissions.get(i); 8747 final BasePermission bp = mSettings.mPermissions.get(name); 8748 8749 if (DEBUG_INSTALL) { 8750 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8751 } 8752 8753 if (bp == null || bp.packageSetting == null) { 8754 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8755 Slog.w(TAG, "Unknown permission " + name 8756 + " in package " + pkg.packageName); 8757 } 8758 continue; 8759 } 8760 8761 final String perm = bp.name; 8762 boolean allowedSig = false; 8763 int grant = GRANT_DENIED; 8764 8765 // Keep track of app op permissions. 8766 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8767 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8768 if (pkgs == null) { 8769 pkgs = new ArraySet<>(); 8770 mAppOpPermissionPackages.put(bp.name, pkgs); 8771 } 8772 pkgs.add(pkg.packageName); 8773 } 8774 8775 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8776 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8777 >= Build.VERSION_CODES.M; 8778 switch (level) { 8779 case PermissionInfo.PROTECTION_NORMAL: { 8780 // For all apps normal permissions are install time ones. 8781 grant = GRANT_INSTALL; 8782 } break; 8783 8784 case PermissionInfo.PROTECTION_DANGEROUS: { 8785 // If a permission review is required for legacy apps we represent 8786 // their permissions as always granted runtime ones since we need 8787 // to keep the review required permission flag per user while an 8788 // install permission's state is shared across all users. 8789 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8790 // For legacy apps dangerous permissions are install time ones. 8791 grant = GRANT_INSTALL; 8792 } else if (origPermissions.hasInstallPermission(bp.name)) { 8793 // For legacy apps that became modern, install becomes runtime. 8794 grant = GRANT_UPGRADE; 8795 } else if (mPromoteSystemApps 8796 && isSystemApp(ps) 8797 && mExistingSystemPackages.contains(ps.name)) { 8798 // For legacy system apps, install becomes runtime. 8799 // We cannot check hasInstallPermission() for system apps since those 8800 // permissions were granted implicitly and not persisted pre-M. 8801 grant = GRANT_UPGRADE; 8802 } else { 8803 // For modern apps keep runtime permissions unchanged. 8804 grant = GRANT_RUNTIME; 8805 } 8806 } break; 8807 8808 case PermissionInfo.PROTECTION_SIGNATURE: { 8809 // For all apps signature permissions are install time ones. 8810 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8811 if (allowedSig) { 8812 grant = GRANT_INSTALL; 8813 } 8814 } break; 8815 } 8816 8817 if (DEBUG_INSTALL) { 8818 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8819 } 8820 8821 if (grant != GRANT_DENIED) { 8822 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8823 // If this is an existing, non-system package, then 8824 // we can't add any new permissions to it. 8825 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8826 // Except... if this is a permission that was added 8827 // to the platform (note: need to only do this when 8828 // updating the platform). 8829 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8830 grant = GRANT_DENIED; 8831 } 8832 } 8833 } 8834 8835 switch (grant) { 8836 case GRANT_INSTALL: { 8837 // Revoke this as runtime permission to handle the case of 8838 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8839 for (int userId : UserManagerService.getInstance().getUserIds()) { 8840 if (origPermissions.getRuntimePermissionState( 8841 bp.name, userId) != null) { 8842 // Revoke the runtime permission and clear the flags. 8843 origPermissions.revokeRuntimePermission(bp, userId); 8844 origPermissions.updatePermissionFlags(bp, userId, 8845 PackageManager.MASK_PERMISSION_FLAGS, 0); 8846 // If we revoked a permission permission, we have to write. 8847 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8848 changedRuntimePermissionUserIds, userId); 8849 } 8850 } 8851 // Grant an install permission. 8852 if (permissionsState.grantInstallPermission(bp) != 8853 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8854 changedInstallPermission = true; 8855 } 8856 } break; 8857 8858 case GRANT_RUNTIME: { 8859 // Grant previously granted runtime permissions. 8860 for (int userId : UserManagerService.getInstance().getUserIds()) { 8861 PermissionState permissionState = origPermissions 8862 .getRuntimePermissionState(bp.name, userId); 8863 int flags = permissionState != null 8864 ? permissionState.getFlags() : 0; 8865 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8866 if (permissionsState.grantRuntimePermission(bp, userId) == 8867 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8868 // If we cannot put the permission as it was, we have to write. 8869 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8870 changedRuntimePermissionUserIds, userId); 8871 } 8872 // If the app supports runtime permissions no need for a review. 8873 if (Build.PERMISSIONS_REVIEW_REQUIRED 8874 && appSupportsRuntimePermissions 8875 && (flags & PackageManager 8876 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8877 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8878 // Since we changed the flags, we have to write. 8879 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8880 changedRuntimePermissionUserIds, userId); 8881 } 8882 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8883 && !appSupportsRuntimePermissions) { 8884 // For legacy apps that need a permission review, every new 8885 // runtime permission is granted but it is pending a review. 8886 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8887 permissionsState.grantRuntimePermission(bp, userId); 8888 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8889 // We changed the permission and flags, hence have to write. 8890 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8891 changedRuntimePermissionUserIds, userId); 8892 } 8893 } 8894 // Propagate the permission flags. 8895 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8896 } 8897 } break; 8898 8899 case GRANT_UPGRADE: { 8900 // Grant runtime permissions for a previously held install permission. 8901 PermissionState permissionState = origPermissions 8902 .getInstallPermissionState(bp.name); 8903 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8904 8905 if (origPermissions.revokeInstallPermission(bp) 8906 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8907 // We will be transferring the permission flags, so clear them. 8908 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8909 PackageManager.MASK_PERMISSION_FLAGS, 0); 8910 changedInstallPermission = true; 8911 } 8912 8913 // If the permission is not to be promoted to runtime we ignore it and 8914 // also its other flags as they are not applicable to install permissions. 8915 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8916 for (int userId : currentUserIds) { 8917 if (permissionsState.grantRuntimePermission(bp, userId) != 8918 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8919 // Transfer the permission flags. 8920 permissionsState.updatePermissionFlags(bp, userId, 8921 flags, flags); 8922 // If we granted the permission, we have to write. 8923 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8924 changedRuntimePermissionUserIds, userId); 8925 } 8926 } 8927 } 8928 } break; 8929 8930 default: { 8931 if (packageOfInterest == null 8932 || packageOfInterest.equals(pkg.packageName)) { 8933 Slog.w(TAG, "Not granting permission " + perm 8934 + " to package " + pkg.packageName 8935 + " because it was previously installed without"); 8936 } 8937 } break; 8938 } 8939 } else { 8940 if (permissionsState.revokeInstallPermission(bp) != 8941 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8942 // Also drop the permission flags. 8943 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8944 PackageManager.MASK_PERMISSION_FLAGS, 0); 8945 changedInstallPermission = true; 8946 Slog.i(TAG, "Un-granting permission " + perm 8947 + " from package " + pkg.packageName 8948 + " (protectionLevel=" + bp.protectionLevel 8949 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8950 + ")"); 8951 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8952 // Don't print warning for app op permissions, since it is fine for them 8953 // not to be granted, there is a UI for the user to decide. 8954 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8955 Slog.w(TAG, "Not granting permission " + perm 8956 + " to package " + pkg.packageName 8957 + " (protectionLevel=" + bp.protectionLevel 8958 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8959 + ")"); 8960 } 8961 } 8962 } 8963 } 8964 8965 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8966 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8967 // This is the first that we have heard about this package, so the 8968 // permissions we have now selected are fixed until explicitly 8969 // changed. 8970 ps.installPermissionsFixed = true; 8971 } 8972 8973 // Persist the runtime permissions state for users with changes. If permissions 8974 // were revoked because no app in the shared user declares them we have to 8975 // write synchronously to avoid losing runtime permissions state. 8976 for (int userId : changedRuntimePermissionUserIds) { 8977 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8978 } 8979 8980 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8981 } 8982 8983 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8984 boolean allowed = false; 8985 final int NP = PackageParser.NEW_PERMISSIONS.length; 8986 for (int ip=0; ip<NP; ip++) { 8987 final PackageParser.NewPermissionInfo npi 8988 = PackageParser.NEW_PERMISSIONS[ip]; 8989 if (npi.name.equals(perm) 8990 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8991 allowed = true; 8992 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8993 + pkg.packageName); 8994 break; 8995 } 8996 } 8997 return allowed; 8998 } 8999 9000 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9001 BasePermission bp, PermissionsState origPermissions) { 9002 boolean allowed; 9003 allowed = (compareSignatures( 9004 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9005 == PackageManager.SIGNATURE_MATCH) 9006 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9007 == PackageManager.SIGNATURE_MATCH); 9008 if (!allowed && (bp.protectionLevel 9009 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9010 if (isSystemApp(pkg)) { 9011 // For updated system applications, a system permission 9012 // is granted only if it had been defined by the original application. 9013 if (pkg.isUpdatedSystemApp()) { 9014 final PackageSetting sysPs = mSettings 9015 .getDisabledSystemPkgLPr(pkg.packageName); 9016 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9017 // If the original was granted this permission, we take 9018 // that grant decision as read and propagate it to the 9019 // update. 9020 if (sysPs.isPrivileged()) { 9021 allowed = true; 9022 } 9023 } else { 9024 // The system apk may have been updated with an older 9025 // version of the one on the data partition, but which 9026 // granted a new system permission that it didn't have 9027 // before. In this case we do want to allow the app to 9028 // now get the new permission if the ancestral apk is 9029 // privileged to get it. 9030 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9031 for (int j=0; 9032 j<sysPs.pkg.requestedPermissions.size(); j++) { 9033 if (perm.equals( 9034 sysPs.pkg.requestedPermissions.get(j))) { 9035 allowed = true; 9036 break; 9037 } 9038 } 9039 } 9040 } 9041 } else { 9042 allowed = isPrivilegedApp(pkg); 9043 } 9044 } 9045 } 9046 if (!allowed) { 9047 if (!allowed && (bp.protectionLevel 9048 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9049 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9050 // If this was a previously normal/dangerous permission that got moved 9051 // to a system permission as part of the runtime permission redesign, then 9052 // we still want to blindly grant it to old apps. 9053 allowed = true; 9054 } 9055 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9056 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9057 // If this permission is to be granted to the system installer and 9058 // this app is an installer, then it gets the permission. 9059 allowed = true; 9060 } 9061 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9062 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9063 // If this permission is to be granted to the system verifier and 9064 // this app is a verifier, then it gets the permission. 9065 allowed = true; 9066 } 9067 if (!allowed && (bp.protectionLevel 9068 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9069 && isSystemApp(pkg)) { 9070 // Any pre-installed system app is allowed to get this permission. 9071 allowed = true; 9072 } 9073 if (!allowed && (bp.protectionLevel 9074 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9075 // For development permissions, a development permission 9076 // is granted only if it was already granted. 9077 allowed = origPermissions.hasInstallPermission(perm); 9078 } 9079 } 9080 return allowed; 9081 } 9082 9083 final class ActivityIntentResolver 9084 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9086 boolean defaultOnly, int userId) { 9087 if (!sUserManager.exists(userId)) return null; 9088 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9089 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9090 } 9091 9092 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9093 int userId) { 9094 if (!sUserManager.exists(userId)) return null; 9095 mFlags = flags; 9096 return super.queryIntent(intent, resolvedType, 9097 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9098 } 9099 9100 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9101 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9102 if (!sUserManager.exists(userId)) return null; 9103 if (packageActivities == null) { 9104 return null; 9105 } 9106 mFlags = flags; 9107 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9108 final int N = packageActivities.size(); 9109 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9110 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9111 9112 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9113 for (int i = 0; i < N; ++i) { 9114 intentFilters = packageActivities.get(i).intents; 9115 if (intentFilters != null && intentFilters.size() > 0) { 9116 PackageParser.ActivityIntentInfo[] array = 9117 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9118 intentFilters.toArray(array); 9119 listCut.add(array); 9120 } 9121 } 9122 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9123 } 9124 9125 public final void addActivity(PackageParser.Activity a, String type) { 9126 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9127 mActivities.put(a.getComponentName(), a); 9128 if (DEBUG_SHOW_INFO) 9129 Log.v( 9130 TAG, " " + type + " " + 9131 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9132 if (DEBUG_SHOW_INFO) 9133 Log.v(TAG, " Class=" + a.info.name); 9134 final int NI = a.intents.size(); 9135 for (int j=0; j<NI; j++) { 9136 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9137 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9138 intent.setPriority(0); 9139 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9140 + a.className + " with priority > 0, forcing to 0"); 9141 } 9142 if (DEBUG_SHOW_INFO) { 9143 Log.v(TAG, " IntentFilter:"); 9144 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9145 } 9146 if (!intent.debugCheck()) { 9147 Log.w(TAG, "==> For Activity " + a.info.name); 9148 } 9149 addFilter(intent); 9150 } 9151 } 9152 9153 public final void removeActivity(PackageParser.Activity a, String type) { 9154 mActivities.remove(a.getComponentName()); 9155 if (DEBUG_SHOW_INFO) { 9156 Log.v(TAG, " " + type + " " 9157 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9158 : a.info.name) + ":"); 9159 Log.v(TAG, " Class=" + a.info.name); 9160 } 9161 final int NI = a.intents.size(); 9162 for (int j=0; j<NI; j++) { 9163 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9164 if (DEBUG_SHOW_INFO) { 9165 Log.v(TAG, " IntentFilter:"); 9166 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9167 } 9168 removeFilter(intent); 9169 } 9170 } 9171 9172 @Override 9173 protected boolean allowFilterResult( 9174 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9175 ActivityInfo filterAi = filter.activity.info; 9176 for (int i=dest.size()-1; i>=0; i--) { 9177 ActivityInfo destAi = dest.get(i).activityInfo; 9178 if (destAi.name == filterAi.name 9179 && destAi.packageName == filterAi.packageName) { 9180 return false; 9181 } 9182 } 9183 return true; 9184 } 9185 9186 @Override 9187 protected ActivityIntentInfo[] newArray(int size) { 9188 return new ActivityIntentInfo[size]; 9189 } 9190 9191 @Override 9192 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9193 if (!sUserManager.exists(userId)) return true; 9194 PackageParser.Package p = filter.activity.owner; 9195 if (p != null) { 9196 PackageSetting ps = (PackageSetting)p.mExtras; 9197 if (ps != null) { 9198 // System apps are never considered stopped for purposes of 9199 // filtering, because there may be no way for the user to 9200 // actually re-launch them. 9201 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9202 && ps.getStopped(userId); 9203 } 9204 } 9205 return false; 9206 } 9207 9208 @Override 9209 protected boolean isPackageForFilter(String packageName, 9210 PackageParser.ActivityIntentInfo info) { 9211 return packageName.equals(info.activity.owner.packageName); 9212 } 9213 9214 @Override 9215 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9216 int match, int userId) { 9217 if (!sUserManager.exists(userId)) return null; 9218 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9219 return null; 9220 } 9221 final PackageParser.Activity activity = info.activity; 9222 if (mSafeMode && (activity.info.applicationInfo.flags 9223 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9224 return null; 9225 } 9226 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9227 if (ps == null) { 9228 return null; 9229 } 9230 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9231 ps.readUserState(userId), userId); 9232 if (ai == null) { 9233 return null; 9234 } 9235 final ResolveInfo res = new ResolveInfo(); 9236 res.activityInfo = ai; 9237 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9238 res.filter = info; 9239 } 9240 if (info != null) { 9241 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9242 } 9243 res.priority = info.getPriority(); 9244 res.preferredOrder = activity.owner.mPreferredOrder; 9245 //System.out.println("Result: " + res.activityInfo.className + 9246 // " = " + res.priority); 9247 res.match = match; 9248 res.isDefault = info.hasDefault; 9249 res.labelRes = info.labelRes; 9250 res.nonLocalizedLabel = info.nonLocalizedLabel; 9251 if (userNeedsBadging(userId)) { 9252 res.noResourceId = true; 9253 } else { 9254 res.icon = info.icon; 9255 } 9256 res.iconResourceId = info.icon; 9257 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9258 return res; 9259 } 9260 9261 @Override 9262 protected void sortResults(List<ResolveInfo> results) { 9263 Collections.sort(results, mResolvePrioritySorter); 9264 } 9265 9266 @Override 9267 protected void dumpFilter(PrintWriter out, String prefix, 9268 PackageParser.ActivityIntentInfo filter) { 9269 out.print(prefix); out.print( 9270 Integer.toHexString(System.identityHashCode(filter.activity))); 9271 out.print(' '); 9272 filter.activity.printComponentShortName(out); 9273 out.print(" filter "); 9274 out.println(Integer.toHexString(System.identityHashCode(filter))); 9275 } 9276 9277 @Override 9278 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9279 return filter.activity; 9280 } 9281 9282 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9283 PackageParser.Activity activity = (PackageParser.Activity)label; 9284 out.print(prefix); out.print( 9285 Integer.toHexString(System.identityHashCode(activity))); 9286 out.print(' '); 9287 activity.printComponentShortName(out); 9288 if (count > 1) { 9289 out.print(" ("); out.print(count); out.print(" filters)"); 9290 } 9291 out.println(); 9292 } 9293 9294// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9295// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9296// final List<ResolveInfo> retList = Lists.newArrayList(); 9297// while (i.hasNext()) { 9298// final ResolveInfo resolveInfo = i.next(); 9299// if (isEnabledLP(resolveInfo.activityInfo)) { 9300// retList.add(resolveInfo); 9301// } 9302// } 9303// return retList; 9304// } 9305 9306 // Keys are String (activity class name), values are Activity. 9307 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9308 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9309 private int mFlags; 9310 } 9311 9312 private final class ServiceIntentResolver 9313 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9314 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9315 boolean defaultOnly, int userId) { 9316 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9317 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9318 } 9319 9320 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9321 int userId) { 9322 if (!sUserManager.exists(userId)) return null; 9323 mFlags = flags; 9324 return super.queryIntent(intent, resolvedType, 9325 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9326 } 9327 9328 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9329 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9330 if (!sUserManager.exists(userId)) return null; 9331 if (packageServices == null) { 9332 return null; 9333 } 9334 mFlags = flags; 9335 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9336 final int N = packageServices.size(); 9337 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9338 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9339 9340 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9341 for (int i = 0; i < N; ++i) { 9342 intentFilters = packageServices.get(i).intents; 9343 if (intentFilters != null && intentFilters.size() > 0) { 9344 PackageParser.ServiceIntentInfo[] array = 9345 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9346 intentFilters.toArray(array); 9347 listCut.add(array); 9348 } 9349 } 9350 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9351 } 9352 9353 public final void addService(PackageParser.Service s) { 9354 mServices.put(s.getComponentName(), s); 9355 if (DEBUG_SHOW_INFO) { 9356 Log.v(TAG, " " 9357 + (s.info.nonLocalizedLabel != null 9358 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9359 Log.v(TAG, " Class=" + s.info.name); 9360 } 9361 final int NI = s.intents.size(); 9362 int j; 9363 for (j=0; j<NI; j++) { 9364 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9365 if (DEBUG_SHOW_INFO) { 9366 Log.v(TAG, " IntentFilter:"); 9367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9368 } 9369 if (!intent.debugCheck()) { 9370 Log.w(TAG, "==> For Service " + s.info.name); 9371 } 9372 addFilter(intent); 9373 } 9374 } 9375 9376 public final void removeService(PackageParser.Service s) { 9377 mServices.remove(s.getComponentName()); 9378 if (DEBUG_SHOW_INFO) { 9379 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9380 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9381 Log.v(TAG, " Class=" + s.info.name); 9382 } 9383 final int NI = s.intents.size(); 9384 int j; 9385 for (j=0; j<NI; j++) { 9386 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9387 if (DEBUG_SHOW_INFO) { 9388 Log.v(TAG, " IntentFilter:"); 9389 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9390 } 9391 removeFilter(intent); 9392 } 9393 } 9394 9395 @Override 9396 protected boolean allowFilterResult( 9397 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9398 ServiceInfo filterSi = filter.service.info; 9399 for (int i=dest.size()-1; i>=0; i--) { 9400 ServiceInfo destAi = dest.get(i).serviceInfo; 9401 if (destAi.name == filterSi.name 9402 && destAi.packageName == filterSi.packageName) { 9403 return false; 9404 } 9405 } 9406 return true; 9407 } 9408 9409 @Override 9410 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9411 return new PackageParser.ServiceIntentInfo[size]; 9412 } 9413 9414 @Override 9415 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9416 if (!sUserManager.exists(userId)) return true; 9417 PackageParser.Package p = filter.service.owner; 9418 if (p != null) { 9419 PackageSetting ps = (PackageSetting)p.mExtras; 9420 if (ps != null) { 9421 // System apps are never considered stopped for purposes of 9422 // filtering, because there may be no way for the user to 9423 // actually re-launch them. 9424 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9425 && ps.getStopped(userId); 9426 } 9427 } 9428 return false; 9429 } 9430 9431 @Override 9432 protected boolean isPackageForFilter(String packageName, 9433 PackageParser.ServiceIntentInfo info) { 9434 return packageName.equals(info.service.owner.packageName); 9435 } 9436 9437 @Override 9438 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9439 int match, int userId) { 9440 if (!sUserManager.exists(userId)) return null; 9441 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9442 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9443 return null; 9444 } 9445 final PackageParser.Service service = info.service; 9446 if (mSafeMode && (service.info.applicationInfo.flags 9447 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9448 return null; 9449 } 9450 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9451 if (ps == null) { 9452 return null; 9453 } 9454 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9455 ps.readUserState(userId), userId); 9456 if (si == null) { 9457 return null; 9458 } 9459 final ResolveInfo res = new ResolveInfo(); 9460 res.serviceInfo = si; 9461 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9462 res.filter = filter; 9463 } 9464 res.priority = info.getPriority(); 9465 res.preferredOrder = service.owner.mPreferredOrder; 9466 res.match = match; 9467 res.isDefault = info.hasDefault; 9468 res.labelRes = info.labelRes; 9469 res.nonLocalizedLabel = info.nonLocalizedLabel; 9470 res.icon = info.icon; 9471 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9472 return res; 9473 } 9474 9475 @Override 9476 protected void sortResults(List<ResolveInfo> results) { 9477 Collections.sort(results, mResolvePrioritySorter); 9478 } 9479 9480 @Override 9481 protected void dumpFilter(PrintWriter out, String prefix, 9482 PackageParser.ServiceIntentInfo filter) { 9483 out.print(prefix); out.print( 9484 Integer.toHexString(System.identityHashCode(filter.service))); 9485 out.print(' '); 9486 filter.service.printComponentShortName(out); 9487 out.print(" filter "); 9488 out.println(Integer.toHexString(System.identityHashCode(filter))); 9489 } 9490 9491 @Override 9492 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9493 return filter.service; 9494 } 9495 9496 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9497 PackageParser.Service service = (PackageParser.Service)label; 9498 out.print(prefix); out.print( 9499 Integer.toHexString(System.identityHashCode(service))); 9500 out.print(' '); 9501 service.printComponentShortName(out); 9502 if (count > 1) { 9503 out.print(" ("); out.print(count); out.print(" filters)"); 9504 } 9505 out.println(); 9506 } 9507 9508// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9509// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9510// final List<ResolveInfo> retList = Lists.newArrayList(); 9511// while (i.hasNext()) { 9512// final ResolveInfo resolveInfo = (ResolveInfo) i; 9513// if (isEnabledLP(resolveInfo.serviceInfo)) { 9514// retList.add(resolveInfo); 9515// } 9516// } 9517// return retList; 9518// } 9519 9520 // Keys are String (activity class name), values are Activity. 9521 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9522 = new ArrayMap<ComponentName, PackageParser.Service>(); 9523 private int mFlags; 9524 }; 9525 9526 private final class ProviderIntentResolver 9527 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9528 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9529 boolean defaultOnly, int userId) { 9530 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9531 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9532 } 9533 9534 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9535 int userId) { 9536 if (!sUserManager.exists(userId)) 9537 return null; 9538 mFlags = flags; 9539 return super.queryIntent(intent, resolvedType, 9540 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9541 } 9542 9543 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9544 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9545 if (!sUserManager.exists(userId)) 9546 return null; 9547 if (packageProviders == null) { 9548 return null; 9549 } 9550 mFlags = flags; 9551 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9552 final int N = packageProviders.size(); 9553 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9554 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9555 9556 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9557 for (int i = 0; i < N; ++i) { 9558 intentFilters = packageProviders.get(i).intents; 9559 if (intentFilters != null && intentFilters.size() > 0) { 9560 PackageParser.ProviderIntentInfo[] array = 9561 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9562 intentFilters.toArray(array); 9563 listCut.add(array); 9564 } 9565 } 9566 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9567 } 9568 9569 public final void addProvider(PackageParser.Provider p) { 9570 if (mProviders.containsKey(p.getComponentName())) { 9571 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9572 return; 9573 } 9574 9575 mProviders.put(p.getComponentName(), p); 9576 if (DEBUG_SHOW_INFO) { 9577 Log.v(TAG, " " 9578 + (p.info.nonLocalizedLabel != null 9579 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9580 Log.v(TAG, " Class=" + p.info.name); 9581 } 9582 final int NI = p.intents.size(); 9583 int j; 9584 for (j = 0; j < NI; j++) { 9585 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9586 if (DEBUG_SHOW_INFO) { 9587 Log.v(TAG, " IntentFilter:"); 9588 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9589 } 9590 if (!intent.debugCheck()) { 9591 Log.w(TAG, "==> For Provider " + p.info.name); 9592 } 9593 addFilter(intent); 9594 } 9595 } 9596 9597 public final void removeProvider(PackageParser.Provider p) { 9598 mProviders.remove(p.getComponentName()); 9599 if (DEBUG_SHOW_INFO) { 9600 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9601 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9602 Log.v(TAG, " Class=" + p.info.name); 9603 } 9604 final int NI = p.intents.size(); 9605 int j; 9606 for (j = 0; j < NI; j++) { 9607 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9608 if (DEBUG_SHOW_INFO) { 9609 Log.v(TAG, " IntentFilter:"); 9610 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9611 } 9612 removeFilter(intent); 9613 } 9614 } 9615 9616 @Override 9617 protected boolean allowFilterResult( 9618 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9619 ProviderInfo filterPi = filter.provider.info; 9620 for (int i = dest.size() - 1; i >= 0; i--) { 9621 ProviderInfo destPi = dest.get(i).providerInfo; 9622 if (destPi.name == filterPi.name 9623 && destPi.packageName == filterPi.packageName) { 9624 return false; 9625 } 9626 } 9627 return true; 9628 } 9629 9630 @Override 9631 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9632 return new PackageParser.ProviderIntentInfo[size]; 9633 } 9634 9635 @Override 9636 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9637 if (!sUserManager.exists(userId)) 9638 return true; 9639 PackageParser.Package p = filter.provider.owner; 9640 if (p != null) { 9641 PackageSetting ps = (PackageSetting) p.mExtras; 9642 if (ps != null) { 9643 // System apps are never considered stopped for purposes of 9644 // filtering, because there may be no way for the user to 9645 // actually re-launch them. 9646 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9647 && ps.getStopped(userId); 9648 } 9649 } 9650 return false; 9651 } 9652 9653 @Override 9654 protected boolean isPackageForFilter(String packageName, 9655 PackageParser.ProviderIntentInfo info) { 9656 return packageName.equals(info.provider.owner.packageName); 9657 } 9658 9659 @Override 9660 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9661 int match, int userId) { 9662 if (!sUserManager.exists(userId)) 9663 return null; 9664 final PackageParser.ProviderIntentInfo info = filter; 9665 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9666 return null; 9667 } 9668 final PackageParser.Provider provider = info.provider; 9669 if (mSafeMode && (provider.info.applicationInfo.flags 9670 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9671 return null; 9672 } 9673 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9674 if (ps == null) { 9675 return null; 9676 } 9677 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9678 ps.readUserState(userId), userId); 9679 if (pi == null) { 9680 return null; 9681 } 9682 final ResolveInfo res = new ResolveInfo(); 9683 res.providerInfo = pi; 9684 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9685 res.filter = filter; 9686 } 9687 res.priority = info.getPriority(); 9688 res.preferredOrder = provider.owner.mPreferredOrder; 9689 res.match = match; 9690 res.isDefault = info.hasDefault; 9691 res.labelRes = info.labelRes; 9692 res.nonLocalizedLabel = info.nonLocalizedLabel; 9693 res.icon = info.icon; 9694 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9695 return res; 9696 } 9697 9698 @Override 9699 protected void sortResults(List<ResolveInfo> results) { 9700 Collections.sort(results, mResolvePrioritySorter); 9701 } 9702 9703 @Override 9704 protected void dumpFilter(PrintWriter out, String prefix, 9705 PackageParser.ProviderIntentInfo filter) { 9706 out.print(prefix); 9707 out.print( 9708 Integer.toHexString(System.identityHashCode(filter.provider))); 9709 out.print(' '); 9710 filter.provider.printComponentShortName(out); 9711 out.print(" filter "); 9712 out.println(Integer.toHexString(System.identityHashCode(filter))); 9713 } 9714 9715 @Override 9716 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9717 return filter.provider; 9718 } 9719 9720 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9721 PackageParser.Provider provider = (PackageParser.Provider)label; 9722 out.print(prefix); out.print( 9723 Integer.toHexString(System.identityHashCode(provider))); 9724 out.print(' '); 9725 provider.printComponentShortName(out); 9726 if (count > 1) { 9727 out.print(" ("); out.print(count); out.print(" filters)"); 9728 } 9729 out.println(); 9730 } 9731 9732 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9733 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9734 private int mFlags; 9735 } 9736 9737 private static final class EphemeralIntentResolver 9738 extends IntentResolver<IntentFilter, ResolveInfo> { 9739 @Override 9740 protected IntentFilter[] newArray(int size) { 9741 return new IntentFilter[size]; 9742 } 9743 9744 @Override 9745 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9746 return true; 9747 } 9748 9749 @Override 9750 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9751 if (!sUserManager.exists(userId)) return null; 9752 final ResolveInfo res = new ResolveInfo(); 9753 res.filter = info; 9754 return res; 9755 } 9756 } 9757 9758 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9759 new Comparator<ResolveInfo>() { 9760 public int compare(ResolveInfo r1, ResolveInfo r2) { 9761 int v1 = r1.priority; 9762 int v2 = r2.priority; 9763 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9764 if (v1 != v2) { 9765 return (v1 > v2) ? -1 : 1; 9766 } 9767 v1 = r1.preferredOrder; 9768 v2 = r2.preferredOrder; 9769 if (v1 != v2) { 9770 return (v1 > v2) ? -1 : 1; 9771 } 9772 if (r1.isDefault != r2.isDefault) { 9773 return r1.isDefault ? -1 : 1; 9774 } 9775 v1 = r1.match; 9776 v2 = r2.match; 9777 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9778 if (v1 != v2) { 9779 return (v1 > v2) ? -1 : 1; 9780 } 9781 if (r1.system != r2.system) { 9782 return r1.system ? -1 : 1; 9783 } 9784 if (r1.activityInfo != null) { 9785 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9786 } 9787 if (r1.serviceInfo != null) { 9788 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9789 } 9790 if (r1.providerInfo != null) { 9791 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9792 } 9793 return 0; 9794 } 9795 }; 9796 9797 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9798 new Comparator<ProviderInfo>() { 9799 public int compare(ProviderInfo p1, ProviderInfo p2) { 9800 final int v1 = p1.initOrder; 9801 final int v2 = p2.initOrder; 9802 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9803 } 9804 }; 9805 9806 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9807 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9808 final int[] userIds) { 9809 mHandler.post(new Runnable() { 9810 @Override 9811 public void run() { 9812 try { 9813 final IActivityManager am = ActivityManagerNative.getDefault(); 9814 if (am == null) return; 9815 final int[] resolvedUserIds; 9816 if (userIds == null) { 9817 resolvedUserIds = am.getRunningUserIds(); 9818 } else { 9819 resolvedUserIds = userIds; 9820 } 9821 for (int id : resolvedUserIds) { 9822 final Intent intent = new Intent(action, 9823 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9824 if (extras != null) { 9825 intent.putExtras(extras); 9826 } 9827 if (targetPkg != null) { 9828 intent.setPackage(targetPkg); 9829 } 9830 // Modify the UID when posting to other users 9831 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9832 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9833 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9834 intent.putExtra(Intent.EXTRA_UID, uid); 9835 } 9836 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9837 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9838 if (DEBUG_BROADCASTS) { 9839 RuntimeException here = new RuntimeException("here"); 9840 here.fillInStackTrace(); 9841 Slog.d(TAG, "Sending to user " + id + ": " 9842 + intent.toShortString(false, true, false, false) 9843 + " " + intent.getExtras(), here); 9844 } 9845 am.broadcastIntent(null, intent, null, finishedReceiver, 9846 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9847 null, finishedReceiver != null, false, id); 9848 } 9849 } catch (RemoteException ex) { 9850 } 9851 } 9852 }); 9853 } 9854 9855 /** 9856 * Check if the external storage media is available. This is true if there 9857 * is a mounted external storage medium or if the external storage is 9858 * emulated. 9859 */ 9860 private boolean isExternalMediaAvailable() { 9861 return mMediaMounted || Environment.isExternalStorageEmulated(); 9862 } 9863 9864 @Override 9865 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9866 // writer 9867 synchronized (mPackages) { 9868 if (!isExternalMediaAvailable()) { 9869 // If the external storage is no longer mounted at this point, 9870 // the caller may not have been able to delete all of this 9871 // packages files and can not delete any more. Bail. 9872 return null; 9873 } 9874 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9875 if (lastPackage != null) { 9876 pkgs.remove(lastPackage); 9877 } 9878 if (pkgs.size() > 0) { 9879 return pkgs.get(0); 9880 } 9881 } 9882 return null; 9883 } 9884 9885 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9886 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9887 userId, andCode ? 1 : 0, packageName); 9888 if (mSystemReady) { 9889 msg.sendToTarget(); 9890 } else { 9891 if (mPostSystemReadyMessages == null) { 9892 mPostSystemReadyMessages = new ArrayList<>(); 9893 } 9894 mPostSystemReadyMessages.add(msg); 9895 } 9896 } 9897 9898 void startCleaningPackages() { 9899 // reader 9900 synchronized (mPackages) { 9901 if (!isExternalMediaAvailable()) { 9902 return; 9903 } 9904 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9905 return; 9906 } 9907 } 9908 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9909 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9910 IActivityManager am = ActivityManagerNative.getDefault(); 9911 if (am != null) { 9912 try { 9913 am.startService(null, intent, null, mContext.getOpPackageName(), 9914 UserHandle.USER_SYSTEM); 9915 } catch (RemoteException e) { 9916 } 9917 } 9918 } 9919 9920 @Override 9921 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9922 int installFlags, String installerPackageName, VerificationParams verificationParams, 9923 String packageAbiOverride) { 9924 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9925 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9926 } 9927 9928 @Override 9929 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9930 int installFlags, String installerPackageName, VerificationParams verificationParams, 9931 String packageAbiOverride, int userId) { 9932 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9933 9934 final int callingUid = Binder.getCallingUid(); 9935 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9936 9937 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9938 try { 9939 if (observer != null) { 9940 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9941 } 9942 } catch (RemoteException re) { 9943 } 9944 return; 9945 } 9946 9947 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9948 installFlags |= PackageManager.INSTALL_FROM_ADB; 9949 9950 } else { 9951 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9952 // about installerPackageName. 9953 9954 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9955 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9956 } 9957 9958 UserHandle user; 9959 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9960 user = UserHandle.ALL; 9961 } else { 9962 user = new UserHandle(userId); 9963 } 9964 9965 // Only system components can circumvent runtime permissions when installing. 9966 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9967 && mContext.checkCallingOrSelfPermission(Manifest.permission 9968 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9969 throw new SecurityException("You need the " 9970 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9971 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9972 } 9973 9974 verificationParams.setInstallerUid(callingUid); 9975 9976 final File originFile = new File(originPath); 9977 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9978 9979 final Message msg = mHandler.obtainMessage(INIT_COPY); 9980 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9981 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9982 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9983 msg.obj = params; 9984 9985 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9986 System.identityHashCode(msg.obj)); 9987 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9988 System.identityHashCode(msg.obj)); 9989 9990 mHandler.sendMessage(msg); 9991 } 9992 9993 void installStage(String packageName, File stagedDir, String stagedCid, 9994 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9995 String installerPackageName, int installerUid, UserHandle user) { 9996 if (DEBUG_EPHEMERAL) { 9997 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 9998 Slog.d(TAG, "Ephemeral install of " + packageName); 9999 } 10000 } 10001 final VerificationParams verifParams = new VerificationParams( 10002 null, sessionParams.originatingUri, sessionParams.referrerUri, 10003 sessionParams.originatingUid, null); 10004 verifParams.setInstallerUid(installerUid); 10005 10006 final OriginInfo origin; 10007 if (stagedDir != null) { 10008 origin = OriginInfo.fromStagedFile(stagedDir); 10009 } else { 10010 origin = OriginInfo.fromStagedContainer(stagedCid); 10011 } 10012 10013 final Message msg = mHandler.obtainMessage(INIT_COPY); 10014 final InstallParams params = new InstallParams(origin, null, observer, 10015 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10016 verifParams, user, sessionParams.abiOverride, 10017 sessionParams.grantedRuntimePermissions); 10018 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10019 msg.obj = params; 10020 10021 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10022 System.identityHashCode(msg.obj)); 10023 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10024 System.identityHashCode(msg.obj)); 10025 10026 mHandler.sendMessage(msg); 10027 } 10028 10029 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10030 Bundle extras = new Bundle(1); 10031 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10032 10033 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10034 packageName, extras, 0, null, null, new int[] {userId}); 10035 try { 10036 IActivityManager am = ActivityManagerNative.getDefault(); 10037 final boolean isSystem = 10038 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10039 if (isSystem && am.isUserRunning(userId, 0)) { 10040 // The just-installed/enabled app is bundled on the system, so presumed 10041 // to be able to run automatically without needing an explicit launch. 10042 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10043 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10044 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10045 .setPackage(packageName); 10046 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10047 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10048 } 10049 } catch (RemoteException e) { 10050 // shouldn't happen 10051 Slog.w(TAG, "Unable to bootstrap installed package", e); 10052 } 10053 } 10054 10055 @Override 10056 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10057 int userId) { 10058 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10059 PackageSetting pkgSetting; 10060 final int uid = Binder.getCallingUid(); 10061 enforceCrossUserPermission(uid, userId, true, true, 10062 "setApplicationHiddenSetting for user " + userId); 10063 10064 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10065 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10066 return false; 10067 } 10068 10069 long callingId = Binder.clearCallingIdentity(); 10070 try { 10071 boolean sendAdded = false; 10072 boolean sendRemoved = false; 10073 // writer 10074 synchronized (mPackages) { 10075 pkgSetting = mSettings.mPackages.get(packageName); 10076 if (pkgSetting == null) { 10077 return false; 10078 } 10079 if (pkgSetting.getHidden(userId) != hidden) { 10080 pkgSetting.setHidden(hidden, userId); 10081 mSettings.writePackageRestrictionsLPr(userId); 10082 if (hidden) { 10083 sendRemoved = true; 10084 } else { 10085 sendAdded = true; 10086 } 10087 } 10088 } 10089 if (sendAdded) { 10090 sendPackageAddedForUser(packageName, pkgSetting, userId); 10091 return true; 10092 } 10093 if (sendRemoved) { 10094 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10095 "hiding pkg"); 10096 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10097 return true; 10098 } 10099 } finally { 10100 Binder.restoreCallingIdentity(callingId); 10101 } 10102 return false; 10103 } 10104 10105 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10106 int userId) { 10107 final PackageRemovedInfo info = new PackageRemovedInfo(); 10108 info.removedPackage = packageName; 10109 info.removedUsers = new int[] {userId}; 10110 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10111 info.sendBroadcast(false, false, false); 10112 } 10113 10114 /** 10115 * Returns true if application is not found or there was an error. Otherwise it returns 10116 * the hidden state of the package for the given user. 10117 */ 10118 @Override 10119 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10121 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10122 false, "getApplicationHidden for user " + userId); 10123 PackageSetting pkgSetting; 10124 long callingId = Binder.clearCallingIdentity(); 10125 try { 10126 // writer 10127 synchronized (mPackages) { 10128 pkgSetting = mSettings.mPackages.get(packageName); 10129 if (pkgSetting == null) { 10130 return true; 10131 } 10132 return pkgSetting.getHidden(userId); 10133 } 10134 } finally { 10135 Binder.restoreCallingIdentity(callingId); 10136 } 10137 } 10138 10139 /** 10140 * @hide 10141 */ 10142 @Override 10143 public int installExistingPackageAsUser(String packageName, int userId) { 10144 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10145 null); 10146 PackageSetting pkgSetting; 10147 final int uid = Binder.getCallingUid(); 10148 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10149 + userId); 10150 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10151 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10152 } 10153 10154 long callingId = Binder.clearCallingIdentity(); 10155 try { 10156 boolean sendAdded = false; 10157 10158 // writer 10159 synchronized (mPackages) { 10160 pkgSetting = mSettings.mPackages.get(packageName); 10161 if (pkgSetting == null) { 10162 return PackageManager.INSTALL_FAILED_INVALID_URI; 10163 } 10164 if (!pkgSetting.getInstalled(userId)) { 10165 pkgSetting.setInstalled(true, userId); 10166 pkgSetting.setHidden(false, userId); 10167 mSettings.writePackageRestrictionsLPr(userId); 10168 sendAdded = true; 10169 } 10170 } 10171 10172 if (sendAdded) { 10173 sendPackageAddedForUser(packageName, pkgSetting, userId); 10174 } 10175 } finally { 10176 Binder.restoreCallingIdentity(callingId); 10177 } 10178 10179 return PackageManager.INSTALL_SUCCEEDED; 10180 } 10181 10182 boolean isUserRestricted(int userId, String restrictionKey) { 10183 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10184 if (restrictions.getBoolean(restrictionKey, false)) { 10185 Log.w(TAG, "User is restricted: " + restrictionKey); 10186 return true; 10187 } 10188 return false; 10189 } 10190 10191 @Override 10192 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10193 mContext.enforceCallingOrSelfPermission( 10194 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10195 "Only package verification agents can verify applications"); 10196 10197 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10198 final PackageVerificationResponse response = new PackageVerificationResponse( 10199 verificationCode, Binder.getCallingUid()); 10200 msg.arg1 = id; 10201 msg.obj = response; 10202 mHandler.sendMessage(msg); 10203 } 10204 10205 @Override 10206 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10207 long millisecondsToDelay) { 10208 mContext.enforceCallingOrSelfPermission( 10209 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10210 "Only package verification agents can extend verification timeouts"); 10211 10212 final PackageVerificationState state = mPendingVerification.get(id); 10213 final PackageVerificationResponse response = new PackageVerificationResponse( 10214 verificationCodeAtTimeout, Binder.getCallingUid()); 10215 10216 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10217 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10218 } 10219 if (millisecondsToDelay < 0) { 10220 millisecondsToDelay = 0; 10221 } 10222 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10223 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10224 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10225 } 10226 10227 if ((state != null) && !state.timeoutExtended()) { 10228 state.extendTimeout(); 10229 10230 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10231 msg.arg1 = id; 10232 msg.obj = response; 10233 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10234 } 10235 } 10236 10237 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10238 int verificationCode, UserHandle user) { 10239 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10240 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10241 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10242 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10243 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10244 10245 mContext.sendBroadcastAsUser(intent, user, 10246 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10247 } 10248 10249 private ComponentName matchComponentForVerifier(String packageName, 10250 List<ResolveInfo> receivers) { 10251 ActivityInfo targetReceiver = null; 10252 10253 final int NR = receivers.size(); 10254 for (int i = 0; i < NR; i++) { 10255 final ResolveInfo info = receivers.get(i); 10256 if (info.activityInfo == null) { 10257 continue; 10258 } 10259 10260 if (packageName.equals(info.activityInfo.packageName)) { 10261 targetReceiver = info.activityInfo; 10262 break; 10263 } 10264 } 10265 10266 if (targetReceiver == null) { 10267 return null; 10268 } 10269 10270 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10271 } 10272 10273 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10274 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10275 if (pkgInfo.verifiers.length == 0) { 10276 return null; 10277 } 10278 10279 final int N = pkgInfo.verifiers.length; 10280 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10281 for (int i = 0; i < N; i++) { 10282 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10283 10284 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10285 receivers); 10286 if (comp == null) { 10287 continue; 10288 } 10289 10290 final int verifierUid = getUidForVerifier(verifierInfo); 10291 if (verifierUid == -1) { 10292 continue; 10293 } 10294 10295 if (DEBUG_VERIFY) { 10296 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10297 + " with the correct signature"); 10298 } 10299 sufficientVerifiers.add(comp); 10300 verificationState.addSufficientVerifier(verifierUid); 10301 } 10302 10303 return sufficientVerifiers; 10304 } 10305 10306 private int getUidForVerifier(VerifierInfo verifierInfo) { 10307 synchronized (mPackages) { 10308 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10309 if (pkg == null) { 10310 return -1; 10311 } else if (pkg.mSignatures.length != 1) { 10312 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10313 + " has more than one signature; ignoring"); 10314 return -1; 10315 } 10316 10317 /* 10318 * If the public key of the package's signature does not match 10319 * our expected public key, then this is a different package and 10320 * we should skip. 10321 */ 10322 10323 final byte[] expectedPublicKey; 10324 try { 10325 final Signature verifierSig = pkg.mSignatures[0]; 10326 final PublicKey publicKey = verifierSig.getPublicKey(); 10327 expectedPublicKey = publicKey.getEncoded(); 10328 } catch (CertificateException e) { 10329 return -1; 10330 } 10331 10332 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10333 10334 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10335 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10336 + " does not have the expected public key; ignoring"); 10337 return -1; 10338 } 10339 10340 return pkg.applicationInfo.uid; 10341 } 10342 } 10343 10344 @Override 10345 public void finishPackageInstall(int token) { 10346 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10347 10348 if (DEBUG_INSTALL) { 10349 Slog.v(TAG, "BM finishing package install for " + token); 10350 } 10351 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10352 10353 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10354 mHandler.sendMessage(msg); 10355 } 10356 10357 /** 10358 * Get the verification agent timeout. 10359 * 10360 * @return verification timeout in milliseconds 10361 */ 10362 private long getVerificationTimeout() { 10363 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10364 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10365 DEFAULT_VERIFICATION_TIMEOUT); 10366 } 10367 10368 /** 10369 * Get the default verification agent response code. 10370 * 10371 * @return default verification response code 10372 */ 10373 private int getDefaultVerificationResponse() { 10374 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10375 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10376 DEFAULT_VERIFICATION_RESPONSE); 10377 } 10378 10379 /** 10380 * Check whether or not package verification has been enabled. 10381 * 10382 * @return true if verification should be performed 10383 */ 10384 private boolean isVerificationEnabled(int userId, int installFlags) { 10385 if (!DEFAULT_VERIFY_ENABLE) { 10386 return false; 10387 } 10388 // TODO: fix b/25118622; don't bypass verification 10389 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10390 return false; 10391 } 10392 // Ephemeral apps don't get the full verification treatment 10393 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10394 if (DEBUG_EPHEMERAL) { 10395 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10396 } 10397 return false; 10398 } 10399 10400 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10401 10402 // Check if installing from ADB 10403 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10404 // Do not run verification in a test harness environment 10405 if (ActivityManager.isRunningInTestHarness()) { 10406 return false; 10407 } 10408 if (ensureVerifyAppsEnabled) { 10409 return true; 10410 } 10411 // Check if the developer does not want package verification for ADB installs 10412 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10413 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10414 return false; 10415 } 10416 } 10417 10418 if (ensureVerifyAppsEnabled) { 10419 return true; 10420 } 10421 10422 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10423 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10424 } 10425 10426 @Override 10427 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10428 throws RemoteException { 10429 mContext.enforceCallingOrSelfPermission( 10430 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10431 "Only intentfilter verification agents can verify applications"); 10432 10433 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10434 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10435 Binder.getCallingUid(), verificationCode, failedDomains); 10436 msg.arg1 = id; 10437 msg.obj = response; 10438 mHandler.sendMessage(msg); 10439 } 10440 10441 @Override 10442 public int getIntentVerificationStatus(String packageName, int userId) { 10443 synchronized (mPackages) { 10444 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10445 } 10446 } 10447 10448 @Override 10449 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10450 mContext.enforceCallingOrSelfPermission( 10451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10452 10453 boolean result = false; 10454 synchronized (mPackages) { 10455 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10456 } 10457 if (result) { 10458 scheduleWritePackageRestrictionsLocked(userId); 10459 } 10460 return result; 10461 } 10462 10463 @Override 10464 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10465 synchronized (mPackages) { 10466 return mSettings.getIntentFilterVerificationsLPr(packageName); 10467 } 10468 } 10469 10470 @Override 10471 public List<IntentFilter> getAllIntentFilters(String packageName) { 10472 if (TextUtils.isEmpty(packageName)) { 10473 return Collections.<IntentFilter>emptyList(); 10474 } 10475 synchronized (mPackages) { 10476 PackageParser.Package pkg = mPackages.get(packageName); 10477 if (pkg == null || pkg.activities == null) { 10478 return Collections.<IntentFilter>emptyList(); 10479 } 10480 final int count = pkg.activities.size(); 10481 ArrayList<IntentFilter> result = new ArrayList<>(); 10482 for (int n=0; n<count; n++) { 10483 PackageParser.Activity activity = pkg.activities.get(n); 10484 if (activity.intents != null && activity.intents.size() > 0) { 10485 result.addAll(activity.intents); 10486 } 10487 } 10488 return result; 10489 } 10490 } 10491 10492 @Override 10493 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10494 mContext.enforceCallingOrSelfPermission( 10495 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10496 10497 synchronized (mPackages) { 10498 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10499 if (packageName != null) { 10500 result |= updateIntentVerificationStatus(packageName, 10501 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10502 userId); 10503 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10504 packageName, userId); 10505 } 10506 return result; 10507 } 10508 } 10509 10510 @Override 10511 public String getDefaultBrowserPackageName(int userId) { 10512 synchronized (mPackages) { 10513 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10514 } 10515 } 10516 10517 /** 10518 * Get the "allow unknown sources" setting. 10519 * 10520 * @return the current "allow unknown sources" setting 10521 */ 10522 private int getUnknownSourcesSettings() { 10523 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10524 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10525 -1); 10526 } 10527 10528 @Override 10529 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10530 final int uid = Binder.getCallingUid(); 10531 // writer 10532 synchronized (mPackages) { 10533 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10534 if (targetPackageSetting == null) { 10535 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10536 } 10537 10538 PackageSetting installerPackageSetting; 10539 if (installerPackageName != null) { 10540 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10541 if (installerPackageSetting == null) { 10542 throw new IllegalArgumentException("Unknown installer package: " 10543 + installerPackageName); 10544 } 10545 } else { 10546 installerPackageSetting = null; 10547 } 10548 10549 Signature[] callerSignature; 10550 Object obj = mSettings.getUserIdLPr(uid); 10551 if (obj != null) { 10552 if (obj instanceof SharedUserSetting) { 10553 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10554 } else if (obj instanceof PackageSetting) { 10555 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10556 } else { 10557 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10558 } 10559 } else { 10560 throw new SecurityException("Unknown calling uid " + uid); 10561 } 10562 10563 // Verify: can't set installerPackageName to a package that is 10564 // not signed with the same cert as the caller. 10565 if (installerPackageSetting != null) { 10566 if (compareSignatures(callerSignature, 10567 installerPackageSetting.signatures.mSignatures) 10568 != PackageManager.SIGNATURE_MATCH) { 10569 throw new SecurityException( 10570 "Caller does not have same cert as new installer package " 10571 + installerPackageName); 10572 } 10573 } 10574 10575 // Verify: if target already has an installer package, it must 10576 // be signed with the same cert as the caller. 10577 if (targetPackageSetting.installerPackageName != null) { 10578 PackageSetting setting = mSettings.mPackages.get( 10579 targetPackageSetting.installerPackageName); 10580 // If the currently set package isn't valid, then it's always 10581 // okay to change it. 10582 if (setting != null) { 10583 if (compareSignatures(callerSignature, 10584 setting.signatures.mSignatures) 10585 != PackageManager.SIGNATURE_MATCH) { 10586 throw new SecurityException( 10587 "Caller does not have same cert as old installer package " 10588 + targetPackageSetting.installerPackageName); 10589 } 10590 } 10591 } 10592 10593 // Okay! 10594 targetPackageSetting.installerPackageName = installerPackageName; 10595 scheduleWriteSettingsLocked(); 10596 } 10597 } 10598 10599 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10600 // Queue up an async operation since the package installation may take a little while. 10601 mHandler.post(new Runnable() { 10602 public void run() { 10603 mHandler.removeCallbacks(this); 10604 // Result object to be returned 10605 PackageInstalledInfo res = new PackageInstalledInfo(); 10606 res.returnCode = currentStatus; 10607 res.uid = -1; 10608 res.pkg = null; 10609 res.removedInfo = new PackageRemovedInfo(); 10610 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10611 args.doPreInstall(res.returnCode); 10612 synchronized (mInstallLock) { 10613 installPackageTracedLI(args, res); 10614 } 10615 args.doPostInstall(res.returnCode, res.uid); 10616 } 10617 10618 // A restore should be performed at this point if (a) the install 10619 // succeeded, (b) the operation is not an update, and (c) the new 10620 // package has not opted out of backup participation. 10621 final boolean update = res.removedInfo.removedPackage != null; 10622 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10623 boolean doRestore = !update 10624 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10625 10626 // Set up the post-install work request bookkeeping. This will be used 10627 // and cleaned up by the post-install event handling regardless of whether 10628 // there's a restore pass performed. Token values are >= 1. 10629 int token; 10630 if (mNextInstallToken < 0) mNextInstallToken = 1; 10631 token = mNextInstallToken++; 10632 10633 PostInstallData data = new PostInstallData(args, res); 10634 mRunningInstalls.put(token, data); 10635 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10636 10637 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10638 // Pass responsibility to the Backup Manager. It will perform a 10639 // restore if appropriate, then pass responsibility back to the 10640 // Package Manager to run the post-install observer callbacks 10641 // and broadcasts. 10642 IBackupManager bm = IBackupManager.Stub.asInterface( 10643 ServiceManager.getService(Context.BACKUP_SERVICE)); 10644 if (bm != null) { 10645 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10646 + " to BM for possible restore"); 10647 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10648 try { 10649 // TODO: http://b/22388012 10650 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10651 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10652 } else { 10653 doRestore = false; 10654 } 10655 } catch (RemoteException e) { 10656 // can't happen; the backup manager is local 10657 } catch (Exception e) { 10658 Slog.e(TAG, "Exception trying to enqueue restore", e); 10659 doRestore = false; 10660 } 10661 } else { 10662 Slog.e(TAG, "Backup Manager not found!"); 10663 doRestore = false; 10664 } 10665 } 10666 10667 if (!doRestore) { 10668 // No restore possible, or the Backup Manager was mysteriously not 10669 // available -- just fire the post-install work request directly. 10670 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10671 10672 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10673 10674 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10675 mHandler.sendMessage(msg); 10676 } 10677 } 10678 }); 10679 } 10680 10681 private abstract class HandlerParams { 10682 private static final int MAX_RETRIES = 4; 10683 10684 /** 10685 * Number of times startCopy() has been attempted and had a non-fatal 10686 * error. 10687 */ 10688 private int mRetries = 0; 10689 10690 /** User handle for the user requesting the information or installation. */ 10691 private final UserHandle mUser; 10692 String traceMethod; 10693 int traceCookie; 10694 10695 HandlerParams(UserHandle user) { 10696 mUser = user; 10697 } 10698 10699 UserHandle getUser() { 10700 return mUser; 10701 } 10702 10703 HandlerParams setTraceMethod(String traceMethod) { 10704 this.traceMethod = traceMethod; 10705 return this; 10706 } 10707 10708 HandlerParams setTraceCookie(int traceCookie) { 10709 this.traceCookie = traceCookie; 10710 return this; 10711 } 10712 10713 final boolean startCopy() { 10714 boolean res; 10715 try { 10716 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10717 10718 if (++mRetries > MAX_RETRIES) { 10719 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10720 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10721 handleServiceError(); 10722 return false; 10723 } else { 10724 handleStartCopy(); 10725 res = true; 10726 } 10727 } catch (RemoteException e) { 10728 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10729 mHandler.sendEmptyMessage(MCS_RECONNECT); 10730 res = false; 10731 } 10732 handleReturnCode(); 10733 return res; 10734 } 10735 10736 final void serviceError() { 10737 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10738 handleServiceError(); 10739 handleReturnCode(); 10740 } 10741 10742 abstract void handleStartCopy() throws RemoteException; 10743 abstract void handleServiceError(); 10744 abstract void handleReturnCode(); 10745 } 10746 10747 class MeasureParams extends HandlerParams { 10748 private final PackageStats mStats; 10749 private boolean mSuccess; 10750 10751 private final IPackageStatsObserver mObserver; 10752 10753 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10754 super(new UserHandle(stats.userHandle)); 10755 mObserver = observer; 10756 mStats = stats; 10757 } 10758 10759 @Override 10760 public String toString() { 10761 return "MeasureParams{" 10762 + Integer.toHexString(System.identityHashCode(this)) 10763 + " " + mStats.packageName + "}"; 10764 } 10765 10766 @Override 10767 void handleStartCopy() throws RemoteException { 10768 synchronized (mInstallLock) { 10769 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10770 } 10771 10772 if (mSuccess) { 10773 final boolean mounted; 10774 if (Environment.isExternalStorageEmulated()) { 10775 mounted = true; 10776 } else { 10777 final String status = Environment.getExternalStorageState(); 10778 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10779 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10780 } 10781 10782 if (mounted) { 10783 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10784 10785 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10786 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10787 10788 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10789 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10790 10791 // Always subtract cache size, since it's a subdirectory 10792 mStats.externalDataSize -= mStats.externalCacheSize; 10793 10794 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10795 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10796 10797 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10798 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10799 } 10800 } 10801 } 10802 10803 @Override 10804 void handleReturnCode() { 10805 if (mObserver != null) { 10806 try { 10807 mObserver.onGetStatsCompleted(mStats, mSuccess); 10808 } catch (RemoteException e) { 10809 Slog.i(TAG, "Observer no longer exists."); 10810 } 10811 } 10812 } 10813 10814 @Override 10815 void handleServiceError() { 10816 Slog.e(TAG, "Could not measure application " + mStats.packageName 10817 + " external storage"); 10818 } 10819 } 10820 10821 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10822 throws RemoteException { 10823 long result = 0; 10824 for (File path : paths) { 10825 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10826 } 10827 return result; 10828 } 10829 10830 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10831 for (File path : paths) { 10832 try { 10833 mcs.clearDirectory(path.getAbsolutePath()); 10834 } catch (RemoteException e) { 10835 } 10836 } 10837 } 10838 10839 static class OriginInfo { 10840 /** 10841 * Location where install is coming from, before it has been 10842 * copied/renamed into place. This could be a single monolithic APK 10843 * file, or a cluster directory. This location may be untrusted. 10844 */ 10845 final File file; 10846 final String cid; 10847 10848 /** 10849 * Flag indicating that {@link #file} or {@link #cid} has already been 10850 * staged, meaning downstream users don't need to defensively copy the 10851 * contents. 10852 */ 10853 final boolean staged; 10854 10855 /** 10856 * Flag indicating that {@link #file} or {@link #cid} is an already 10857 * installed app that is being moved. 10858 */ 10859 final boolean existing; 10860 10861 final String resolvedPath; 10862 final File resolvedFile; 10863 10864 static OriginInfo fromNothing() { 10865 return new OriginInfo(null, null, false, false); 10866 } 10867 10868 static OriginInfo fromUntrustedFile(File file) { 10869 return new OriginInfo(file, null, false, false); 10870 } 10871 10872 static OriginInfo fromExistingFile(File file) { 10873 return new OriginInfo(file, null, false, true); 10874 } 10875 10876 static OriginInfo fromStagedFile(File file) { 10877 return new OriginInfo(file, null, true, false); 10878 } 10879 10880 static OriginInfo fromStagedContainer(String cid) { 10881 return new OriginInfo(null, cid, true, false); 10882 } 10883 10884 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10885 this.file = file; 10886 this.cid = cid; 10887 this.staged = staged; 10888 this.existing = existing; 10889 10890 if (cid != null) { 10891 resolvedPath = PackageHelper.getSdDir(cid); 10892 resolvedFile = new File(resolvedPath); 10893 } else if (file != null) { 10894 resolvedPath = file.getAbsolutePath(); 10895 resolvedFile = file; 10896 } else { 10897 resolvedPath = null; 10898 resolvedFile = null; 10899 } 10900 } 10901 } 10902 10903 static class MoveInfo { 10904 final int moveId; 10905 final String fromUuid; 10906 final String toUuid; 10907 final String packageName; 10908 final String dataAppName; 10909 final int appId; 10910 final String seinfo; 10911 10912 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10913 String dataAppName, int appId, String seinfo) { 10914 this.moveId = moveId; 10915 this.fromUuid = fromUuid; 10916 this.toUuid = toUuid; 10917 this.packageName = packageName; 10918 this.dataAppName = dataAppName; 10919 this.appId = appId; 10920 this.seinfo = seinfo; 10921 } 10922 } 10923 10924 class InstallParams extends HandlerParams { 10925 final OriginInfo origin; 10926 final MoveInfo move; 10927 final IPackageInstallObserver2 observer; 10928 int installFlags; 10929 final String installerPackageName; 10930 final String volumeUuid; 10931 final VerificationParams verificationParams; 10932 private InstallArgs mArgs; 10933 private int mRet; 10934 final String packageAbiOverride; 10935 final String[] grantedRuntimePermissions; 10936 10937 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10938 int installFlags, String installerPackageName, String volumeUuid, 10939 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10940 String[] grantedPermissions) { 10941 super(user); 10942 this.origin = origin; 10943 this.move = move; 10944 this.observer = observer; 10945 this.installFlags = installFlags; 10946 this.installerPackageName = installerPackageName; 10947 this.volumeUuid = volumeUuid; 10948 this.verificationParams = verificationParams; 10949 this.packageAbiOverride = packageAbiOverride; 10950 this.grantedRuntimePermissions = grantedPermissions; 10951 } 10952 10953 @Override 10954 public String toString() { 10955 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10956 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10957 } 10958 10959 public ManifestDigest getManifestDigest() { 10960 if (verificationParams == null) { 10961 return null; 10962 } 10963 return verificationParams.getManifestDigest(); 10964 } 10965 10966 private int installLocationPolicy(PackageInfoLite pkgLite) { 10967 String packageName = pkgLite.packageName; 10968 int installLocation = pkgLite.installLocation; 10969 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10970 // reader 10971 synchronized (mPackages) { 10972 PackageParser.Package pkg = mPackages.get(packageName); 10973 if (pkg != null) { 10974 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10975 // Check for downgrading. 10976 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10977 try { 10978 checkDowngrade(pkg, pkgLite); 10979 } catch (PackageManagerException e) { 10980 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10981 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10982 } 10983 } 10984 // Check for updated system application. 10985 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10986 if (onSd) { 10987 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10988 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10989 } 10990 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10991 } else { 10992 if (onSd) { 10993 // Install flag overrides everything. 10994 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10995 } 10996 // If current upgrade specifies particular preference 10997 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10998 // Application explicitly specified internal. 10999 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11000 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11001 // App explictly prefers external. Let policy decide 11002 } else { 11003 // Prefer previous location 11004 if (isExternal(pkg)) { 11005 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11006 } 11007 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11008 } 11009 } 11010 } else { 11011 // Invalid install. Return error code 11012 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11013 } 11014 } 11015 } 11016 // All the special cases have been taken care of. 11017 // Return result based on recommended install location. 11018 if (onSd) { 11019 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11020 } 11021 return pkgLite.recommendedInstallLocation; 11022 } 11023 11024 /* 11025 * Invoke remote method to get package information and install 11026 * location values. Override install location based on default 11027 * policy if needed and then create install arguments based 11028 * on the install location. 11029 */ 11030 public void handleStartCopy() throws RemoteException { 11031 int ret = PackageManager.INSTALL_SUCCEEDED; 11032 11033 // If we're already staged, we've firmly committed to an install location 11034 if (origin.staged) { 11035 if (origin.file != null) { 11036 installFlags |= PackageManager.INSTALL_INTERNAL; 11037 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11038 } else if (origin.cid != null) { 11039 installFlags |= PackageManager.INSTALL_EXTERNAL; 11040 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11041 } else { 11042 throw new IllegalStateException("Invalid stage location"); 11043 } 11044 } 11045 11046 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11047 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11048 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11049 PackageInfoLite pkgLite = null; 11050 11051 if (onInt && onSd) { 11052 // Check if both bits are set. 11053 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11054 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11055 } else if (onSd && ephemeral) { 11056 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11057 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11058 } else { 11059 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11060 packageAbiOverride); 11061 11062 if (DEBUG_EPHEMERAL && ephemeral) { 11063 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11064 } 11065 11066 /* 11067 * If we have too little free space, try to free cache 11068 * before giving up. 11069 */ 11070 if (!origin.staged && pkgLite.recommendedInstallLocation 11071 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11072 // TODO: focus freeing disk space on the target device 11073 final StorageManager storage = StorageManager.from(mContext); 11074 final long lowThreshold = storage.getStorageLowBytes( 11075 Environment.getDataDirectory()); 11076 11077 final long sizeBytes = mContainerService.calculateInstalledSize( 11078 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11079 11080 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11081 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11082 installFlags, packageAbiOverride); 11083 } 11084 11085 /* 11086 * The cache free must have deleted the file we 11087 * downloaded to install. 11088 * 11089 * TODO: fix the "freeCache" call to not delete 11090 * the file we care about. 11091 */ 11092 if (pkgLite.recommendedInstallLocation 11093 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11094 pkgLite.recommendedInstallLocation 11095 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11096 } 11097 } 11098 } 11099 11100 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11101 int loc = pkgLite.recommendedInstallLocation; 11102 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11103 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11104 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11105 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11106 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11107 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11108 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11109 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11110 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11111 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11112 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11113 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11114 } else { 11115 // Override with defaults if needed. 11116 loc = installLocationPolicy(pkgLite); 11117 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11118 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11119 } else if (!onSd && !onInt) { 11120 // Override install location with flags 11121 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11122 // Set the flag to install on external media. 11123 installFlags |= PackageManager.INSTALL_EXTERNAL; 11124 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11125 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11126 if (DEBUG_EPHEMERAL) { 11127 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11128 } 11129 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11130 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11131 |PackageManager.INSTALL_INTERNAL); 11132 } else { 11133 // Make sure the flag for installing on external 11134 // media is unset 11135 installFlags |= PackageManager.INSTALL_INTERNAL; 11136 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11137 } 11138 } 11139 } 11140 } 11141 11142 final InstallArgs args = createInstallArgs(this); 11143 mArgs = args; 11144 11145 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11146 // TODO: http://b/22976637 11147 // Apps installed for "all" users use the device owner to verify the app 11148 UserHandle verifierUser = getUser(); 11149 if (verifierUser == UserHandle.ALL) { 11150 verifierUser = UserHandle.SYSTEM; 11151 } 11152 11153 /* 11154 * Determine if we have any installed package verifiers. If we 11155 * do, then we'll defer to them to verify the packages. 11156 */ 11157 final int requiredUid = mRequiredVerifierPackage == null ? -1 11158 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11159 if (!origin.existing && requiredUid != -1 11160 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11161 final Intent verification = new Intent( 11162 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11163 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11164 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11165 PACKAGE_MIME_TYPE); 11166 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11167 11168 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11169 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 11170 verifierUser.getIdentifier()); 11171 11172 if (DEBUG_VERIFY) { 11173 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11174 + verification.toString() + " with " + pkgLite.verifiers.length 11175 + " optional verifiers"); 11176 } 11177 11178 final int verificationId = mPendingVerificationToken++; 11179 11180 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11181 11182 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11183 installerPackageName); 11184 11185 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11186 installFlags); 11187 11188 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11189 pkgLite.packageName); 11190 11191 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11192 pkgLite.versionCode); 11193 11194 if (verificationParams != null) { 11195 if (verificationParams.getVerificationURI() != null) { 11196 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11197 verificationParams.getVerificationURI()); 11198 } 11199 if (verificationParams.getOriginatingURI() != null) { 11200 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11201 verificationParams.getOriginatingURI()); 11202 } 11203 if (verificationParams.getReferrer() != null) { 11204 verification.putExtra(Intent.EXTRA_REFERRER, 11205 verificationParams.getReferrer()); 11206 } 11207 if (verificationParams.getOriginatingUid() >= 0) { 11208 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11209 verificationParams.getOriginatingUid()); 11210 } 11211 if (verificationParams.getInstallerUid() >= 0) { 11212 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11213 verificationParams.getInstallerUid()); 11214 } 11215 } 11216 11217 final PackageVerificationState verificationState = new PackageVerificationState( 11218 requiredUid, args); 11219 11220 mPendingVerification.append(verificationId, verificationState); 11221 11222 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11223 receivers, verificationState); 11224 11225 /* 11226 * If any sufficient verifiers were listed in the package 11227 * manifest, attempt to ask them. 11228 */ 11229 if (sufficientVerifiers != null) { 11230 final int N = sufficientVerifiers.size(); 11231 if (N == 0) { 11232 Slog.i(TAG, "Additional verifiers required, but none installed."); 11233 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11234 } else { 11235 for (int i = 0; i < N; i++) { 11236 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11237 11238 final Intent sufficientIntent = new Intent(verification); 11239 sufficientIntent.setComponent(verifierComponent); 11240 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11241 } 11242 } 11243 } 11244 11245 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11246 mRequiredVerifierPackage, receivers); 11247 if (ret == PackageManager.INSTALL_SUCCEEDED 11248 && mRequiredVerifierPackage != null) { 11249 Trace.asyncTraceBegin( 11250 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11251 /* 11252 * Send the intent to the required verification agent, 11253 * but only start the verification timeout after the 11254 * target BroadcastReceivers have run. 11255 */ 11256 verification.setComponent(requiredVerifierComponent); 11257 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11258 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11259 new BroadcastReceiver() { 11260 @Override 11261 public void onReceive(Context context, Intent intent) { 11262 final Message msg = mHandler 11263 .obtainMessage(CHECK_PENDING_VERIFICATION); 11264 msg.arg1 = verificationId; 11265 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11266 } 11267 }, null, 0, null, null); 11268 11269 /* 11270 * We don't want the copy to proceed until verification 11271 * succeeds, so null out this field. 11272 */ 11273 mArgs = null; 11274 } 11275 } else { 11276 /* 11277 * No package verification is enabled, so immediately start 11278 * the remote call to initiate copy using temporary file. 11279 */ 11280 ret = args.copyApk(mContainerService, true); 11281 } 11282 } 11283 11284 mRet = ret; 11285 } 11286 11287 @Override 11288 void handleReturnCode() { 11289 // If mArgs is null, then MCS couldn't be reached. When it 11290 // reconnects, it will try again to install. At that point, this 11291 // will succeed. 11292 if (mArgs != null) { 11293 processPendingInstall(mArgs, mRet); 11294 } 11295 } 11296 11297 @Override 11298 void handleServiceError() { 11299 mArgs = createInstallArgs(this); 11300 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11301 } 11302 11303 public boolean isForwardLocked() { 11304 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11305 } 11306 } 11307 11308 /** 11309 * Used during creation of InstallArgs 11310 * 11311 * @param installFlags package installation flags 11312 * @return true if should be installed on external storage 11313 */ 11314 private static boolean installOnExternalAsec(int installFlags) { 11315 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11316 return false; 11317 } 11318 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11319 return true; 11320 } 11321 return false; 11322 } 11323 11324 /** 11325 * Used during creation of InstallArgs 11326 * 11327 * @param installFlags package installation flags 11328 * @return true if should be installed as forward locked 11329 */ 11330 private static boolean installForwardLocked(int installFlags) { 11331 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11332 } 11333 11334 private InstallArgs createInstallArgs(InstallParams params) { 11335 if (params.move != null) { 11336 return new MoveInstallArgs(params); 11337 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11338 return new AsecInstallArgs(params); 11339 } else { 11340 return new FileInstallArgs(params); 11341 } 11342 } 11343 11344 /** 11345 * Create args that describe an existing installed package. Typically used 11346 * when cleaning up old installs, or used as a move source. 11347 */ 11348 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11349 String resourcePath, String[] instructionSets) { 11350 final boolean isInAsec; 11351 if (installOnExternalAsec(installFlags)) { 11352 /* Apps on SD card are always in ASEC containers. */ 11353 isInAsec = true; 11354 } else if (installForwardLocked(installFlags) 11355 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11356 /* 11357 * Forward-locked apps are only in ASEC containers if they're the 11358 * new style 11359 */ 11360 isInAsec = true; 11361 } else { 11362 isInAsec = false; 11363 } 11364 11365 if (isInAsec) { 11366 return new AsecInstallArgs(codePath, instructionSets, 11367 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11368 } else { 11369 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11370 } 11371 } 11372 11373 static abstract class InstallArgs { 11374 /** @see InstallParams#origin */ 11375 final OriginInfo origin; 11376 /** @see InstallParams#move */ 11377 final MoveInfo move; 11378 11379 final IPackageInstallObserver2 observer; 11380 // Always refers to PackageManager flags only 11381 final int installFlags; 11382 final String installerPackageName; 11383 final String volumeUuid; 11384 final ManifestDigest manifestDigest; 11385 final UserHandle user; 11386 final String abiOverride; 11387 final String[] installGrantPermissions; 11388 /** If non-null, drop an async trace when the install completes */ 11389 final String traceMethod; 11390 final int traceCookie; 11391 11392 // The list of instruction sets supported by this app. This is currently 11393 // only used during the rmdex() phase to clean up resources. We can get rid of this 11394 // if we move dex files under the common app path. 11395 /* nullable */ String[] instructionSets; 11396 11397 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11398 int installFlags, String installerPackageName, String volumeUuid, 11399 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11400 String abiOverride, String[] installGrantPermissions, 11401 String traceMethod, int traceCookie) { 11402 this.origin = origin; 11403 this.move = move; 11404 this.installFlags = installFlags; 11405 this.observer = observer; 11406 this.installerPackageName = installerPackageName; 11407 this.volumeUuid = volumeUuid; 11408 this.manifestDigest = manifestDigest; 11409 this.user = user; 11410 this.instructionSets = instructionSets; 11411 this.abiOverride = abiOverride; 11412 this.installGrantPermissions = installGrantPermissions; 11413 this.traceMethod = traceMethod; 11414 this.traceCookie = traceCookie; 11415 } 11416 11417 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11418 abstract int doPreInstall(int status); 11419 11420 /** 11421 * Rename package into final resting place. All paths on the given 11422 * scanned package should be updated to reflect the rename. 11423 */ 11424 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11425 abstract int doPostInstall(int status, int uid); 11426 11427 /** @see PackageSettingBase#codePathString */ 11428 abstract String getCodePath(); 11429 /** @see PackageSettingBase#resourcePathString */ 11430 abstract String getResourcePath(); 11431 11432 // Need installer lock especially for dex file removal. 11433 abstract void cleanUpResourcesLI(); 11434 abstract boolean doPostDeleteLI(boolean delete); 11435 11436 /** 11437 * Called before the source arguments are copied. This is used mostly 11438 * for MoveParams when it needs to read the source file to put it in the 11439 * destination. 11440 */ 11441 int doPreCopy() { 11442 return PackageManager.INSTALL_SUCCEEDED; 11443 } 11444 11445 /** 11446 * Called after the source arguments are copied. This is used mostly for 11447 * MoveParams when it needs to read the source file to put it in the 11448 * destination. 11449 * 11450 * @return 11451 */ 11452 int doPostCopy(int uid) { 11453 return PackageManager.INSTALL_SUCCEEDED; 11454 } 11455 11456 protected boolean isFwdLocked() { 11457 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11458 } 11459 11460 protected boolean isExternalAsec() { 11461 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11462 } 11463 11464 protected boolean isEphemeral() { 11465 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11466 } 11467 11468 UserHandle getUser() { 11469 return user; 11470 } 11471 } 11472 11473 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11474 if (!allCodePaths.isEmpty()) { 11475 if (instructionSets == null) { 11476 throw new IllegalStateException("instructionSet == null"); 11477 } 11478 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11479 for (String codePath : allCodePaths) { 11480 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11481 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11482 if (retCode < 0) { 11483 Slog.w(TAG, "Couldn't remove dex file for package: " 11484 + " at location " + codePath + ", retcode=" + retCode); 11485 // we don't consider this to be a failure of the core package deletion 11486 } 11487 } 11488 } 11489 } 11490 } 11491 11492 /** 11493 * Logic to handle installation of non-ASEC applications, including copying 11494 * and renaming logic. 11495 */ 11496 class FileInstallArgs extends InstallArgs { 11497 private File codeFile; 11498 private File resourceFile; 11499 11500 // Example topology: 11501 // /data/app/com.example/base.apk 11502 // /data/app/com.example/split_foo.apk 11503 // /data/app/com.example/lib/arm/libfoo.so 11504 // /data/app/com.example/lib/arm64/libfoo.so 11505 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11506 11507 /** New install */ 11508 FileInstallArgs(InstallParams params) { 11509 super(params.origin, params.move, params.observer, params.installFlags, 11510 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11511 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11512 params.grantedRuntimePermissions, 11513 params.traceMethod, params.traceCookie); 11514 if (isFwdLocked()) { 11515 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11516 } 11517 } 11518 11519 /** Existing install */ 11520 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11521 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11522 null, null, null, 0); 11523 this.codeFile = (codePath != null) ? new File(codePath) : null; 11524 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11525 } 11526 11527 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11528 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11529 try { 11530 return doCopyApk(imcs, temp); 11531 } finally { 11532 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11533 } 11534 } 11535 11536 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11537 if (origin.staged) { 11538 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11539 codeFile = origin.file; 11540 resourceFile = origin.file; 11541 return PackageManager.INSTALL_SUCCEEDED; 11542 } 11543 11544 try { 11545 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11546 final File tempDir = 11547 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11548 codeFile = tempDir; 11549 resourceFile = tempDir; 11550 } catch (IOException e) { 11551 Slog.w(TAG, "Failed to create copy file: " + e); 11552 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11553 } 11554 11555 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11556 @Override 11557 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11558 if (!FileUtils.isValidExtFilename(name)) { 11559 throw new IllegalArgumentException("Invalid filename: " + name); 11560 } 11561 try { 11562 final File file = new File(codeFile, name); 11563 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11564 O_RDWR | O_CREAT, 0644); 11565 Os.chmod(file.getAbsolutePath(), 0644); 11566 return new ParcelFileDescriptor(fd); 11567 } catch (ErrnoException e) { 11568 throw new RemoteException("Failed to open: " + e.getMessage()); 11569 } 11570 } 11571 }; 11572 11573 int ret = PackageManager.INSTALL_SUCCEEDED; 11574 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11575 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11576 Slog.e(TAG, "Failed to copy package"); 11577 return ret; 11578 } 11579 11580 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11581 NativeLibraryHelper.Handle handle = null; 11582 try { 11583 handle = NativeLibraryHelper.Handle.create(codeFile); 11584 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11585 abiOverride); 11586 } catch (IOException e) { 11587 Slog.e(TAG, "Copying native libraries failed", e); 11588 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11589 } finally { 11590 IoUtils.closeQuietly(handle); 11591 } 11592 11593 return ret; 11594 } 11595 11596 int doPreInstall(int status) { 11597 if (status != PackageManager.INSTALL_SUCCEEDED) { 11598 cleanUp(); 11599 } 11600 return status; 11601 } 11602 11603 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11604 if (status != PackageManager.INSTALL_SUCCEEDED) { 11605 cleanUp(); 11606 return false; 11607 } 11608 11609 final File targetDir = codeFile.getParentFile(); 11610 final File beforeCodeFile = codeFile; 11611 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11612 11613 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11614 try { 11615 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11616 } catch (ErrnoException e) { 11617 Slog.w(TAG, "Failed to rename", e); 11618 return false; 11619 } 11620 11621 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11622 Slog.w(TAG, "Failed to restorecon"); 11623 return false; 11624 } 11625 11626 // Reflect the rename internally 11627 codeFile = afterCodeFile; 11628 resourceFile = afterCodeFile; 11629 11630 // Reflect the rename in scanned details 11631 pkg.codePath = afterCodeFile.getAbsolutePath(); 11632 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11633 pkg.baseCodePath); 11634 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11635 pkg.splitCodePaths); 11636 11637 // Reflect the rename in app info 11638 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11639 pkg.applicationInfo.setCodePath(pkg.codePath); 11640 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11641 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11642 pkg.applicationInfo.setResourcePath(pkg.codePath); 11643 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11644 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11645 11646 return true; 11647 } 11648 11649 int doPostInstall(int status, int uid) { 11650 if (status != PackageManager.INSTALL_SUCCEEDED) { 11651 cleanUp(); 11652 } 11653 return status; 11654 } 11655 11656 @Override 11657 String getCodePath() { 11658 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11659 } 11660 11661 @Override 11662 String getResourcePath() { 11663 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11664 } 11665 11666 private boolean cleanUp() { 11667 if (codeFile == null || !codeFile.exists()) { 11668 return false; 11669 } 11670 11671 if (codeFile.isDirectory()) { 11672 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11673 } else { 11674 codeFile.delete(); 11675 } 11676 11677 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11678 resourceFile.delete(); 11679 } 11680 11681 return true; 11682 } 11683 11684 void cleanUpResourcesLI() { 11685 // Try enumerating all code paths before deleting 11686 List<String> allCodePaths = Collections.EMPTY_LIST; 11687 if (codeFile != null && codeFile.exists()) { 11688 try { 11689 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11690 allCodePaths = pkg.getAllCodePaths(); 11691 } catch (PackageParserException e) { 11692 // Ignored; we tried our best 11693 } 11694 } 11695 11696 cleanUp(); 11697 removeDexFiles(allCodePaths, instructionSets); 11698 } 11699 11700 boolean doPostDeleteLI(boolean delete) { 11701 // XXX err, shouldn't we respect the delete flag? 11702 cleanUpResourcesLI(); 11703 return true; 11704 } 11705 } 11706 11707 private boolean isAsecExternal(String cid) { 11708 final String asecPath = PackageHelper.getSdFilesystem(cid); 11709 return !asecPath.startsWith(mAsecInternalPath); 11710 } 11711 11712 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11713 PackageManagerException { 11714 if (copyRet < 0) { 11715 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11716 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11717 throw new PackageManagerException(copyRet, message); 11718 } 11719 } 11720 } 11721 11722 /** 11723 * Extract the MountService "container ID" from the full code path of an 11724 * .apk. 11725 */ 11726 static String cidFromCodePath(String fullCodePath) { 11727 int eidx = fullCodePath.lastIndexOf("/"); 11728 String subStr1 = fullCodePath.substring(0, eidx); 11729 int sidx = subStr1.lastIndexOf("/"); 11730 return subStr1.substring(sidx+1, eidx); 11731 } 11732 11733 /** 11734 * Logic to handle installation of ASEC applications, including copying and 11735 * renaming logic. 11736 */ 11737 class AsecInstallArgs extends InstallArgs { 11738 static final String RES_FILE_NAME = "pkg.apk"; 11739 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11740 11741 String cid; 11742 String packagePath; 11743 String resourcePath; 11744 11745 /** New install */ 11746 AsecInstallArgs(InstallParams params) { 11747 super(params.origin, params.move, params.observer, params.installFlags, 11748 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11749 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11750 params.grantedRuntimePermissions, 11751 params.traceMethod, params.traceCookie); 11752 } 11753 11754 /** Existing install */ 11755 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11756 boolean isExternal, boolean isForwardLocked) { 11757 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11758 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11759 instructionSets, null, null, null, 0); 11760 // Hackily pretend we're still looking at a full code path 11761 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11762 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11763 } 11764 11765 // Extract cid from fullCodePath 11766 int eidx = fullCodePath.lastIndexOf("/"); 11767 String subStr1 = fullCodePath.substring(0, eidx); 11768 int sidx = subStr1.lastIndexOf("/"); 11769 cid = subStr1.substring(sidx+1, eidx); 11770 setMountPath(subStr1); 11771 } 11772 11773 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11774 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11775 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11776 instructionSets, null, null, null, 0); 11777 this.cid = cid; 11778 setMountPath(PackageHelper.getSdDir(cid)); 11779 } 11780 11781 void createCopyFile() { 11782 cid = mInstallerService.allocateExternalStageCidLegacy(); 11783 } 11784 11785 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11786 if (origin.staged && origin.cid != null) { 11787 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11788 cid = origin.cid; 11789 setMountPath(PackageHelper.getSdDir(cid)); 11790 return PackageManager.INSTALL_SUCCEEDED; 11791 } 11792 11793 if (temp) { 11794 createCopyFile(); 11795 } else { 11796 /* 11797 * Pre-emptively destroy the container since it's destroyed if 11798 * copying fails due to it existing anyway. 11799 */ 11800 PackageHelper.destroySdDir(cid); 11801 } 11802 11803 final String newMountPath = imcs.copyPackageToContainer( 11804 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11805 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11806 11807 if (newMountPath != null) { 11808 setMountPath(newMountPath); 11809 return PackageManager.INSTALL_SUCCEEDED; 11810 } else { 11811 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11812 } 11813 } 11814 11815 @Override 11816 String getCodePath() { 11817 return packagePath; 11818 } 11819 11820 @Override 11821 String getResourcePath() { 11822 return resourcePath; 11823 } 11824 11825 int doPreInstall(int status) { 11826 if (status != PackageManager.INSTALL_SUCCEEDED) { 11827 // Destroy container 11828 PackageHelper.destroySdDir(cid); 11829 } else { 11830 boolean mounted = PackageHelper.isContainerMounted(cid); 11831 if (!mounted) { 11832 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11833 Process.SYSTEM_UID); 11834 if (newMountPath != null) { 11835 setMountPath(newMountPath); 11836 } else { 11837 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11838 } 11839 } 11840 } 11841 return status; 11842 } 11843 11844 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11845 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11846 String newMountPath = null; 11847 if (PackageHelper.isContainerMounted(cid)) { 11848 // Unmount the container 11849 if (!PackageHelper.unMountSdDir(cid)) { 11850 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11851 return false; 11852 } 11853 } 11854 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11855 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11856 " which might be stale. Will try to clean up."); 11857 // Clean up the stale container and proceed to recreate. 11858 if (!PackageHelper.destroySdDir(newCacheId)) { 11859 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11860 return false; 11861 } 11862 // Successfully cleaned up stale container. Try to rename again. 11863 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11864 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11865 + " inspite of cleaning it up."); 11866 return false; 11867 } 11868 } 11869 if (!PackageHelper.isContainerMounted(newCacheId)) { 11870 Slog.w(TAG, "Mounting container " + newCacheId); 11871 newMountPath = PackageHelper.mountSdDir(newCacheId, 11872 getEncryptKey(), Process.SYSTEM_UID); 11873 } else { 11874 newMountPath = PackageHelper.getSdDir(newCacheId); 11875 } 11876 if (newMountPath == null) { 11877 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11878 return false; 11879 } 11880 Log.i(TAG, "Succesfully renamed " + cid + 11881 " to " + newCacheId + 11882 " at new path: " + newMountPath); 11883 cid = newCacheId; 11884 11885 final File beforeCodeFile = new File(packagePath); 11886 setMountPath(newMountPath); 11887 final File afterCodeFile = new File(packagePath); 11888 11889 // Reflect the rename in scanned details 11890 pkg.codePath = afterCodeFile.getAbsolutePath(); 11891 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11892 pkg.baseCodePath); 11893 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11894 pkg.splitCodePaths); 11895 11896 // Reflect the rename in app info 11897 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11898 pkg.applicationInfo.setCodePath(pkg.codePath); 11899 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11900 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11901 pkg.applicationInfo.setResourcePath(pkg.codePath); 11902 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11903 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11904 11905 return true; 11906 } 11907 11908 private void setMountPath(String mountPath) { 11909 final File mountFile = new File(mountPath); 11910 11911 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11912 if (monolithicFile.exists()) { 11913 packagePath = monolithicFile.getAbsolutePath(); 11914 if (isFwdLocked()) { 11915 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11916 } else { 11917 resourcePath = packagePath; 11918 } 11919 } else { 11920 packagePath = mountFile.getAbsolutePath(); 11921 resourcePath = packagePath; 11922 } 11923 } 11924 11925 int doPostInstall(int status, int uid) { 11926 if (status != PackageManager.INSTALL_SUCCEEDED) { 11927 cleanUp(); 11928 } else { 11929 final int groupOwner; 11930 final String protectedFile; 11931 if (isFwdLocked()) { 11932 groupOwner = UserHandle.getSharedAppGid(uid); 11933 protectedFile = RES_FILE_NAME; 11934 } else { 11935 groupOwner = -1; 11936 protectedFile = null; 11937 } 11938 11939 if (uid < Process.FIRST_APPLICATION_UID 11940 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11941 Slog.e(TAG, "Failed to finalize " + cid); 11942 PackageHelper.destroySdDir(cid); 11943 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11944 } 11945 11946 boolean mounted = PackageHelper.isContainerMounted(cid); 11947 if (!mounted) { 11948 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11949 } 11950 } 11951 return status; 11952 } 11953 11954 private void cleanUp() { 11955 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11956 11957 // Destroy secure container 11958 PackageHelper.destroySdDir(cid); 11959 } 11960 11961 private List<String> getAllCodePaths() { 11962 final File codeFile = new File(getCodePath()); 11963 if (codeFile != null && codeFile.exists()) { 11964 try { 11965 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11966 return pkg.getAllCodePaths(); 11967 } catch (PackageParserException e) { 11968 // Ignored; we tried our best 11969 } 11970 } 11971 return Collections.EMPTY_LIST; 11972 } 11973 11974 void cleanUpResourcesLI() { 11975 // Enumerate all code paths before deleting 11976 cleanUpResourcesLI(getAllCodePaths()); 11977 } 11978 11979 private void cleanUpResourcesLI(List<String> allCodePaths) { 11980 cleanUp(); 11981 removeDexFiles(allCodePaths, instructionSets); 11982 } 11983 11984 String getPackageName() { 11985 return getAsecPackageName(cid); 11986 } 11987 11988 boolean doPostDeleteLI(boolean delete) { 11989 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11990 final List<String> allCodePaths = getAllCodePaths(); 11991 boolean mounted = PackageHelper.isContainerMounted(cid); 11992 if (mounted) { 11993 // Unmount first 11994 if (PackageHelper.unMountSdDir(cid)) { 11995 mounted = false; 11996 } 11997 } 11998 if (!mounted && delete) { 11999 cleanUpResourcesLI(allCodePaths); 12000 } 12001 return !mounted; 12002 } 12003 12004 @Override 12005 int doPreCopy() { 12006 if (isFwdLocked()) { 12007 if (!PackageHelper.fixSdPermissions(cid, 12008 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 12009 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12010 } 12011 } 12012 12013 return PackageManager.INSTALL_SUCCEEDED; 12014 } 12015 12016 @Override 12017 int doPostCopy(int uid) { 12018 if (isFwdLocked()) { 12019 if (uid < Process.FIRST_APPLICATION_UID 12020 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12021 RES_FILE_NAME)) { 12022 Slog.e(TAG, "Failed to finalize " + cid); 12023 PackageHelper.destroySdDir(cid); 12024 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12025 } 12026 } 12027 12028 return PackageManager.INSTALL_SUCCEEDED; 12029 } 12030 } 12031 12032 /** 12033 * Logic to handle movement of existing installed applications. 12034 */ 12035 class MoveInstallArgs extends InstallArgs { 12036 private File codeFile; 12037 private File resourceFile; 12038 12039 /** New install */ 12040 MoveInstallArgs(InstallParams params) { 12041 super(params.origin, params.move, params.observer, params.installFlags, 12042 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 12043 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12044 params.grantedRuntimePermissions, 12045 params.traceMethod, params.traceCookie); 12046 } 12047 12048 int copyApk(IMediaContainerService imcs, boolean temp) { 12049 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12050 + move.fromUuid + " to " + move.toUuid); 12051 synchronized (mInstaller) { 12052 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12053 move.dataAppName, move.appId, move.seinfo) != 0) { 12054 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12055 } 12056 } 12057 12058 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12059 resourceFile = codeFile; 12060 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12061 12062 return PackageManager.INSTALL_SUCCEEDED; 12063 } 12064 12065 int doPreInstall(int status) { 12066 if (status != PackageManager.INSTALL_SUCCEEDED) { 12067 cleanUp(move.toUuid); 12068 } 12069 return status; 12070 } 12071 12072 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12073 if (status != PackageManager.INSTALL_SUCCEEDED) { 12074 cleanUp(move.toUuid); 12075 return false; 12076 } 12077 12078 // Reflect the move in app info 12079 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12080 pkg.applicationInfo.setCodePath(pkg.codePath); 12081 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12082 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12083 pkg.applicationInfo.setResourcePath(pkg.codePath); 12084 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12085 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12086 12087 return true; 12088 } 12089 12090 int doPostInstall(int status, int uid) { 12091 if (status == PackageManager.INSTALL_SUCCEEDED) { 12092 cleanUp(move.fromUuid); 12093 } else { 12094 cleanUp(move.toUuid); 12095 } 12096 return status; 12097 } 12098 12099 @Override 12100 String getCodePath() { 12101 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12102 } 12103 12104 @Override 12105 String getResourcePath() { 12106 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12107 } 12108 12109 private boolean cleanUp(String volumeUuid) { 12110 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12111 move.dataAppName); 12112 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12113 synchronized (mInstallLock) { 12114 // Clean up both app data and code 12115 removeDataDirsLI(volumeUuid, move.packageName); 12116 if (codeFile.isDirectory()) { 12117 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12118 } else { 12119 codeFile.delete(); 12120 } 12121 } 12122 return true; 12123 } 12124 12125 void cleanUpResourcesLI() { 12126 throw new UnsupportedOperationException(); 12127 } 12128 12129 boolean doPostDeleteLI(boolean delete) { 12130 throw new UnsupportedOperationException(); 12131 } 12132 } 12133 12134 static String getAsecPackageName(String packageCid) { 12135 int idx = packageCid.lastIndexOf("-"); 12136 if (idx == -1) { 12137 return packageCid; 12138 } 12139 return packageCid.substring(0, idx); 12140 } 12141 12142 // Utility method used to create code paths based on package name and available index. 12143 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12144 String idxStr = ""; 12145 int idx = 1; 12146 // Fall back to default value of idx=1 if prefix is not 12147 // part of oldCodePath 12148 if (oldCodePath != null) { 12149 String subStr = oldCodePath; 12150 // Drop the suffix right away 12151 if (suffix != null && subStr.endsWith(suffix)) { 12152 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12153 } 12154 // If oldCodePath already contains prefix find out the 12155 // ending index to either increment or decrement. 12156 int sidx = subStr.lastIndexOf(prefix); 12157 if (sidx != -1) { 12158 subStr = subStr.substring(sidx + prefix.length()); 12159 if (subStr != null) { 12160 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12161 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12162 } 12163 try { 12164 idx = Integer.parseInt(subStr); 12165 if (idx <= 1) { 12166 idx++; 12167 } else { 12168 idx--; 12169 } 12170 } catch(NumberFormatException e) { 12171 } 12172 } 12173 } 12174 } 12175 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12176 return prefix + idxStr; 12177 } 12178 12179 private File getNextCodePath(File targetDir, String packageName) { 12180 int suffix = 1; 12181 File result; 12182 do { 12183 result = new File(targetDir, packageName + "-" + suffix); 12184 suffix++; 12185 } while (result.exists()); 12186 return result; 12187 } 12188 12189 // Utility method that returns the relative package path with respect 12190 // to the installation directory. Like say for /data/data/com.test-1.apk 12191 // string com.test-1 is returned. 12192 static String deriveCodePathName(String codePath) { 12193 if (codePath == null) { 12194 return null; 12195 } 12196 final File codeFile = new File(codePath); 12197 final String name = codeFile.getName(); 12198 if (codeFile.isDirectory()) { 12199 return name; 12200 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12201 final int lastDot = name.lastIndexOf('.'); 12202 return name.substring(0, lastDot); 12203 } else { 12204 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12205 return null; 12206 } 12207 } 12208 12209 static class PackageInstalledInfo { 12210 String name; 12211 int uid; 12212 // The set of users that originally had this package installed. 12213 int[] origUsers; 12214 // The set of users that now have this package installed. 12215 int[] newUsers; 12216 PackageParser.Package pkg; 12217 int returnCode; 12218 String returnMsg; 12219 PackageRemovedInfo removedInfo; 12220 12221 public void setError(int code, String msg) { 12222 returnCode = code; 12223 returnMsg = msg; 12224 Slog.w(TAG, msg); 12225 } 12226 12227 public void setError(String msg, PackageParserException e) { 12228 returnCode = e.error; 12229 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12230 Slog.w(TAG, msg, e); 12231 } 12232 12233 public void setError(String msg, PackageManagerException e) { 12234 returnCode = e.error; 12235 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12236 Slog.w(TAG, msg, e); 12237 } 12238 12239 // In some error cases we want to convey more info back to the observer 12240 String origPackage; 12241 String origPermission; 12242 } 12243 12244 /* 12245 * Install a non-existing package. 12246 */ 12247 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12248 UserHandle user, String installerPackageName, String volumeUuid, 12249 PackageInstalledInfo res) { 12250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12251 12252 // Remember this for later, in case we need to rollback this install 12253 String pkgName = pkg.packageName; 12254 12255 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12256 // TODO: b/23350563 12257 final boolean dataDirExists = Environment 12258 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12259 12260 synchronized(mPackages) { 12261 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12262 // A package with the same name is already installed, though 12263 // it has been renamed to an older name. The package we 12264 // are trying to install should be installed as an update to 12265 // the existing one, but that has not been requested, so bail. 12266 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12267 + " without first uninstalling package running as " 12268 + mSettings.mRenamedPackages.get(pkgName)); 12269 return; 12270 } 12271 if (mPackages.containsKey(pkgName)) { 12272 // Don't allow installation over an existing package with the same name. 12273 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12274 + " without first uninstalling."); 12275 return; 12276 } 12277 } 12278 12279 try { 12280 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12281 System.currentTimeMillis(), user); 12282 12283 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12284 // delete the partially installed application. the data directory will have to be 12285 // restored if it was already existing 12286 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12287 // remove package from internal structures. Note that we want deletePackageX to 12288 // delete the package data and cache directories that it created in 12289 // scanPackageLocked, unless those directories existed before we even tried to 12290 // install. 12291 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12292 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12293 res.removedInfo, true); 12294 } 12295 12296 } catch (PackageManagerException e) { 12297 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12298 } 12299 12300 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12301 } 12302 12303 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12304 // Can't rotate keys during boot or if sharedUser. 12305 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12306 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12307 return false; 12308 } 12309 // app is using upgradeKeySets; make sure all are valid 12310 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12311 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12312 for (int i = 0; i < upgradeKeySets.length; i++) { 12313 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12314 Slog.wtf(TAG, "Package " 12315 + (oldPs.name != null ? oldPs.name : "<null>") 12316 + " contains upgrade-key-set reference to unknown key-set: " 12317 + upgradeKeySets[i] 12318 + " reverting to signatures check."); 12319 return false; 12320 } 12321 } 12322 return true; 12323 } 12324 12325 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12326 // Upgrade keysets are being used. Determine if new package has a superset of the 12327 // required keys. 12328 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12329 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12330 for (int i = 0; i < upgradeKeySets.length; i++) { 12331 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12332 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12333 return true; 12334 } 12335 } 12336 return false; 12337 } 12338 12339 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12340 UserHandle user, String installerPackageName, String volumeUuid, 12341 PackageInstalledInfo res) { 12342 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12343 12344 final PackageParser.Package oldPackage; 12345 final String pkgName = pkg.packageName; 12346 final int[] allUsers; 12347 final boolean[] perUserInstalled; 12348 12349 // First find the old package info and check signatures 12350 synchronized(mPackages) { 12351 oldPackage = mPackages.get(pkgName); 12352 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12353 if (isEphemeral && !oldIsEphemeral) { 12354 // can't downgrade from full to ephemeral 12355 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12356 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12357 return; 12358 } 12359 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12360 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12361 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12362 if(!checkUpgradeKeySetLP(ps, pkg)) { 12363 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12364 "New package not signed by keys specified by upgrade-keysets: " 12365 + pkgName); 12366 return; 12367 } 12368 } else { 12369 // default to original signature matching 12370 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12371 != PackageManager.SIGNATURE_MATCH) { 12372 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12373 "New package has a different signature: " + pkgName); 12374 return; 12375 } 12376 } 12377 12378 // In case of rollback, remember per-user/profile install state 12379 allUsers = sUserManager.getUserIds(); 12380 perUserInstalled = new boolean[allUsers.length]; 12381 for (int i = 0; i < allUsers.length; i++) { 12382 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12383 } 12384 } 12385 12386 boolean sysPkg = (isSystemApp(oldPackage)); 12387 if (sysPkg) { 12388 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12389 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12390 } else { 12391 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12392 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12393 } 12394 } 12395 12396 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12397 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12398 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12399 String volumeUuid, PackageInstalledInfo res) { 12400 String pkgName = deletedPackage.packageName; 12401 boolean deletedPkg = true; 12402 boolean updatedSettings = false; 12403 12404 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12405 + deletedPackage); 12406 long origUpdateTime; 12407 if (pkg.mExtras != null) { 12408 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12409 } else { 12410 origUpdateTime = 0; 12411 } 12412 12413 // First delete the existing package while retaining the data directory 12414 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12415 res.removedInfo, true)) { 12416 // If the existing package wasn't successfully deleted 12417 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12418 deletedPkg = false; 12419 } else { 12420 // Successfully deleted the old package; proceed with replace. 12421 12422 // If deleted package lived in a container, give users a chance to 12423 // relinquish resources before killing. 12424 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12425 if (DEBUG_INSTALL) { 12426 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12427 } 12428 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12429 final ArrayList<String> pkgList = new ArrayList<String>(1); 12430 pkgList.add(deletedPackage.applicationInfo.packageName); 12431 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12432 } 12433 12434 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12435 try { 12436 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12437 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12438 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12439 perUserInstalled, res, user); 12440 updatedSettings = true; 12441 } catch (PackageManagerException e) { 12442 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12443 } 12444 } 12445 12446 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12447 // remove package from internal structures. Note that we want deletePackageX to 12448 // delete the package data and cache directories that it created in 12449 // scanPackageLocked, unless those directories existed before we even tried to 12450 // install. 12451 if(updatedSettings) { 12452 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12453 deletePackageLI( 12454 pkgName, null, true, allUsers, perUserInstalled, 12455 PackageManager.DELETE_KEEP_DATA, 12456 res.removedInfo, true); 12457 } 12458 // Since we failed to install the new package we need to restore the old 12459 // package that we deleted. 12460 if (deletedPkg) { 12461 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12462 File restoreFile = new File(deletedPackage.codePath); 12463 // Parse old package 12464 boolean oldExternal = isExternal(deletedPackage); 12465 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12466 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12467 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12468 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12469 try { 12470 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12471 null); 12472 } catch (PackageManagerException e) { 12473 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12474 + e.getMessage()); 12475 return; 12476 } 12477 // Restore of old package succeeded. Update permissions. 12478 // writer 12479 synchronized (mPackages) { 12480 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12481 UPDATE_PERMISSIONS_ALL); 12482 // can downgrade to reader 12483 mSettings.writeLPr(); 12484 } 12485 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12486 } 12487 } 12488 } 12489 12490 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12491 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12492 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12493 String volumeUuid, PackageInstalledInfo res) { 12494 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12495 + ", old=" + deletedPackage); 12496 boolean disabledSystem = false; 12497 boolean updatedSettings = false; 12498 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12499 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12500 != 0) { 12501 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12502 } 12503 String packageName = deletedPackage.packageName; 12504 if (packageName == null) { 12505 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12506 "Attempt to delete null packageName."); 12507 return; 12508 } 12509 PackageParser.Package oldPkg; 12510 PackageSetting oldPkgSetting; 12511 // reader 12512 synchronized (mPackages) { 12513 oldPkg = mPackages.get(packageName); 12514 oldPkgSetting = mSettings.mPackages.get(packageName); 12515 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12516 (oldPkgSetting == null)) { 12517 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12518 "Couldn't find package:" + packageName + " information"); 12519 return; 12520 } 12521 } 12522 12523 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12524 12525 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12526 res.removedInfo.removedPackage = packageName; 12527 // Remove existing system package 12528 removePackageLI(oldPkgSetting, true); 12529 // writer 12530 synchronized (mPackages) { 12531 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12532 if (!disabledSystem && deletedPackage != null) { 12533 // We didn't need to disable the .apk as a current system package, 12534 // which means we are replacing another update that is already 12535 // installed. We need to make sure to delete the older one's .apk. 12536 res.removedInfo.args = createInstallArgsForExisting(0, 12537 deletedPackage.applicationInfo.getCodePath(), 12538 deletedPackage.applicationInfo.getResourcePath(), 12539 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12540 } else { 12541 res.removedInfo.args = null; 12542 } 12543 } 12544 12545 // Successfully disabled the old package. Now proceed with re-installation 12546 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12547 12548 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12549 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12550 12551 PackageParser.Package newPackage = null; 12552 try { 12553 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12554 if (newPackage.mExtras != null) { 12555 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12556 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12557 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12558 12559 // is the update attempting to change shared user? that isn't going to work... 12560 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12561 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12562 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12563 + " to " + newPkgSetting.sharedUser); 12564 updatedSettings = true; 12565 } 12566 } 12567 12568 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12569 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12570 perUserInstalled, res, user); 12571 updatedSettings = true; 12572 } 12573 12574 } catch (PackageManagerException e) { 12575 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12576 } 12577 12578 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12579 // Re installation failed. Restore old information 12580 // Remove new pkg information 12581 if (newPackage != null) { 12582 removeInstalledPackageLI(newPackage, true); 12583 } 12584 // Add back the old system package 12585 try { 12586 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12587 } catch (PackageManagerException e) { 12588 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12589 } 12590 // Restore the old system information in Settings 12591 synchronized (mPackages) { 12592 if (disabledSystem) { 12593 mSettings.enableSystemPackageLPw(packageName); 12594 } 12595 if (updatedSettings) { 12596 mSettings.setInstallerPackageName(packageName, 12597 oldPkgSetting.installerPackageName); 12598 } 12599 mSettings.writeLPr(); 12600 } 12601 } 12602 } 12603 12604 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12605 // Collect all used permissions in the UID 12606 ArraySet<String> usedPermissions = new ArraySet<>(); 12607 final int packageCount = su.packages.size(); 12608 for (int i = 0; i < packageCount; i++) { 12609 PackageSetting ps = su.packages.valueAt(i); 12610 if (ps.pkg == null) { 12611 continue; 12612 } 12613 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12614 for (int j = 0; j < requestedPermCount; j++) { 12615 String permission = ps.pkg.requestedPermissions.get(j); 12616 BasePermission bp = mSettings.mPermissions.get(permission); 12617 if (bp != null) { 12618 usedPermissions.add(permission); 12619 } 12620 } 12621 } 12622 12623 PermissionsState permissionsState = su.getPermissionsState(); 12624 // Prune install permissions 12625 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12626 final int installPermCount = installPermStates.size(); 12627 for (int i = installPermCount - 1; i >= 0; i--) { 12628 PermissionState permissionState = installPermStates.get(i); 12629 if (!usedPermissions.contains(permissionState.getName())) { 12630 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12631 if (bp != null) { 12632 permissionsState.revokeInstallPermission(bp); 12633 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12634 PackageManager.MASK_PERMISSION_FLAGS, 0); 12635 } 12636 } 12637 } 12638 12639 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12640 12641 // Prune runtime permissions 12642 for (int userId : allUserIds) { 12643 List<PermissionState> runtimePermStates = permissionsState 12644 .getRuntimePermissionStates(userId); 12645 final int runtimePermCount = runtimePermStates.size(); 12646 for (int i = runtimePermCount - 1; i >= 0; i--) { 12647 PermissionState permissionState = runtimePermStates.get(i); 12648 if (!usedPermissions.contains(permissionState.getName())) { 12649 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12650 if (bp != null) { 12651 permissionsState.revokeRuntimePermission(bp, userId); 12652 permissionsState.updatePermissionFlags(bp, userId, 12653 PackageManager.MASK_PERMISSION_FLAGS, 0); 12654 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12655 runtimePermissionChangedUserIds, userId); 12656 } 12657 } 12658 } 12659 } 12660 12661 return runtimePermissionChangedUserIds; 12662 } 12663 12664 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12665 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12666 UserHandle user) { 12667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12668 12669 String pkgName = newPackage.packageName; 12670 synchronized (mPackages) { 12671 //write settings. the installStatus will be incomplete at this stage. 12672 //note that the new package setting would have already been 12673 //added to mPackages. It hasn't been persisted yet. 12674 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12675 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12676 mSettings.writeLPr(); 12677 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12678 } 12679 12680 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12681 synchronized (mPackages) { 12682 updatePermissionsLPw(newPackage.packageName, newPackage, 12683 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12684 ? UPDATE_PERMISSIONS_ALL : 0)); 12685 // For system-bundled packages, we assume that installing an upgraded version 12686 // of the package implies that the user actually wants to run that new code, 12687 // so we enable the package. 12688 PackageSetting ps = mSettings.mPackages.get(pkgName); 12689 if (ps != null) { 12690 if (isSystemApp(newPackage)) { 12691 // NB: implicit assumption that system package upgrades apply to all users 12692 if (DEBUG_INSTALL) { 12693 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12694 } 12695 if (res.origUsers != null) { 12696 for (int userHandle : res.origUsers) { 12697 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12698 userHandle, installerPackageName); 12699 } 12700 } 12701 // Also convey the prior install/uninstall state 12702 if (allUsers != null && perUserInstalled != null) { 12703 for (int i = 0; i < allUsers.length; i++) { 12704 if (DEBUG_INSTALL) { 12705 Slog.d(TAG, " user " + allUsers[i] 12706 + " => " + perUserInstalled[i]); 12707 } 12708 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12709 } 12710 // these install state changes will be persisted in the 12711 // upcoming call to mSettings.writeLPr(). 12712 } 12713 } 12714 // It's implied that when a user requests installation, they want the app to be 12715 // installed and enabled. 12716 int userId = user.getIdentifier(); 12717 if (userId != UserHandle.USER_ALL) { 12718 ps.setInstalled(true, userId); 12719 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12720 } 12721 } 12722 res.name = pkgName; 12723 res.uid = newPackage.applicationInfo.uid; 12724 res.pkg = newPackage; 12725 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12726 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12727 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12728 //to update install status 12729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12730 mSettings.writeLPr(); 12731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12732 } 12733 12734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12735 } 12736 12737 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12738 try { 12739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12740 installPackageLI(args, res); 12741 } finally { 12742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12743 } 12744 } 12745 12746 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12747 final int installFlags = args.installFlags; 12748 final String installerPackageName = args.installerPackageName; 12749 final String volumeUuid = args.volumeUuid; 12750 final File tmpPackageFile = new File(args.getCodePath()); 12751 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12752 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12753 || (args.volumeUuid != null)); 12754 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12755 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12756 boolean replace = false; 12757 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12758 if (args.move != null) { 12759 // moving a complete application; perfom an initial scan on the new install location 12760 scanFlags |= SCAN_INITIAL; 12761 } 12762 // Result object to be returned 12763 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12764 12765 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12766 12767 // Sanity check 12768 if (ephemeral && (forwardLocked || onExternal)) { 12769 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12770 + " external=" + onExternal); 12771 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12772 return; 12773 } 12774 12775 // Retrieve PackageSettings and parse package 12776 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12777 | PackageParser.PARSE_ENFORCE_CODE 12778 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12779 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12780 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0) 12781 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12782 PackageParser pp = new PackageParser(); 12783 pp.setSeparateProcesses(mSeparateProcesses); 12784 pp.setDisplayMetrics(mMetrics); 12785 12786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12787 final PackageParser.Package pkg; 12788 try { 12789 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12790 } catch (PackageParserException e) { 12791 res.setError("Failed parse during installPackageLI", e); 12792 return; 12793 } finally { 12794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12795 } 12796 12797 // Mark that we have an install time CPU ABI override. 12798 pkg.cpuAbiOverride = args.abiOverride; 12799 12800 String pkgName = res.name = pkg.packageName; 12801 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12802 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12803 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12804 return; 12805 } 12806 } 12807 12808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12809 try { 12810 pp.collectCertificates(pkg, parseFlags); 12811 } catch (PackageParserException e) { 12812 res.setError("Failed collect during installPackageLI", e); 12813 return; 12814 } finally { 12815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12816 } 12817 12818 /* If the installer passed in a manifest digest, compare it now. */ 12819 if (args.manifestDigest != null) { 12820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12821 try { 12822 pp.collectManifestDigest(pkg); 12823 } catch (PackageParserException e) { 12824 res.setError("Failed collect during installPackageLI", e); 12825 return; 12826 } finally { 12827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12828 } 12829 12830 if (DEBUG_INSTALL) { 12831 final String parsedManifest = pkg.manifestDigest == null ? "null" 12832 : pkg.manifestDigest.toString(); 12833 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12834 + parsedManifest); 12835 } 12836 12837 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12838 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12839 return; 12840 } 12841 } else if (DEBUG_INSTALL) { 12842 final String parsedManifest = pkg.manifestDigest == null 12843 ? "null" : pkg.manifestDigest.toString(); 12844 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12845 } 12846 12847 // Get rid of all references to package scan path via parser. 12848 pp = null; 12849 String oldCodePath = null; 12850 boolean systemApp = false; 12851 synchronized (mPackages) { 12852 // Check if installing already existing package 12853 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12854 String oldName = mSettings.mRenamedPackages.get(pkgName); 12855 if (pkg.mOriginalPackages != null 12856 && pkg.mOriginalPackages.contains(oldName) 12857 && mPackages.containsKey(oldName)) { 12858 // This package is derived from an original package, 12859 // and this device has been updating from that original 12860 // name. We must continue using the original name, so 12861 // rename the new package here. 12862 pkg.setPackageName(oldName); 12863 pkgName = pkg.packageName; 12864 replace = true; 12865 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12866 + oldName + " pkgName=" + pkgName); 12867 } else if (mPackages.containsKey(pkgName)) { 12868 // This package, under its official name, already exists 12869 // on the device; we should replace it. 12870 replace = true; 12871 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12872 } 12873 12874 // Prevent apps opting out from runtime permissions 12875 if (replace) { 12876 PackageParser.Package oldPackage = mPackages.get(pkgName); 12877 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12878 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12879 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12880 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12881 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12882 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12883 + " doesn't support runtime permissions but the old" 12884 + " target SDK " + oldTargetSdk + " does."); 12885 return; 12886 } 12887 } 12888 } 12889 12890 PackageSetting ps = mSettings.mPackages.get(pkgName); 12891 if (ps != null) { 12892 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12893 12894 // Quick sanity check that we're signed correctly if updating; 12895 // we'll check this again later when scanning, but we want to 12896 // bail early here before tripping over redefined permissions. 12897 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12898 if (!checkUpgradeKeySetLP(ps, pkg)) { 12899 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12900 + pkg.packageName + " upgrade keys do not match the " 12901 + "previously installed version"); 12902 return; 12903 } 12904 } else { 12905 try { 12906 verifySignaturesLP(ps, pkg); 12907 } catch (PackageManagerException e) { 12908 res.setError(e.error, e.getMessage()); 12909 return; 12910 } 12911 } 12912 12913 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12914 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12915 systemApp = (ps.pkg.applicationInfo.flags & 12916 ApplicationInfo.FLAG_SYSTEM) != 0; 12917 } 12918 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12919 } 12920 12921 // Check whether the newly-scanned package wants to define an already-defined perm 12922 int N = pkg.permissions.size(); 12923 for (int i = N-1; i >= 0; i--) { 12924 PackageParser.Permission perm = pkg.permissions.get(i); 12925 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12926 if (bp != null) { 12927 // If the defining package is signed with our cert, it's okay. This 12928 // also includes the "updating the same package" case, of course. 12929 // "updating same package" could also involve key-rotation. 12930 final boolean sigsOk; 12931 if (bp.sourcePackage.equals(pkg.packageName) 12932 && (bp.packageSetting instanceof PackageSetting) 12933 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12934 scanFlags))) { 12935 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12936 } else { 12937 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12938 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12939 } 12940 if (!sigsOk) { 12941 // If the owning package is the system itself, we log but allow 12942 // install to proceed; we fail the install on all other permission 12943 // redefinitions. 12944 if (!bp.sourcePackage.equals("android")) { 12945 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12946 + pkg.packageName + " attempting to redeclare permission " 12947 + perm.info.name + " already owned by " + bp.sourcePackage); 12948 res.origPermission = perm.info.name; 12949 res.origPackage = bp.sourcePackage; 12950 return; 12951 } else { 12952 Slog.w(TAG, "Package " + pkg.packageName 12953 + " attempting to redeclare system permission " 12954 + perm.info.name + "; ignoring new declaration"); 12955 pkg.permissions.remove(i); 12956 } 12957 } 12958 } 12959 } 12960 12961 } 12962 12963 if (systemApp) { 12964 if (onExternal) { 12965 // Abort update; system app can't be replaced with app on sdcard 12966 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12967 "Cannot install updates to system apps on sdcard"); 12968 return; 12969 } else if (ephemeral) { 12970 // Abort update; system app can't be replaced with an ephemeral app 12971 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12972 "Cannot update a system app with an ephemeral app"); 12973 return; 12974 } 12975 } 12976 12977 if (args.move != null) { 12978 // We did an in-place move, so dex is ready to roll 12979 scanFlags |= SCAN_NO_DEX; 12980 scanFlags |= SCAN_MOVE; 12981 12982 synchronized (mPackages) { 12983 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12984 if (ps == null) { 12985 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12986 "Missing settings for moved package " + pkgName); 12987 } 12988 12989 // We moved the entire application as-is, so bring over the 12990 // previously derived ABI information. 12991 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12992 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12993 } 12994 12995 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12996 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12997 scanFlags |= SCAN_NO_DEX; 12998 12999 try { 13000 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13001 true /* extract libs */); 13002 } catch (PackageManagerException pme) { 13003 Slog.e(TAG, "Error deriving application ABI", pme); 13004 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13005 return; 13006 } 13007 } 13008 13009 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13010 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13011 return; 13012 } 13013 13014 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13015 13016 if (replace) { 13017 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13018 installerPackageName, volumeUuid, res); 13019 } else { 13020 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13021 args.user, installerPackageName, volumeUuid, res); 13022 } 13023 synchronized (mPackages) { 13024 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13025 if (ps != null) { 13026 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13027 } 13028 } 13029 } 13030 13031 private void startIntentFilterVerifications(int userId, boolean replacing, 13032 PackageParser.Package pkg) { 13033 if (mIntentFilterVerifierComponent == null) { 13034 Slog.w(TAG, "No IntentFilter verification will not be done as " 13035 + "there is no IntentFilterVerifier available!"); 13036 return; 13037 } 13038 13039 final int verifierUid = getPackageUid( 13040 mIntentFilterVerifierComponent.getPackageName(), 13041 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13042 13043 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13044 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13045 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13046 mHandler.sendMessage(msg); 13047 } 13048 13049 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13050 PackageParser.Package pkg) { 13051 int size = pkg.activities.size(); 13052 if (size == 0) { 13053 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13054 "No activity, so no need to verify any IntentFilter!"); 13055 return; 13056 } 13057 13058 final boolean hasDomainURLs = hasDomainURLs(pkg); 13059 if (!hasDomainURLs) { 13060 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13061 "No domain URLs, so no need to verify any IntentFilter!"); 13062 return; 13063 } 13064 13065 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13066 + " if any IntentFilter from the " + size 13067 + " Activities needs verification ..."); 13068 13069 int count = 0; 13070 final String packageName = pkg.packageName; 13071 13072 synchronized (mPackages) { 13073 // If this is a new install and we see that we've already run verification for this 13074 // package, we have nothing to do: it means the state was restored from backup. 13075 if (!replacing) { 13076 IntentFilterVerificationInfo ivi = 13077 mSettings.getIntentFilterVerificationLPr(packageName); 13078 if (ivi != null) { 13079 if (DEBUG_DOMAIN_VERIFICATION) { 13080 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13081 + ivi.getStatusString()); 13082 } 13083 return; 13084 } 13085 } 13086 13087 // If any filters need to be verified, then all need to be. 13088 boolean needToVerify = false; 13089 for (PackageParser.Activity a : pkg.activities) { 13090 for (ActivityIntentInfo filter : a.intents) { 13091 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13092 if (DEBUG_DOMAIN_VERIFICATION) { 13093 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13094 } 13095 needToVerify = true; 13096 break; 13097 } 13098 } 13099 } 13100 13101 if (needToVerify) { 13102 final int verificationId = mIntentFilterVerificationToken++; 13103 for (PackageParser.Activity a : pkg.activities) { 13104 for (ActivityIntentInfo filter : a.intents) { 13105 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13106 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13107 "Verification needed for IntentFilter:" + filter.toString()); 13108 mIntentFilterVerifier.addOneIntentFilterVerification( 13109 verifierUid, userId, verificationId, filter, packageName); 13110 count++; 13111 } 13112 } 13113 } 13114 } 13115 } 13116 13117 if (count > 0) { 13118 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13119 + " IntentFilter verification" + (count > 1 ? "s" : "") 13120 + " for userId:" + userId); 13121 mIntentFilterVerifier.startVerifications(userId); 13122 } else { 13123 if (DEBUG_DOMAIN_VERIFICATION) { 13124 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13125 } 13126 } 13127 } 13128 13129 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13130 final ComponentName cn = filter.activity.getComponentName(); 13131 final String packageName = cn.getPackageName(); 13132 13133 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13134 packageName); 13135 if (ivi == null) { 13136 return true; 13137 } 13138 int status = ivi.getStatus(); 13139 switch (status) { 13140 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13141 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13142 return true; 13143 13144 default: 13145 // Nothing to do 13146 return false; 13147 } 13148 } 13149 13150 private static boolean isMultiArch(ApplicationInfo info) { 13151 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13152 } 13153 13154 private static boolean isExternal(PackageParser.Package pkg) { 13155 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13156 } 13157 13158 private static boolean isExternal(PackageSetting ps) { 13159 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13160 } 13161 13162 private static boolean isEphemeral(PackageParser.Package pkg) { 13163 return pkg.applicationInfo.isEphemeralApp(); 13164 } 13165 13166 private static boolean isEphemeral(PackageSetting ps) { 13167 return ps.pkg != null && isEphemeral(ps.pkg); 13168 } 13169 13170 private static boolean isSystemApp(PackageParser.Package pkg) { 13171 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13172 } 13173 13174 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13175 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13176 } 13177 13178 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13179 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13180 } 13181 13182 private static boolean isSystemApp(PackageSetting ps) { 13183 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13184 } 13185 13186 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13187 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13188 } 13189 13190 private int packageFlagsToInstallFlags(PackageSetting ps) { 13191 int installFlags = 0; 13192 if (isEphemeral(ps)) { 13193 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13194 } 13195 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13196 // This existing package was an external ASEC install when we have 13197 // the external flag without a UUID 13198 installFlags |= PackageManager.INSTALL_EXTERNAL; 13199 } 13200 if (ps.isForwardLocked()) { 13201 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13202 } 13203 return installFlags; 13204 } 13205 13206 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13207 if (isExternal(pkg)) { 13208 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13209 return StorageManager.UUID_PRIMARY_PHYSICAL; 13210 } else { 13211 return pkg.volumeUuid; 13212 } 13213 } else { 13214 return StorageManager.UUID_PRIVATE_INTERNAL; 13215 } 13216 } 13217 13218 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13219 if (isExternal(pkg)) { 13220 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13221 return mSettings.getExternalVersion(); 13222 } else { 13223 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13224 } 13225 } else { 13226 return mSettings.getInternalVersion(); 13227 } 13228 } 13229 13230 private void deleteTempPackageFiles() { 13231 final FilenameFilter filter = new FilenameFilter() { 13232 public boolean accept(File dir, String name) { 13233 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13234 } 13235 }; 13236 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13237 file.delete(); 13238 } 13239 } 13240 13241 @Override 13242 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13243 int flags) { 13244 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13245 flags); 13246 } 13247 13248 @Override 13249 public void deletePackage(final String packageName, 13250 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13251 mContext.enforceCallingOrSelfPermission( 13252 android.Manifest.permission.DELETE_PACKAGES, null); 13253 Preconditions.checkNotNull(packageName); 13254 Preconditions.checkNotNull(observer); 13255 final int uid = Binder.getCallingUid(); 13256 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13257 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13258 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13259 mContext.enforceCallingOrSelfPermission( 13260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13261 "deletePackage for user " + userId); 13262 } 13263 13264 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13265 try { 13266 observer.onPackageDeleted(packageName, 13267 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13268 } catch (RemoteException re) { 13269 } 13270 return; 13271 } 13272 13273 for (int currentUserId : users) { 13274 if (getBlockUninstallForUser(packageName, currentUserId)) { 13275 try { 13276 observer.onPackageDeleted(packageName, 13277 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13278 } catch (RemoteException re) { 13279 } 13280 return; 13281 } 13282 } 13283 13284 if (DEBUG_REMOVE) { 13285 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13286 } 13287 // Queue up an async operation since the package deletion may take a little while. 13288 mHandler.post(new Runnable() { 13289 public void run() { 13290 mHandler.removeCallbacks(this); 13291 final int returnCode = deletePackageX(packageName, userId, flags); 13292 try { 13293 observer.onPackageDeleted(packageName, returnCode, null); 13294 } catch (RemoteException e) { 13295 Log.i(TAG, "Observer no longer exists."); 13296 } //end catch 13297 } //end run 13298 }); 13299 } 13300 13301 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13302 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13303 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13304 try { 13305 if (dpm != null) { 13306 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13307 /* callingUserOnly =*/ false); 13308 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13309 : deviceOwnerComponentName.getPackageName(); 13310 // Does the package contains the device owner? 13311 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13312 // this check is probably not needed, since DO should be registered as a device 13313 // admin on some user too. (Original bug for this: b/17657954) 13314 if (packageName.equals(deviceOwnerPackageName)) { 13315 return true; 13316 } 13317 // Does it contain a device admin for any user? 13318 int[] users; 13319 if (userId == UserHandle.USER_ALL) { 13320 users = sUserManager.getUserIds(); 13321 } else { 13322 users = new int[]{userId}; 13323 } 13324 for (int i = 0; i < users.length; ++i) { 13325 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13326 return true; 13327 } 13328 } 13329 } 13330 } catch (RemoteException e) { 13331 } 13332 return false; 13333 } 13334 13335 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13336 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13337 } 13338 13339 /** 13340 * This method is an internal method that could be get invoked either 13341 * to delete an installed package or to clean up a failed installation. 13342 * After deleting an installed package, a broadcast is sent to notify any 13343 * listeners that the package has been installed. For cleaning up a failed 13344 * installation, the broadcast is not necessary since the package's 13345 * installation wouldn't have sent the initial broadcast either 13346 * The key steps in deleting a package are 13347 * deleting the package information in internal structures like mPackages, 13348 * deleting the packages base directories through installd 13349 * updating mSettings to reflect current status 13350 * persisting settings for later use 13351 * sending a broadcast if necessary 13352 */ 13353 private int deletePackageX(String packageName, int userId, int flags) { 13354 final PackageRemovedInfo info = new PackageRemovedInfo(); 13355 final boolean res; 13356 13357 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13358 ? UserHandle.ALL : new UserHandle(userId); 13359 13360 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13361 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13362 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13363 } 13364 13365 boolean removedForAllUsers = false; 13366 boolean systemUpdate = false; 13367 13368 PackageParser.Package uninstalledPkg; 13369 13370 // for the uninstall-updates case and restricted profiles, remember the per- 13371 // userhandle installed state 13372 int[] allUsers; 13373 boolean[] perUserInstalled; 13374 synchronized (mPackages) { 13375 uninstalledPkg = mPackages.get(packageName); 13376 PackageSetting ps = mSettings.mPackages.get(packageName); 13377 allUsers = sUserManager.getUserIds(); 13378 perUserInstalled = new boolean[allUsers.length]; 13379 for (int i = 0; i < allUsers.length; i++) { 13380 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13381 } 13382 } 13383 13384 synchronized (mInstallLock) { 13385 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13386 res = deletePackageLI(packageName, removeForUser, 13387 true, allUsers, perUserInstalled, 13388 flags | REMOVE_CHATTY, info, true); 13389 systemUpdate = info.isRemovedPackageSystemUpdate; 13390 synchronized (mPackages) { 13391 if (res) { 13392 if (!systemUpdate && mPackages.get(packageName) == null) { 13393 removedForAllUsers = true; 13394 } 13395 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13396 } 13397 } 13398 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13399 + " removedForAllUsers=" + removedForAllUsers); 13400 } 13401 13402 if (res) { 13403 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13404 13405 // If the removed package was a system update, the old system package 13406 // was re-enabled; we need to broadcast this information 13407 if (systemUpdate) { 13408 Bundle extras = new Bundle(1); 13409 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13410 ? info.removedAppId : info.uid); 13411 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13412 13413 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13414 extras, 0, null, null, null); 13415 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13416 extras, 0, null, null, null); 13417 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13418 null, 0, packageName, null, null); 13419 } 13420 } 13421 // Force a gc here. 13422 Runtime.getRuntime().gc(); 13423 // Delete the resources here after sending the broadcast to let 13424 // other processes clean up before deleting resources. 13425 if (info.args != null) { 13426 synchronized (mInstallLock) { 13427 info.args.doPostDeleteLI(true); 13428 } 13429 } 13430 13431 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13432 } 13433 13434 class PackageRemovedInfo { 13435 String removedPackage; 13436 int uid = -1; 13437 int removedAppId = -1; 13438 int[] removedUsers = null; 13439 boolean isRemovedPackageSystemUpdate = false; 13440 // Clean up resources deleted packages. 13441 InstallArgs args = null; 13442 13443 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13444 Bundle extras = new Bundle(1); 13445 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13446 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13447 if (replacing) { 13448 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13449 } 13450 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13451 if (removedPackage != null) { 13452 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13453 extras, 0, null, null, removedUsers); 13454 if (fullRemove && !replacing) { 13455 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13456 extras, 0, null, null, removedUsers); 13457 } 13458 } 13459 if (removedAppId >= 0) { 13460 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13461 removedUsers); 13462 } 13463 } 13464 } 13465 13466 /* 13467 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13468 * flag is not set, the data directory is removed as well. 13469 * make sure this flag is set for partially installed apps. If not its meaningless to 13470 * delete a partially installed application. 13471 */ 13472 private void removePackageDataLI(PackageSetting ps, 13473 int[] allUserHandles, boolean[] perUserInstalled, 13474 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13475 String packageName = ps.name; 13476 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13477 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13478 // Retrieve object to delete permissions for shared user later on 13479 final PackageSetting deletedPs; 13480 // reader 13481 synchronized (mPackages) { 13482 deletedPs = mSettings.mPackages.get(packageName); 13483 if (outInfo != null) { 13484 outInfo.removedPackage = packageName; 13485 outInfo.removedUsers = deletedPs != null 13486 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13487 : null; 13488 } 13489 } 13490 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13491 removeDataDirsLI(ps.volumeUuid, packageName); 13492 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13493 } 13494 // writer 13495 synchronized (mPackages) { 13496 if (deletedPs != null) { 13497 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13498 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13499 clearDefaultBrowserIfNeeded(packageName); 13500 if (outInfo != null) { 13501 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13502 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13503 } 13504 updatePermissionsLPw(deletedPs.name, null, 0); 13505 if (deletedPs.sharedUser != null) { 13506 // Remove permissions associated with package. Since runtime 13507 // permissions are per user we have to kill the removed package 13508 // or packages running under the shared user of the removed 13509 // package if revoking the permissions requested only by the removed 13510 // package is successful and this causes a change in gids. 13511 for (int userId : UserManagerService.getInstance().getUserIds()) { 13512 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13513 userId); 13514 if (userIdToKill == UserHandle.USER_ALL 13515 || userIdToKill >= UserHandle.USER_SYSTEM) { 13516 // If gids changed for this user, kill all affected packages. 13517 mHandler.post(new Runnable() { 13518 @Override 13519 public void run() { 13520 // This has to happen with no lock held. 13521 killApplication(deletedPs.name, deletedPs.appId, 13522 KILL_APP_REASON_GIDS_CHANGED); 13523 } 13524 }); 13525 break; 13526 } 13527 } 13528 } 13529 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13530 } 13531 // make sure to preserve per-user disabled state if this removal was just 13532 // a downgrade of a system app to the factory package 13533 if (allUserHandles != null && perUserInstalled != null) { 13534 if (DEBUG_REMOVE) { 13535 Slog.d(TAG, "Propagating install state across downgrade"); 13536 } 13537 for (int i = 0; i < allUserHandles.length; i++) { 13538 if (DEBUG_REMOVE) { 13539 Slog.d(TAG, " user " + allUserHandles[i] 13540 + " => " + perUserInstalled[i]); 13541 } 13542 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13543 } 13544 } 13545 } 13546 // can downgrade to reader 13547 if (writeSettings) { 13548 // Save settings now 13549 mSettings.writeLPr(); 13550 } 13551 } 13552 if (outInfo != null) { 13553 // A user ID was deleted here. Go through all users and remove it 13554 // from KeyStore. 13555 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13556 } 13557 } 13558 13559 static boolean locationIsPrivileged(File path) { 13560 try { 13561 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13562 .getCanonicalPath(); 13563 return path.getCanonicalPath().startsWith(privilegedAppDir); 13564 } catch (IOException e) { 13565 Slog.e(TAG, "Unable to access code path " + path); 13566 } 13567 return false; 13568 } 13569 13570 /* 13571 * Tries to delete system package. 13572 */ 13573 private boolean deleteSystemPackageLI(PackageSetting newPs, 13574 int[] allUserHandles, boolean[] perUserInstalled, 13575 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13576 final boolean applyUserRestrictions 13577 = (allUserHandles != null) && (perUserInstalled != null); 13578 PackageSetting disabledPs = null; 13579 // Confirm if the system package has been updated 13580 // An updated system app can be deleted. This will also have to restore 13581 // the system pkg from system partition 13582 // reader 13583 synchronized (mPackages) { 13584 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13585 } 13586 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13587 + " disabledPs=" + disabledPs); 13588 if (disabledPs == null) { 13589 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13590 return false; 13591 } else if (DEBUG_REMOVE) { 13592 Slog.d(TAG, "Deleting system pkg from data partition"); 13593 } 13594 if (DEBUG_REMOVE) { 13595 if (applyUserRestrictions) { 13596 Slog.d(TAG, "Remembering install states:"); 13597 for (int i = 0; i < allUserHandles.length; i++) { 13598 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13599 } 13600 } 13601 } 13602 // Delete the updated package 13603 outInfo.isRemovedPackageSystemUpdate = true; 13604 if (disabledPs.versionCode < newPs.versionCode) { 13605 // Delete data for downgrades 13606 flags &= ~PackageManager.DELETE_KEEP_DATA; 13607 } else { 13608 // Preserve data by setting flag 13609 flags |= PackageManager.DELETE_KEEP_DATA; 13610 } 13611 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13612 allUserHandles, perUserInstalled, outInfo, writeSettings); 13613 if (!ret) { 13614 return false; 13615 } 13616 // writer 13617 synchronized (mPackages) { 13618 // Reinstate the old system package 13619 mSettings.enableSystemPackageLPw(newPs.name); 13620 // Remove any native libraries from the upgraded package. 13621 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13622 } 13623 // Install the system package 13624 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13625 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13626 if (locationIsPrivileged(disabledPs.codePath)) { 13627 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13628 } 13629 13630 final PackageParser.Package newPkg; 13631 try { 13632 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13633 } catch (PackageManagerException e) { 13634 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13635 return false; 13636 } 13637 13638 // writer 13639 synchronized (mPackages) { 13640 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13641 13642 // Propagate the permissions state as we do not want to drop on the floor 13643 // runtime permissions. The update permissions method below will take 13644 // care of removing obsolete permissions and grant install permissions. 13645 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13646 updatePermissionsLPw(newPkg.packageName, newPkg, 13647 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13648 13649 if (applyUserRestrictions) { 13650 if (DEBUG_REMOVE) { 13651 Slog.d(TAG, "Propagating install state across reinstall"); 13652 } 13653 for (int i = 0; i < allUserHandles.length; i++) { 13654 if (DEBUG_REMOVE) { 13655 Slog.d(TAG, " user " + allUserHandles[i] 13656 + " => " + perUserInstalled[i]); 13657 } 13658 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13659 13660 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13661 } 13662 // Regardless of writeSettings we need to ensure that this restriction 13663 // state propagation is persisted 13664 mSettings.writeAllUsersPackageRestrictionsLPr(); 13665 } 13666 // can downgrade to reader here 13667 if (writeSettings) { 13668 mSettings.writeLPr(); 13669 } 13670 } 13671 return true; 13672 } 13673 13674 private boolean deleteInstalledPackageLI(PackageSetting ps, 13675 boolean deleteCodeAndResources, int flags, 13676 int[] allUserHandles, boolean[] perUserInstalled, 13677 PackageRemovedInfo outInfo, boolean writeSettings) { 13678 if (outInfo != null) { 13679 outInfo.uid = ps.appId; 13680 } 13681 13682 // Delete package data from internal structures and also remove data if flag is set 13683 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13684 13685 // Delete application code and resources 13686 if (deleteCodeAndResources && (outInfo != null)) { 13687 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13688 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13689 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13690 } 13691 return true; 13692 } 13693 13694 @Override 13695 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13696 int userId) { 13697 mContext.enforceCallingOrSelfPermission( 13698 android.Manifest.permission.DELETE_PACKAGES, null); 13699 synchronized (mPackages) { 13700 PackageSetting ps = mSettings.mPackages.get(packageName); 13701 if (ps == null) { 13702 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13703 return false; 13704 } 13705 if (!ps.getInstalled(userId)) { 13706 // Can't block uninstall for an app that is not installed or enabled. 13707 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13708 return false; 13709 } 13710 ps.setBlockUninstall(blockUninstall, userId); 13711 mSettings.writePackageRestrictionsLPr(userId); 13712 } 13713 return true; 13714 } 13715 13716 @Override 13717 public boolean getBlockUninstallForUser(String packageName, int userId) { 13718 synchronized (mPackages) { 13719 PackageSetting ps = mSettings.mPackages.get(packageName); 13720 if (ps == null) { 13721 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13722 return false; 13723 } 13724 return ps.getBlockUninstall(userId); 13725 } 13726 } 13727 13728 /* 13729 * This method handles package deletion in general 13730 */ 13731 private boolean deletePackageLI(String packageName, UserHandle user, 13732 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13733 int flags, PackageRemovedInfo outInfo, 13734 boolean writeSettings) { 13735 if (packageName == null) { 13736 Slog.w(TAG, "Attempt to delete null packageName."); 13737 return false; 13738 } 13739 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13740 PackageSetting ps; 13741 boolean dataOnly = false; 13742 int removeUser = -1; 13743 int appId = -1; 13744 synchronized (mPackages) { 13745 ps = mSettings.mPackages.get(packageName); 13746 if (ps == null) { 13747 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13748 return false; 13749 } 13750 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13751 && user.getIdentifier() != UserHandle.USER_ALL) { 13752 // The caller is asking that the package only be deleted for a single 13753 // user. To do this, we just mark its uninstalled state and delete 13754 // its data. If this is a system app, we only allow this to happen if 13755 // they have set the special DELETE_SYSTEM_APP which requests different 13756 // semantics than normal for uninstalling system apps. 13757 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13758 final int userId = user.getIdentifier(); 13759 ps.setUserState(userId, 13760 COMPONENT_ENABLED_STATE_DEFAULT, 13761 false, //installed 13762 true, //stopped 13763 true, //notLaunched 13764 false, //hidden 13765 null, null, null, 13766 false, // blockUninstall 13767 ps.readUserState(userId).domainVerificationStatus, 0); 13768 if (!isSystemApp(ps)) { 13769 // Do not uninstall the APK if an app should be cached 13770 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13771 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13772 // Other user still have this package installed, so all 13773 // we need to do is clear this user's data and save that 13774 // it is uninstalled. 13775 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13776 removeUser = user.getIdentifier(); 13777 appId = ps.appId; 13778 scheduleWritePackageRestrictionsLocked(removeUser); 13779 } else { 13780 // We need to set it back to 'installed' so the uninstall 13781 // broadcasts will be sent correctly. 13782 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13783 ps.setInstalled(true, user.getIdentifier()); 13784 } 13785 } else { 13786 // This is a system app, so we assume that the 13787 // other users still have this package installed, so all 13788 // we need to do is clear this user's data and save that 13789 // it is uninstalled. 13790 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13791 removeUser = user.getIdentifier(); 13792 appId = ps.appId; 13793 scheduleWritePackageRestrictionsLocked(removeUser); 13794 } 13795 } 13796 } 13797 13798 if (removeUser >= 0) { 13799 // From above, we determined that we are deleting this only 13800 // for a single user. Continue the work here. 13801 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13802 if (outInfo != null) { 13803 outInfo.removedPackage = packageName; 13804 outInfo.removedAppId = appId; 13805 outInfo.removedUsers = new int[] {removeUser}; 13806 } 13807 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13808 removeKeystoreDataIfNeeded(removeUser, appId); 13809 schedulePackageCleaning(packageName, removeUser, false); 13810 synchronized (mPackages) { 13811 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13812 scheduleWritePackageRestrictionsLocked(removeUser); 13813 } 13814 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13815 } 13816 return true; 13817 } 13818 13819 if (dataOnly) { 13820 // Delete application data first 13821 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13822 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13823 return true; 13824 } 13825 13826 boolean ret = false; 13827 if (isSystemApp(ps)) { 13828 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13829 // When an updated system application is deleted we delete the existing resources as well and 13830 // fall back to existing code in system partition 13831 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13832 flags, outInfo, writeSettings); 13833 } else { 13834 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13835 // Kill application pre-emptively especially for apps on sd. 13836 killApplication(packageName, ps.appId, "uninstall pkg"); 13837 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13838 allUserHandles, perUserInstalled, 13839 outInfo, writeSettings); 13840 } 13841 13842 return ret; 13843 } 13844 13845 private final static class ClearStorageConnection implements ServiceConnection { 13846 IMediaContainerService mContainerService; 13847 13848 @Override 13849 public void onServiceConnected(ComponentName name, IBinder service) { 13850 synchronized (this) { 13851 mContainerService = IMediaContainerService.Stub.asInterface(service); 13852 notifyAll(); 13853 } 13854 } 13855 13856 @Override 13857 public void onServiceDisconnected(ComponentName name) { 13858 } 13859 } 13860 13861 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13862 final boolean mounted; 13863 if (Environment.isExternalStorageEmulated()) { 13864 mounted = true; 13865 } else { 13866 final String status = Environment.getExternalStorageState(); 13867 13868 mounted = status.equals(Environment.MEDIA_MOUNTED) 13869 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13870 } 13871 13872 if (!mounted) { 13873 return; 13874 } 13875 13876 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13877 int[] users; 13878 if (userId == UserHandle.USER_ALL) { 13879 users = sUserManager.getUserIds(); 13880 } else { 13881 users = new int[] { userId }; 13882 } 13883 final ClearStorageConnection conn = new ClearStorageConnection(); 13884 if (mContext.bindServiceAsUser( 13885 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13886 try { 13887 for (int curUser : users) { 13888 long timeout = SystemClock.uptimeMillis() + 5000; 13889 synchronized (conn) { 13890 long now = SystemClock.uptimeMillis(); 13891 while (conn.mContainerService == null && now < timeout) { 13892 try { 13893 conn.wait(timeout - now); 13894 } catch (InterruptedException e) { 13895 } 13896 } 13897 } 13898 if (conn.mContainerService == null) { 13899 return; 13900 } 13901 13902 final UserEnvironment userEnv = new UserEnvironment(curUser); 13903 clearDirectory(conn.mContainerService, 13904 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13905 if (allData) { 13906 clearDirectory(conn.mContainerService, 13907 userEnv.buildExternalStorageAppDataDirs(packageName)); 13908 clearDirectory(conn.mContainerService, 13909 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13910 } 13911 } 13912 } finally { 13913 mContext.unbindService(conn); 13914 } 13915 } 13916 } 13917 13918 @Override 13919 public void clearApplicationUserData(final String packageName, 13920 final IPackageDataObserver observer, final int userId) { 13921 mContext.enforceCallingOrSelfPermission( 13922 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13923 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13924 // Queue up an async operation since the package deletion may take a little while. 13925 mHandler.post(new Runnable() { 13926 public void run() { 13927 mHandler.removeCallbacks(this); 13928 final boolean succeeded; 13929 synchronized (mInstallLock) { 13930 succeeded = clearApplicationUserDataLI(packageName, userId); 13931 } 13932 clearExternalStorageDataSync(packageName, userId, true); 13933 if (succeeded) { 13934 // invoke DeviceStorageMonitor's update method to clear any notifications 13935 DeviceStorageMonitorInternal 13936 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13937 if (dsm != null) { 13938 dsm.checkMemory(); 13939 } 13940 } 13941 if(observer != null) { 13942 try { 13943 observer.onRemoveCompleted(packageName, succeeded); 13944 } catch (RemoteException e) { 13945 Log.i(TAG, "Observer no longer exists."); 13946 } 13947 } //end if observer 13948 } //end run 13949 }); 13950 } 13951 13952 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13953 if (packageName == null) { 13954 Slog.w(TAG, "Attempt to delete null packageName."); 13955 return false; 13956 } 13957 13958 // Try finding details about the requested package 13959 PackageParser.Package pkg; 13960 synchronized (mPackages) { 13961 pkg = mPackages.get(packageName); 13962 if (pkg == null) { 13963 final PackageSetting ps = mSettings.mPackages.get(packageName); 13964 if (ps != null) { 13965 pkg = ps.pkg; 13966 } 13967 } 13968 13969 if (pkg == null) { 13970 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13971 return false; 13972 } 13973 13974 PackageSetting ps = (PackageSetting) pkg.mExtras; 13975 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13976 } 13977 13978 // Always delete data directories for package, even if we found no other 13979 // record of app. This helps users recover from UID mismatches without 13980 // resorting to a full data wipe. 13981 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13982 if (retCode < 0) { 13983 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13984 return false; 13985 } 13986 13987 final int appId = pkg.applicationInfo.uid; 13988 removeKeystoreDataIfNeeded(userId, appId); 13989 13990 // Create a native library symlink only if we have native libraries 13991 // and if the native libraries are 32 bit libraries. We do not provide 13992 // this symlink for 64 bit libraries. 13993 if (pkg.applicationInfo.primaryCpuAbi != null && 13994 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13995 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13996 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13997 nativeLibPath, userId) < 0) { 13998 Slog.w(TAG, "Failed linking native library dir"); 13999 return false; 14000 } 14001 } 14002 14003 return true; 14004 } 14005 14006 /** 14007 * Reverts user permission state changes (permissions and flags) in 14008 * all packages for a given user. 14009 * 14010 * @param userId The device user for which to do a reset. 14011 */ 14012 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14013 final int packageCount = mPackages.size(); 14014 for (int i = 0; i < packageCount; i++) { 14015 PackageParser.Package pkg = mPackages.valueAt(i); 14016 PackageSetting ps = (PackageSetting) pkg.mExtras; 14017 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14018 } 14019 } 14020 14021 /** 14022 * Reverts user permission state changes (permissions and flags). 14023 * 14024 * @param ps The package for which to reset. 14025 * @param userId The device user for which to do a reset. 14026 */ 14027 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14028 final PackageSetting ps, final int userId) { 14029 if (ps.pkg == null) { 14030 return; 14031 } 14032 14033 // These are flags that can change base on user actions. 14034 final int userSettableMask = FLAG_PERMISSION_USER_SET 14035 | FLAG_PERMISSION_USER_FIXED 14036 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14037 | FLAG_PERMISSION_REVIEW_REQUIRED; 14038 14039 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14040 | FLAG_PERMISSION_POLICY_FIXED; 14041 14042 boolean writeInstallPermissions = false; 14043 boolean writeRuntimePermissions = false; 14044 14045 final int permissionCount = ps.pkg.requestedPermissions.size(); 14046 for (int i = 0; i < permissionCount; i++) { 14047 String permission = ps.pkg.requestedPermissions.get(i); 14048 14049 BasePermission bp = mSettings.mPermissions.get(permission); 14050 if (bp == null) { 14051 continue; 14052 } 14053 14054 // If shared user we just reset the state to which only this app contributed. 14055 if (ps.sharedUser != null) { 14056 boolean used = false; 14057 final int packageCount = ps.sharedUser.packages.size(); 14058 for (int j = 0; j < packageCount; j++) { 14059 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14060 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14061 && pkg.pkg.requestedPermissions.contains(permission)) { 14062 used = true; 14063 break; 14064 } 14065 } 14066 if (used) { 14067 continue; 14068 } 14069 } 14070 14071 PermissionsState permissionsState = ps.getPermissionsState(); 14072 14073 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14074 14075 // Always clear the user settable flags. 14076 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14077 bp.name) != null; 14078 // If permission review is enabled and this is a legacy app, mark the 14079 // permission as requiring a review as this is the initial state. 14080 int flags = 0; 14081 if (Build.PERMISSIONS_REVIEW_REQUIRED 14082 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14083 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14084 } 14085 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14086 if (hasInstallState) { 14087 writeInstallPermissions = true; 14088 } else { 14089 writeRuntimePermissions = true; 14090 } 14091 } 14092 14093 // Below is only runtime permission handling. 14094 if (!bp.isRuntime()) { 14095 continue; 14096 } 14097 14098 // Never clobber system or policy. 14099 if ((oldFlags & policyOrSystemFlags) != 0) { 14100 continue; 14101 } 14102 14103 // If this permission was granted by default, make sure it is. 14104 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14105 if (permissionsState.grantRuntimePermission(bp, userId) 14106 != PERMISSION_OPERATION_FAILURE) { 14107 writeRuntimePermissions = true; 14108 } 14109 // If permission review is enabled the permissions for a legacy apps 14110 // are represented as constantly granted runtime ones, so don't revoke. 14111 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14112 // Otherwise, reset the permission. 14113 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14114 switch (revokeResult) { 14115 case PERMISSION_OPERATION_SUCCESS: { 14116 writeRuntimePermissions = true; 14117 } break; 14118 14119 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14120 writeRuntimePermissions = true; 14121 final int appId = ps.appId; 14122 mHandler.post(new Runnable() { 14123 @Override 14124 public void run() { 14125 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14126 } 14127 }); 14128 } break; 14129 } 14130 } 14131 } 14132 14133 // Synchronously write as we are taking permissions away. 14134 if (writeRuntimePermissions) { 14135 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14136 } 14137 14138 // Synchronously write as we are taking permissions away. 14139 if (writeInstallPermissions) { 14140 mSettings.writeLPr(); 14141 } 14142 } 14143 14144 /** 14145 * Remove entries from the keystore daemon. Will only remove it if the 14146 * {@code appId} is valid. 14147 */ 14148 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14149 if (appId < 0) { 14150 return; 14151 } 14152 14153 final KeyStore keyStore = KeyStore.getInstance(); 14154 if (keyStore != null) { 14155 if (userId == UserHandle.USER_ALL) { 14156 for (final int individual : sUserManager.getUserIds()) { 14157 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14158 } 14159 } else { 14160 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14161 } 14162 } else { 14163 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14164 } 14165 } 14166 14167 @Override 14168 public void deleteApplicationCacheFiles(final String packageName, 14169 final IPackageDataObserver observer) { 14170 mContext.enforceCallingOrSelfPermission( 14171 android.Manifest.permission.DELETE_CACHE_FILES, null); 14172 // Queue up an async operation since the package deletion may take a little while. 14173 final int userId = UserHandle.getCallingUserId(); 14174 mHandler.post(new Runnable() { 14175 public void run() { 14176 mHandler.removeCallbacks(this); 14177 final boolean succeded; 14178 synchronized (mInstallLock) { 14179 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14180 } 14181 clearExternalStorageDataSync(packageName, userId, false); 14182 if (observer != null) { 14183 try { 14184 observer.onRemoveCompleted(packageName, succeded); 14185 } catch (RemoteException e) { 14186 Log.i(TAG, "Observer no longer exists."); 14187 } 14188 } //end if observer 14189 } //end run 14190 }); 14191 } 14192 14193 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14194 if (packageName == null) { 14195 Slog.w(TAG, "Attempt to delete null packageName."); 14196 return false; 14197 } 14198 PackageParser.Package p; 14199 synchronized (mPackages) { 14200 p = mPackages.get(packageName); 14201 } 14202 if (p == null) { 14203 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14204 return false; 14205 } 14206 final ApplicationInfo applicationInfo = p.applicationInfo; 14207 if (applicationInfo == null) { 14208 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14209 return false; 14210 } 14211 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14212 if (retCode < 0) { 14213 Slog.w(TAG, "Couldn't remove cache files for package: " 14214 + packageName + " u" + userId); 14215 return false; 14216 } 14217 return true; 14218 } 14219 14220 @Override 14221 public void getPackageSizeInfo(final String packageName, int userHandle, 14222 final IPackageStatsObserver observer) { 14223 mContext.enforceCallingOrSelfPermission( 14224 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14225 if (packageName == null) { 14226 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14227 } 14228 14229 PackageStats stats = new PackageStats(packageName, userHandle); 14230 14231 /* 14232 * Queue up an async operation since the package measurement may take a 14233 * little while. 14234 */ 14235 Message msg = mHandler.obtainMessage(INIT_COPY); 14236 msg.obj = new MeasureParams(stats, observer); 14237 mHandler.sendMessage(msg); 14238 } 14239 14240 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14241 PackageStats pStats) { 14242 if (packageName == null) { 14243 Slog.w(TAG, "Attempt to get size of null packageName."); 14244 return false; 14245 } 14246 PackageParser.Package p; 14247 boolean dataOnly = false; 14248 String libDirRoot = null; 14249 String asecPath = null; 14250 PackageSetting ps = null; 14251 synchronized (mPackages) { 14252 p = mPackages.get(packageName); 14253 ps = mSettings.mPackages.get(packageName); 14254 if(p == null) { 14255 dataOnly = true; 14256 if((ps == null) || (ps.pkg == null)) { 14257 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14258 return false; 14259 } 14260 p = ps.pkg; 14261 } 14262 if (ps != null) { 14263 libDirRoot = ps.legacyNativeLibraryPathString; 14264 } 14265 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14266 final long token = Binder.clearCallingIdentity(); 14267 try { 14268 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14269 if (secureContainerId != null) { 14270 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14271 } 14272 } finally { 14273 Binder.restoreCallingIdentity(token); 14274 } 14275 } 14276 } 14277 String publicSrcDir = null; 14278 if(!dataOnly) { 14279 final ApplicationInfo applicationInfo = p.applicationInfo; 14280 if (applicationInfo == null) { 14281 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14282 return false; 14283 } 14284 if (p.isForwardLocked()) { 14285 publicSrcDir = applicationInfo.getBaseResourcePath(); 14286 } 14287 } 14288 // TODO: extend to measure size of split APKs 14289 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14290 // not just the first level. 14291 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14292 // just the primary. 14293 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14294 14295 String apkPath; 14296 File packageDir = new File(p.codePath); 14297 14298 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14299 apkPath = packageDir.getAbsolutePath(); 14300 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14301 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14302 libDirRoot = null; 14303 } 14304 } else { 14305 apkPath = p.baseCodePath; 14306 } 14307 14308 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14309 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14310 if (res < 0) { 14311 return false; 14312 } 14313 14314 // Fix-up for forward-locked applications in ASEC containers. 14315 if (!isExternal(p)) { 14316 pStats.codeSize += pStats.externalCodeSize; 14317 pStats.externalCodeSize = 0L; 14318 } 14319 14320 return true; 14321 } 14322 14323 14324 @Override 14325 public void addPackageToPreferred(String packageName) { 14326 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14327 } 14328 14329 @Override 14330 public void removePackageFromPreferred(String packageName) { 14331 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14332 } 14333 14334 @Override 14335 public List<PackageInfo> getPreferredPackages(int flags) { 14336 return new ArrayList<PackageInfo>(); 14337 } 14338 14339 private int getUidTargetSdkVersionLockedLPr(int uid) { 14340 Object obj = mSettings.getUserIdLPr(uid); 14341 if (obj instanceof SharedUserSetting) { 14342 final SharedUserSetting sus = (SharedUserSetting) obj; 14343 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14344 final Iterator<PackageSetting> it = sus.packages.iterator(); 14345 while (it.hasNext()) { 14346 final PackageSetting ps = it.next(); 14347 if (ps.pkg != null) { 14348 int v = ps.pkg.applicationInfo.targetSdkVersion; 14349 if (v < vers) vers = v; 14350 } 14351 } 14352 return vers; 14353 } else if (obj instanceof PackageSetting) { 14354 final PackageSetting ps = (PackageSetting) obj; 14355 if (ps.pkg != null) { 14356 return ps.pkg.applicationInfo.targetSdkVersion; 14357 } 14358 } 14359 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14360 } 14361 14362 @Override 14363 public void addPreferredActivity(IntentFilter filter, int match, 14364 ComponentName[] set, ComponentName activity, int userId) { 14365 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14366 "Adding preferred"); 14367 } 14368 14369 private void addPreferredActivityInternal(IntentFilter filter, int match, 14370 ComponentName[] set, ComponentName activity, boolean always, int userId, 14371 String opname) { 14372 // writer 14373 int callingUid = Binder.getCallingUid(); 14374 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14375 if (filter.countActions() == 0) { 14376 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14377 return; 14378 } 14379 synchronized (mPackages) { 14380 if (mContext.checkCallingOrSelfPermission( 14381 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14382 != PackageManager.PERMISSION_GRANTED) { 14383 if (getUidTargetSdkVersionLockedLPr(callingUid) 14384 < Build.VERSION_CODES.FROYO) { 14385 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14386 + callingUid); 14387 return; 14388 } 14389 mContext.enforceCallingOrSelfPermission( 14390 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14391 } 14392 14393 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14394 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14395 + userId + ":"); 14396 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14397 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14398 scheduleWritePackageRestrictionsLocked(userId); 14399 } 14400 } 14401 14402 @Override 14403 public void replacePreferredActivity(IntentFilter filter, int match, 14404 ComponentName[] set, ComponentName activity, int userId) { 14405 if (filter.countActions() != 1) { 14406 throw new IllegalArgumentException( 14407 "replacePreferredActivity expects filter to have only 1 action."); 14408 } 14409 if (filter.countDataAuthorities() != 0 14410 || filter.countDataPaths() != 0 14411 || filter.countDataSchemes() > 1 14412 || filter.countDataTypes() != 0) { 14413 throw new IllegalArgumentException( 14414 "replacePreferredActivity expects filter to have no data authorities, " + 14415 "paths, or types; and at most one scheme."); 14416 } 14417 14418 final int callingUid = Binder.getCallingUid(); 14419 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14420 synchronized (mPackages) { 14421 if (mContext.checkCallingOrSelfPermission( 14422 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14423 != PackageManager.PERMISSION_GRANTED) { 14424 if (getUidTargetSdkVersionLockedLPr(callingUid) 14425 < Build.VERSION_CODES.FROYO) { 14426 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14427 + Binder.getCallingUid()); 14428 return; 14429 } 14430 mContext.enforceCallingOrSelfPermission( 14431 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14432 } 14433 14434 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14435 if (pir != null) { 14436 // Get all of the existing entries that exactly match this filter. 14437 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14438 if (existing != null && existing.size() == 1) { 14439 PreferredActivity cur = existing.get(0); 14440 if (DEBUG_PREFERRED) { 14441 Slog.i(TAG, "Checking replace of preferred:"); 14442 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14443 if (!cur.mPref.mAlways) { 14444 Slog.i(TAG, " -- CUR; not mAlways!"); 14445 } else { 14446 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14447 Slog.i(TAG, " -- CUR: mSet=" 14448 + Arrays.toString(cur.mPref.mSetComponents)); 14449 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14450 Slog.i(TAG, " -- NEW: mMatch=" 14451 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14452 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14453 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14454 } 14455 } 14456 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14457 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14458 && cur.mPref.sameSet(set)) { 14459 // Setting the preferred activity to what it happens to be already 14460 if (DEBUG_PREFERRED) { 14461 Slog.i(TAG, "Replacing with same preferred activity " 14462 + cur.mPref.mShortComponent + " for user " 14463 + userId + ":"); 14464 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14465 } 14466 return; 14467 } 14468 } 14469 14470 if (existing != null) { 14471 if (DEBUG_PREFERRED) { 14472 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14473 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14474 } 14475 for (int i = 0; i < existing.size(); i++) { 14476 PreferredActivity pa = existing.get(i); 14477 if (DEBUG_PREFERRED) { 14478 Slog.i(TAG, "Removing existing preferred activity " 14479 + pa.mPref.mComponent + ":"); 14480 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14481 } 14482 pir.removeFilter(pa); 14483 } 14484 } 14485 } 14486 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14487 "Replacing preferred"); 14488 } 14489 } 14490 14491 @Override 14492 public void clearPackagePreferredActivities(String packageName) { 14493 final int uid = Binder.getCallingUid(); 14494 // writer 14495 synchronized (mPackages) { 14496 PackageParser.Package pkg = mPackages.get(packageName); 14497 if (pkg == null || pkg.applicationInfo.uid != uid) { 14498 if (mContext.checkCallingOrSelfPermission( 14499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14500 != PackageManager.PERMISSION_GRANTED) { 14501 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14502 < Build.VERSION_CODES.FROYO) { 14503 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14504 + Binder.getCallingUid()); 14505 return; 14506 } 14507 mContext.enforceCallingOrSelfPermission( 14508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14509 } 14510 } 14511 14512 int user = UserHandle.getCallingUserId(); 14513 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14514 scheduleWritePackageRestrictionsLocked(user); 14515 } 14516 } 14517 } 14518 14519 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14520 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14521 ArrayList<PreferredActivity> removed = null; 14522 boolean changed = false; 14523 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14524 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14525 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14526 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14527 continue; 14528 } 14529 Iterator<PreferredActivity> it = pir.filterIterator(); 14530 while (it.hasNext()) { 14531 PreferredActivity pa = it.next(); 14532 // Mark entry for removal only if it matches the package name 14533 // and the entry is of type "always". 14534 if (packageName == null || 14535 (pa.mPref.mComponent.getPackageName().equals(packageName) 14536 && pa.mPref.mAlways)) { 14537 if (removed == null) { 14538 removed = new ArrayList<PreferredActivity>(); 14539 } 14540 removed.add(pa); 14541 } 14542 } 14543 if (removed != null) { 14544 for (int j=0; j<removed.size(); j++) { 14545 PreferredActivity pa = removed.get(j); 14546 pir.removeFilter(pa); 14547 } 14548 changed = true; 14549 } 14550 } 14551 return changed; 14552 } 14553 14554 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14555 private void clearIntentFilterVerificationsLPw(int userId) { 14556 final int packageCount = mPackages.size(); 14557 for (int i = 0; i < packageCount; i++) { 14558 PackageParser.Package pkg = mPackages.valueAt(i); 14559 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14560 } 14561 } 14562 14563 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14564 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14565 if (userId == UserHandle.USER_ALL) { 14566 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14567 sUserManager.getUserIds())) { 14568 for (int oneUserId : sUserManager.getUserIds()) { 14569 scheduleWritePackageRestrictionsLocked(oneUserId); 14570 } 14571 } 14572 } else { 14573 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14574 scheduleWritePackageRestrictionsLocked(userId); 14575 } 14576 } 14577 } 14578 14579 void clearDefaultBrowserIfNeeded(String packageName) { 14580 for (int oneUserId : sUserManager.getUserIds()) { 14581 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14582 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14583 if (packageName.equals(defaultBrowserPackageName)) { 14584 setDefaultBrowserPackageName(null, oneUserId); 14585 } 14586 } 14587 } 14588 14589 @Override 14590 public void resetApplicationPreferences(int userId) { 14591 mContext.enforceCallingOrSelfPermission( 14592 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14593 // writer 14594 synchronized (mPackages) { 14595 final long identity = Binder.clearCallingIdentity(); 14596 try { 14597 clearPackagePreferredActivitiesLPw(null, userId); 14598 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14599 // TODO: We have to reset the default SMS and Phone. This requires 14600 // significant refactoring to keep all default apps in the package 14601 // manager (cleaner but more work) or have the services provide 14602 // callbacks to the package manager to request a default app reset. 14603 applyFactoryDefaultBrowserLPw(userId); 14604 clearIntentFilterVerificationsLPw(userId); 14605 primeDomainVerificationsLPw(userId); 14606 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14607 scheduleWritePackageRestrictionsLocked(userId); 14608 } finally { 14609 Binder.restoreCallingIdentity(identity); 14610 } 14611 } 14612 } 14613 14614 @Override 14615 public int getPreferredActivities(List<IntentFilter> outFilters, 14616 List<ComponentName> outActivities, String packageName) { 14617 14618 int num = 0; 14619 final int userId = UserHandle.getCallingUserId(); 14620 // reader 14621 synchronized (mPackages) { 14622 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14623 if (pir != null) { 14624 final Iterator<PreferredActivity> it = pir.filterIterator(); 14625 while (it.hasNext()) { 14626 final PreferredActivity pa = it.next(); 14627 if (packageName == null 14628 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14629 && pa.mPref.mAlways)) { 14630 if (outFilters != null) { 14631 outFilters.add(new IntentFilter(pa)); 14632 } 14633 if (outActivities != null) { 14634 outActivities.add(pa.mPref.mComponent); 14635 } 14636 } 14637 } 14638 } 14639 } 14640 14641 return num; 14642 } 14643 14644 @Override 14645 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14646 int userId) { 14647 int callingUid = Binder.getCallingUid(); 14648 if (callingUid != Process.SYSTEM_UID) { 14649 throw new SecurityException( 14650 "addPersistentPreferredActivity can only be run by the system"); 14651 } 14652 if (filter.countActions() == 0) { 14653 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14654 return; 14655 } 14656 synchronized (mPackages) { 14657 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14658 " :"); 14659 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14660 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14661 new PersistentPreferredActivity(filter, activity)); 14662 scheduleWritePackageRestrictionsLocked(userId); 14663 } 14664 } 14665 14666 @Override 14667 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14668 int callingUid = Binder.getCallingUid(); 14669 if (callingUid != Process.SYSTEM_UID) { 14670 throw new SecurityException( 14671 "clearPackagePersistentPreferredActivities can only be run by the system"); 14672 } 14673 ArrayList<PersistentPreferredActivity> removed = null; 14674 boolean changed = false; 14675 synchronized (mPackages) { 14676 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14677 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14678 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14679 .valueAt(i); 14680 if (userId != thisUserId) { 14681 continue; 14682 } 14683 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14684 while (it.hasNext()) { 14685 PersistentPreferredActivity ppa = it.next(); 14686 // Mark entry for removal only if it matches the package name. 14687 if (ppa.mComponent.getPackageName().equals(packageName)) { 14688 if (removed == null) { 14689 removed = new ArrayList<PersistentPreferredActivity>(); 14690 } 14691 removed.add(ppa); 14692 } 14693 } 14694 if (removed != null) { 14695 for (int j=0; j<removed.size(); j++) { 14696 PersistentPreferredActivity ppa = removed.get(j); 14697 ppir.removeFilter(ppa); 14698 } 14699 changed = true; 14700 } 14701 } 14702 14703 if (changed) { 14704 scheduleWritePackageRestrictionsLocked(userId); 14705 } 14706 } 14707 } 14708 14709 /** 14710 * Common machinery for picking apart a restored XML blob and passing 14711 * it to a caller-supplied functor to be applied to the running system. 14712 */ 14713 private void restoreFromXml(XmlPullParser parser, int userId, 14714 String expectedStartTag, BlobXmlRestorer functor) 14715 throws IOException, XmlPullParserException { 14716 int type; 14717 while ((type = parser.next()) != XmlPullParser.START_TAG 14718 && type != XmlPullParser.END_DOCUMENT) { 14719 } 14720 if (type != XmlPullParser.START_TAG) { 14721 // oops didn't find a start tag?! 14722 if (DEBUG_BACKUP) { 14723 Slog.e(TAG, "Didn't find start tag during restore"); 14724 } 14725 return; 14726 } 14727 14728 // this is supposed to be TAG_PREFERRED_BACKUP 14729 if (!expectedStartTag.equals(parser.getName())) { 14730 if (DEBUG_BACKUP) { 14731 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14732 } 14733 return; 14734 } 14735 14736 // skip interfering stuff, then we're aligned with the backing implementation 14737 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14738 functor.apply(parser, userId); 14739 } 14740 14741 private interface BlobXmlRestorer { 14742 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14743 } 14744 14745 /** 14746 * Non-Binder method, support for the backup/restore mechanism: write the 14747 * full set of preferred activities in its canonical XML format. Returns the 14748 * XML output as a byte array, or null if there is none. 14749 */ 14750 @Override 14751 public byte[] getPreferredActivityBackup(int userId) { 14752 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14753 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14754 } 14755 14756 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14757 try { 14758 final XmlSerializer serializer = new FastXmlSerializer(); 14759 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14760 serializer.startDocument(null, true); 14761 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14762 14763 synchronized (mPackages) { 14764 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14765 } 14766 14767 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14768 serializer.endDocument(); 14769 serializer.flush(); 14770 } catch (Exception e) { 14771 if (DEBUG_BACKUP) { 14772 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14773 } 14774 return null; 14775 } 14776 14777 return dataStream.toByteArray(); 14778 } 14779 14780 @Override 14781 public void restorePreferredActivities(byte[] backup, int userId) { 14782 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14783 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14784 } 14785 14786 try { 14787 final XmlPullParser parser = Xml.newPullParser(); 14788 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14789 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14790 new BlobXmlRestorer() { 14791 @Override 14792 public void apply(XmlPullParser parser, int userId) 14793 throws XmlPullParserException, IOException { 14794 synchronized (mPackages) { 14795 mSettings.readPreferredActivitiesLPw(parser, userId); 14796 } 14797 } 14798 } ); 14799 } catch (Exception e) { 14800 if (DEBUG_BACKUP) { 14801 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14802 } 14803 } 14804 } 14805 14806 /** 14807 * Non-Binder method, support for the backup/restore mechanism: write the 14808 * default browser (etc) settings in its canonical XML format. Returns the default 14809 * browser XML representation as a byte array, or null if there is none. 14810 */ 14811 @Override 14812 public byte[] getDefaultAppsBackup(int userId) { 14813 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14814 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14815 } 14816 14817 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14818 try { 14819 final XmlSerializer serializer = new FastXmlSerializer(); 14820 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14821 serializer.startDocument(null, true); 14822 serializer.startTag(null, TAG_DEFAULT_APPS); 14823 14824 synchronized (mPackages) { 14825 mSettings.writeDefaultAppsLPr(serializer, userId); 14826 } 14827 14828 serializer.endTag(null, TAG_DEFAULT_APPS); 14829 serializer.endDocument(); 14830 serializer.flush(); 14831 } catch (Exception e) { 14832 if (DEBUG_BACKUP) { 14833 Slog.e(TAG, "Unable to write default apps for backup", e); 14834 } 14835 return null; 14836 } 14837 14838 return dataStream.toByteArray(); 14839 } 14840 14841 @Override 14842 public void restoreDefaultApps(byte[] backup, int userId) { 14843 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14844 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14845 } 14846 14847 try { 14848 final XmlPullParser parser = Xml.newPullParser(); 14849 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14850 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14851 new BlobXmlRestorer() { 14852 @Override 14853 public void apply(XmlPullParser parser, int userId) 14854 throws XmlPullParserException, IOException { 14855 synchronized (mPackages) { 14856 mSettings.readDefaultAppsLPw(parser, userId); 14857 } 14858 } 14859 } ); 14860 } catch (Exception e) { 14861 if (DEBUG_BACKUP) { 14862 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14863 } 14864 } 14865 } 14866 14867 @Override 14868 public byte[] getIntentFilterVerificationBackup(int userId) { 14869 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14870 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14871 } 14872 14873 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14874 try { 14875 final XmlSerializer serializer = new FastXmlSerializer(); 14876 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14877 serializer.startDocument(null, true); 14878 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14879 14880 synchronized (mPackages) { 14881 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14882 } 14883 14884 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14885 serializer.endDocument(); 14886 serializer.flush(); 14887 } catch (Exception e) { 14888 if (DEBUG_BACKUP) { 14889 Slog.e(TAG, "Unable to write default apps for backup", e); 14890 } 14891 return null; 14892 } 14893 14894 return dataStream.toByteArray(); 14895 } 14896 14897 @Override 14898 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14899 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14900 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14901 } 14902 14903 try { 14904 final XmlPullParser parser = Xml.newPullParser(); 14905 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14906 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14907 new BlobXmlRestorer() { 14908 @Override 14909 public void apply(XmlPullParser parser, int userId) 14910 throws XmlPullParserException, IOException { 14911 synchronized (mPackages) { 14912 mSettings.readAllDomainVerificationsLPr(parser, userId); 14913 mSettings.writeLPr(); 14914 } 14915 } 14916 } ); 14917 } catch (Exception e) { 14918 if (DEBUG_BACKUP) { 14919 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14920 } 14921 } 14922 } 14923 14924 @Override 14925 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14926 int sourceUserId, int targetUserId, int flags) { 14927 mContext.enforceCallingOrSelfPermission( 14928 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14929 int callingUid = Binder.getCallingUid(); 14930 enforceOwnerRights(ownerPackage, callingUid); 14931 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14932 if (intentFilter.countActions() == 0) { 14933 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14934 return; 14935 } 14936 synchronized (mPackages) { 14937 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14938 ownerPackage, targetUserId, flags); 14939 CrossProfileIntentResolver resolver = 14940 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14941 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14942 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14943 if (existing != null) { 14944 int size = existing.size(); 14945 for (int i = 0; i < size; i++) { 14946 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14947 return; 14948 } 14949 } 14950 } 14951 resolver.addFilter(newFilter); 14952 scheduleWritePackageRestrictionsLocked(sourceUserId); 14953 } 14954 } 14955 14956 @Override 14957 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14958 mContext.enforceCallingOrSelfPermission( 14959 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14960 int callingUid = Binder.getCallingUid(); 14961 enforceOwnerRights(ownerPackage, callingUid); 14962 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14963 synchronized (mPackages) { 14964 CrossProfileIntentResolver resolver = 14965 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14966 ArraySet<CrossProfileIntentFilter> set = 14967 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14968 for (CrossProfileIntentFilter filter : set) { 14969 if (filter.getOwnerPackage().equals(ownerPackage)) { 14970 resolver.removeFilter(filter); 14971 } 14972 } 14973 scheduleWritePackageRestrictionsLocked(sourceUserId); 14974 } 14975 } 14976 14977 // Enforcing that callingUid is owning pkg on userId 14978 private void enforceOwnerRights(String pkg, int callingUid) { 14979 // The system owns everything. 14980 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14981 return; 14982 } 14983 int callingUserId = UserHandle.getUserId(callingUid); 14984 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14985 if (pi == null) { 14986 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14987 + callingUserId); 14988 } 14989 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14990 throw new SecurityException("Calling uid " + callingUid 14991 + " does not own package " + pkg); 14992 } 14993 } 14994 14995 @Override 14996 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14997 Intent intent = new Intent(Intent.ACTION_MAIN); 14998 intent.addCategory(Intent.CATEGORY_HOME); 14999 15000 final int callingUserId = UserHandle.getCallingUserId(); 15001 List<ResolveInfo> list = queryIntentActivities(intent, null, 15002 PackageManager.GET_META_DATA, callingUserId); 15003 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15004 true, false, false, callingUserId); 15005 15006 allHomeCandidates.clear(); 15007 if (list != null) { 15008 for (ResolveInfo ri : list) { 15009 allHomeCandidates.add(ri); 15010 } 15011 } 15012 return (preferred == null || preferred.activityInfo == null) 15013 ? null 15014 : new ComponentName(preferred.activityInfo.packageName, 15015 preferred.activityInfo.name); 15016 } 15017 15018 @Override 15019 public void setApplicationEnabledSetting(String appPackageName, 15020 int newState, int flags, int userId, String callingPackage) { 15021 if (!sUserManager.exists(userId)) return; 15022 if (callingPackage == null) { 15023 callingPackage = Integer.toString(Binder.getCallingUid()); 15024 } 15025 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15026 } 15027 15028 @Override 15029 public void setComponentEnabledSetting(ComponentName componentName, 15030 int newState, int flags, int userId) { 15031 if (!sUserManager.exists(userId)) return; 15032 setEnabledSetting(componentName.getPackageName(), 15033 componentName.getClassName(), newState, flags, userId, null); 15034 } 15035 15036 private void setEnabledSetting(final String packageName, String className, int newState, 15037 final int flags, int userId, String callingPackage) { 15038 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15039 || newState == COMPONENT_ENABLED_STATE_ENABLED 15040 || newState == COMPONENT_ENABLED_STATE_DISABLED 15041 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15042 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15043 throw new IllegalArgumentException("Invalid new component state: " 15044 + newState); 15045 } 15046 PackageSetting pkgSetting; 15047 final int uid = Binder.getCallingUid(); 15048 final int permission = mContext.checkCallingOrSelfPermission( 15049 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15050 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15051 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15052 boolean sendNow = false; 15053 boolean isApp = (className == null); 15054 String componentName = isApp ? packageName : className; 15055 int packageUid = -1; 15056 ArrayList<String> components; 15057 15058 // writer 15059 synchronized (mPackages) { 15060 pkgSetting = mSettings.mPackages.get(packageName); 15061 if (pkgSetting == null) { 15062 if (className == null) { 15063 throw new IllegalArgumentException( 15064 "Unknown package: " + packageName); 15065 } 15066 throw new IllegalArgumentException( 15067 "Unknown component: " + packageName 15068 + "/" + className); 15069 } 15070 // Allow root and verify that userId is not being specified by a different user 15071 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15072 throw new SecurityException( 15073 "Permission Denial: attempt to change component state from pid=" 15074 + Binder.getCallingPid() 15075 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15076 } 15077 if (className == null) { 15078 // We're dealing with an application/package level state change 15079 if (pkgSetting.getEnabled(userId) == newState) { 15080 // Nothing to do 15081 return; 15082 } 15083 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15084 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15085 // Don't care about who enables an app. 15086 callingPackage = null; 15087 } 15088 pkgSetting.setEnabled(newState, userId, callingPackage); 15089 // pkgSetting.pkg.mSetEnabled = newState; 15090 } else { 15091 // We're dealing with a component level state change 15092 // First, verify that this is a valid class name. 15093 PackageParser.Package pkg = pkgSetting.pkg; 15094 if (pkg == null || !pkg.hasComponentClassName(className)) { 15095 if (pkg != null && 15096 pkg.applicationInfo.targetSdkVersion >= 15097 Build.VERSION_CODES.JELLY_BEAN) { 15098 throw new IllegalArgumentException("Component class " + className 15099 + " does not exist in " + packageName); 15100 } else { 15101 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15102 + className + " does not exist in " + packageName); 15103 } 15104 } 15105 switch (newState) { 15106 case COMPONENT_ENABLED_STATE_ENABLED: 15107 if (!pkgSetting.enableComponentLPw(className, userId)) { 15108 return; 15109 } 15110 break; 15111 case COMPONENT_ENABLED_STATE_DISABLED: 15112 if (!pkgSetting.disableComponentLPw(className, userId)) { 15113 return; 15114 } 15115 break; 15116 case COMPONENT_ENABLED_STATE_DEFAULT: 15117 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15118 return; 15119 } 15120 break; 15121 default: 15122 Slog.e(TAG, "Invalid new component state: " + newState); 15123 return; 15124 } 15125 } 15126 scheduleWritePackageRestrictionsLocked(userId); 15127 components = mPendingBroadcasts.get(userId, packageName); 15128 final boolean newPackage = components == null; 15129 if (newPackage) { 15130 components = new ArrayList<String>(); 15131 } 15132 if (!components.contains(componentName)) { 15133 components.add(componentName); 15134 } 15135 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15136 sendNow = true; 15137 // Purge entry from pending broadcast list if another one exists already 15138 // since we are sending one right away. 15139 mPendingBroadcasts.remove(userId, packageName); 15140 } else { 15141 if (newPackage) { 15142 mPendingBroadcasts.put(userId, packageName, components); 15143 } 15144 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15145 // Schedule a message 15146 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15147 } 15148 } 15149 } 15150 15151 long callingId = Binder.clearCallingIdentity(); 15152 try { 15153 if (sendNow) { 15154 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15155 sendPackageChangedBroadcast(packageName, 15156 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15157 } 15158 } finally { 15159 Binder.restoreCallingIdentity(callingId); 15160 } 15161 } 15162 15163 private void sendPackageChangedBroadcast(String packageName, 15164 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15165 if (DEBUG_INSTALL) 15166 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15167 + componentNames); 15168 Bundle extras = new Bundle(4); 15169 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15170 String nameList[] = new String[componentNames.size()]; 15171 componentNames.toArray(nameList); 15172 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15173 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15174 extras.putInt(Intent.EXTRA_UID, packageUid); 15175 // If this is not reporting a change of the overall package, then only send it 15176 // to registered receivers. We don't want to launch a swath of apps for every 15177 // little component state change. 15178 final int flags = !componentNames.contains(packageName) 15179 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15180 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15181 new int[] {UserHandle.getUserId(packageUid)}); 15182 } 15183 15184 @Override 15185 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15186 if (!sUserManager.exists(userId)) return; 15187 final int uid = Binder.getCallingUid(); 15188 final int permission = mContext.checkCallingOrSelfPermission( 15189 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15190 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15191 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15192 // writer 15193 synchronized (mPackages) { 15194 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15195 allowedByPermission, uid, userId)) { 15196 scheduleWritePackageRestrictionsLocked(userId); 15197 } 15198 } 15199 } 15200 15201 @Override 15202 public String getInstallerPackageName(String packageName) { 15203 // reader 15204 synchronized (mPackages) { 15205 return mSettings.getInstallerPackageNameLPr(packageName); 15206 } 15207 } 15208 15209 @Override 15210 public int getApplicationEnabledSetting(String packageName, int userId) { 15211 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15212 int uid = Binder.getCallingUid(); 15213 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15214 // reader 15215 synchronized (mPackages) { 15216 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15217 } 15218 } 15219 15220 @Override 15221 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15222 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15223 int uid = Binder.getCallingUid(); 15224 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15225 // reader 15226 synchronized (mPackages) { 15227 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15228 } 15229 } 15230 15231 @Override 15232 public void enterSafeMode() { 15233 enforceSystemOrRoot("Only the system can request entering safe mode"); 15234 15235 if (!mSystemReady) { 15236 mSafeMode = true; 15237 } 15238 } 15239 15240 @Override 15241 public void systemReady() { 15242 mSystemReady = true; 15243 15244 // Read the compatibilty setting when the system is ready. 15245 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15246 mContext.getContentResolver(), 15247 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15248 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15249 if (DEBUG_SETTINGS) { 15250 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15251 } 15252 15253 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15254 15255 synchronized (mPackages) { 15256 // Verify that all of the preferred activity components actually 15257 // exist. It is possible for applications to be updated and at 15258 // that point remove a previously declared activity component that 15259 // had been set as a preferred activity. We try to clean this up 15260 // the next time we encounter that preferred activity, but it is 15261 // possible for the user flow to never be able to return to that 15262 // situation so here we do a sanity check to make sure we haven't 15263 // left any junk around. 15264 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15265 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15266 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15267 removed.clear(); 15268 for (PreferredActivity pa : pir.filterSet()) { 15269 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15270 removed.add(pa); 15271 } 15272 } 15273 if (removed.size() > 0) { 15274 for (int r=0; r<removed.size(); r++) { 15275 PreferredActivity pa = removed.get(r); 15276 Slog.w(TAG, "Removing dangling preferred activity: " 15277 + pa.mPref.mComponent); 15278 pir.removeFilter(pa); 15279 } 15280 mSettings.writePackageRestrictionsLPr( 15281 mSettings.mPreferredActivities.keyAt(i)); 15282 } 15283 } 15284 15285 for (int userId : UserManagerService.getInstance().getUserIds()) { 15286 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15287 grantPermissionsUserIds = ArrayUtils.appendInt( 15288 grantPermissionsUserIds, userId); 15289 } 15290 } 15291 } 15292 sUserManager.systemReady(); 15293 15294 // If we upgraded grant all default permissions before kicking off. 15295 for (int userId : grantPermissionsUserIds) { 15296 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15297 } 15298 15299 // Kick off any messages waiting for system ready 15300 if (mPostSystemReadyMessages != null) { 15301 for (Message msg : mPostSystemReadyMessages) { 15302 msg.sendToTarget(); 15303 } 15304 mPostSystemReadyMessages = null; 15305 } 15306 15307 // Watch for external volumes that come and go over time 15308 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15309 storage.registerListener(mStorageListener); 15310 15311 mInstallerService.systemReady(); 15312 mPackageDexOptimizer.systemReady(); 15313 15314 MountServiceInternal mountServiceInternal = LocalServices.getService( 15315 MountServiceInternal.class); 15316 mountServiceInternal.addExternalStoragePolicy( 15317 new MountServiceInternal.ExternalStorageMountPolicy() { 15318 @Override 15319 public int getMountMode(int uid, String packageName) { 15320 if (Process.isIsolated(uid)) { 15321 return Zygote.MOUNT_EXTERNAL_NONE; 15322 } 15323 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15324 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15325 } 15326 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15327 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15328 } 15329 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15330 return Zygote.MOUNT_EXTERNAL_READ; 15331 } 15332 return Zygote.MOUNT_EXTERNAL_WRITE; 15333 } 15334 15335 @Override 15336 public boolean hasExternalStorage(int uid, String packageName) { 15337 return true; 15338 } 15339 }); 15340 } 15341 15342 @Override 15343 public boolean isSafeMode() { 15344 return mSafeMode; 15345 } 15346 15347 @Override 15348 public boolean hasSystemUidErrors() { 15349 return mHasSystemUidErrors; 15350 } 15351 15352 static String arrayToString(int[] array) { 15353 StringBuffer buf = new StringBuffer(128); 15354 buf.append('['); 15355 if (array != null) { 15356 for (int i=0; i<array.length; i++) { 15357 if (i > 0) buf.append(", "); 15358 buf.append(array[i]); 15359 } 15360 } 15361 buf.append(']'); 15362 return buf.toString(); 15363 } 15364 15365 static class DumpState { 15366 public static final int DUMP_LIBS = 1 << 0; 15367 public static final int DUMP_FEATURES = 1 << 1; 15368 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15369 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15370 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15371 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15372 public static final int DUMP_PERMISSIONS = 1 << 6; 15373 public static final int DUMP_PACKAGES = 1 << 7; 15374 public static final int DUMP_SHARED_USERS = 1 << 8; 15375 public static final int DUMP_MESSAGES = 1 << 9; 15376 public static final int DUMP_PROVIDERS = 1 << 10; 15377 public static final int DUMP_VERIFIERS = 1 << 11; 15378 public static final int DUMP_PREFERRED = 1 << 12; 15379 public static final int DUMP_PREFERRED_XML = 1 << 13; 15380 public static final int DUMP_KEYSETS = 1 << 14; 15381 public static final int DUMP_VERSION = 1 << 15; 15382 public static final int DUMP_INSTALLS = 1 << 16; 15383 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15384 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15385 15386 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15387 15388 private int mTypes; 15389 15390 private int mOptions; 15391 15392 private boolean mTitlePrinted; 15393 15394 private SharedUserSetting mSharedUser; 15395 15396 public boolean isDumping(int type) { 15397 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15398 return true; 15399 } 15400 15401 return (mTypes & type) != 0; 15402 } 15403 15404 public void setDump(int type) { 15405 mTypes |= type; 15406 } 15407 15408 public boolean isOptionEnabled(int option) { 15409 return (mOptions & option) != 0; 15410 } 15411 15412 public void setOptionEnabled(int option) { 15413 mOptions |= option; 15414 } 15415 15416 public boolean onTitlePrinted() { 15417 final boolean printed = mTitlePrinted; 15418 mTitlePrinted = true; 15419 return printed; 15420 } 15421 15422 public boolean getTitlePrinted() { 15423 return mTitlePrinted; 15424 } 15425 15426 public void setTitlePrinted(boolean enabled) { 15427 mTitlePrinted = enabled; 15428 } 15429 15430 public SharedUserSetting getSharedUser() { 15431 return mSharedUser; 15432 } 15433 15434 public void setSharedUser(SharedUserSetting user) { 15435 mSharedUser = user; 15436 } 15437 } 15438 15439 @Override 15440 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15441 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15442 (new PackageManagerShellCommand(this)).exec( 15443 this, in, out, err, args, resultReceiver); 15444 } 15445 15446 @Override 15447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15448 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15449 != PackageManager.PERMISSION_GRANTED) { 15450 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15451 + Binder.getCallingPid() 15452 + ", uid=" + Binder.getCallingUid() 15453 + " without permission " 15454 + android.Manifest.permission.DUMP); 15455 return; 15456 } 15457 15458 DumpState dumpState = new DumpState(); 15459 boolean fullPreferred = false; 15460 boolean checkin = false; 15461 15462 String packageName = null; 15463 ArraySet<String> permissionNames = null; 15464 15465 int opti = 0; 15466 while (opti < args.length) { 15467 String opt = args[opti]; 15468 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15469 break; 15470 } 15471 opti++; 15472 15473 if ("-a".equals(opt)) { 15474 // Right now we only know how to print all. 15475 } else if ("-h".equals(opt)) { 15476 pw.println("Package manager dump options:"); 15477 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15478 pw.println(" --checkin: dump for a checkin"); 15479 pw.println(" -f: print details of intent filters"); 15480 pw.println(" -h: print this help"); 15481 pw.println(" cmd may be one of:"); 15482 pw.println(" l[ibraries]: list known shared libraries"); 15483 pw.println(" f[eatures]: list device features"); 15484 pw.println(" k[eysets]: print known keysets"); 15485 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15486 pw.println(" perm[issions]: dump permissions"); 15487 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15488 pw.println(" pref[erred]: print preferred package settings"); 15489 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15490 pw.println(" prov[iders]: dump content providers"); 15491 pw.println(" p[ackages]: dump installed packages"); 15492 pw.println(" s[hared-users]: dump shared user IDs"); 15493 pw.println(" m[essages]: print collected runtime messages"); 15494 pw.println(" v[erifiers]: print package verifier info"); 15495 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15496 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15497 pw.println(" version: print database version info"); 15498 pw.println(" write: write current settings now"); 15499 pw.println(" installs: details about install sessions"); 15500 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15501 pw.println(" <package.name>: info about given package"); 15502 return; 15503 } else if ("--checkin".equals(opt)) { 15504 checkin = true; 15505 } else if ("-f".equals(opt)) { 15506 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15507 } else { 15508 pw.println("Unknown argument: " + opt + "; use -h for help"); 15509 } 15510 } 15511 15512 // Is the caller requesting to dump a particular piece of data? 15513 if (opti < args.length) { 15514 String cmd = args[opti]; 15515 opti++; 15516 // Is this a package name? 15517 if ("android".equals(cmd) || cmd.contains(".")) { 15518 packageName = cmd; 15519 // When dumping a single package, we always dump all of its 15520 // filter information since the amount of data will be reasonable. 15521 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15522 } else if ("check-permission".equals(cmd)) { 15523 if (opti >= args.length) { 15524 pw.println("Error: check-permission missing permission argument"); 15525 return; 15526 } 15527 String perm = args[opti]; 15528 opti++; 15529 if (opti >= args.length) { 15530 pw.println("Error: check-permission missing package argument"); 15531 return; 15532 } 15533 String pkg = args[opti]; 15534 opti++; 15535 int user = UserHandle.getUserId(Binder.getCallingUid()); 15536 if (opti < args.length) { 15537 try { 15538 user = Integer.parseInt(args[opti]); 15539 } catch (NumberFormatException e) { 15540 pw.println("Error: check-permission user argument is not a number: " 15541 + args[opti]); 15542 return; 15543 } 15544 } 15545 pw.println(checkPermission(perm, pkg, user)); 15546 return; 15547 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15548 dumpState.setDump(DumpState.DUMP_LIBS); 15549 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15550 dumpState.setDump(DumpState.DUMP_FEATURES); 15551 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15552 if (opti >= args.length) { 15553 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15554 | DumpState.DUMP_SERVICE_RESOLVERS 15555 | DumpState.DUMP_RECEIVER_RESOLVERS 15556 | DumpState.DUMP_CONTENT_RESOLVERS); 15557 } else { 15558 while (opti < args.length) { 15559 String name = args[opti]; 15560 if ("a".equals(name) || "activity".equals(name)) { 15561 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15562 } else if ("s".equals(name) || "service".equals(name)) { 15563 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15564 } else if ("r".equals(name) || "receiver".equals(name)) { 15565 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15566 } else if ("c".equals(name) || "content".equals(name)) { 15567 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15568 } else { 15569 pw.println("Error: unknown resolver table type: " + name); 15570 return; 15571 } 15572 opti++; 15573 } 15574 } 15575 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15576 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15577 } else if ("permission".equals(cmd)) { 15578 if (opti >= args.length) { 15579 pw.println("Error: permission requires permission name"); 15580 return; 15581 } 15582 permissionNames = new ArraySet<>(); 15583 while (opti < args.length) { 15584 permissionNames.add(args[opti]); 15585 opti++; 15586 } 15587 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15588 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15589 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15590 dumpState.setDump(DumpState.DUMP_PREFERRED); 15591 } else if ("preferred-xml".equals(cmd)) { 15592 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15593 if (opti < args.length && "--full".equals(args[opti])) { 15594 fullPreferred = true; 15595 opti++; 15596 } 15597 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15598 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15599 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15600 dumpState.setDump(DumpState.DUMP_PACKAGES); 15601 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15602 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15603 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15604 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15605 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15606 dumpState.setDump(DumpState.DUMP_MESSAGES); 15607 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15608 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15609 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15610 || "intent-filter-verifiers".equals(cmd)) { 15611 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15612 } else if ("version".equals(cmd)) { 15613 dumpState.setDump(DumpState.DUMP_VERSION); 15614 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15615 dumpState.setDump(DumpState.DUMP_KEYSETS); 15616 } else if ("installs".equals(cmd)) { 15617 dumpState.setDump(DumpState.DUMP_INSTALLS); 15618 } else if ("write".equals(cmd)) { 15619 synchronized (mPackages) { 15620 mSettings.writeLPr(); 15621 pw.println("Settings written."); 15622 return; 15623 } 15624 } 15625 } 15626 15627 if (checkin) { 15628 pw.println("vers,1"); 15629 } 15630 15631 // reader 15632 synchronized (mPackages) { 15633 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15634 if (!checkin) { 15635 if (dumpState.onTitlePrinted()) 15636 pw.println(); 15637 pw.println("Database versions:"); 15638 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15639 } 15640 } 15641 15642 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15643 if (!checkin) { 15644 if (dumpState.onTitlePrinted()) 15645 pw.println(); 15646 pw.println("Verifiers:"); 15647 pw.print(" Required: "); 15648 pw.print(mRequiredVerifierPackage); 15649 pw.print(" (uid="); 15650 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15651 pw.println(")"); 15652 } else if (mRequiredVerifierPackage != null) { 15653 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15654 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15655 } 15656 } 15657 15658 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15659 packageName == null) { 15660 if (mIntentFilterVerifierComponent != null) { 15661 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15662 if (!checkin) { 15663 if (dumpState.onTitlePrinted()) 15664 pw.println(); 15665 pw.println("Intent Filter Verifier:"); 15666 pw.print(" Using: "); 15667 pw.print(verifierPackageName); 15668 pw.print(" (uid="); 15669 pw.print(getPackageUid(verifierPackageName, 0)); 15670 pw.println(")"); 15671 } else if (verifierPackageName != null) { 15672 pw.print("ifv,"); pw.print(verifierPackageName); 15673 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15674 } 15675 } else { 15676 pw.println(); 15677 pw.println("No Intent Filter Verifier available!"); 15678 } 15679 } 15680 15681 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15682 boolean printedHeader = false; 15683 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15684 while (it.hasNext()) { 15685 String name = it.next(); 15686 SharedLibraryEntry ent = mSharedLibraries.get(name); 15687 if (!checkin) { 15688 if (!printedHeader) { 15689 if (dumpState.onTitlePrinted()) 15690 pw.println(); 15691 pw.println("Libraries:"); 15692 printedHeader = true; 15693 } 15694 pw.print(" "); 15695 } else { 15696 pw.print("lib,"); 15697 } 15698 pw.print(name); 15699 if (!checkin) { 15700 pw.print(" -> "); 15701 } 15702 if (ent.path != null) { 15703 if (!checkin) { 15704 pw.print("(jar) "); 15705 pw.print(ent.path); 15706 } else { 15707 pw.print(",jar,"); 15708 pw.print(ent.path); 15709 } 15710 } else { 15711 if (!checkin) { 15712 pw.print("(apk) "); 15713 pw.print(ent.apk); 15714 } else { 15715 pw.print(",apk,"); 15716 pw.print(ent.apk); 15717 } 15718 } 15719 pw.println(); 15720 } 15721 } 15722 15723 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15724 if (dumpState.onTitlePrinted()) 15725 pw.println(); 15726 if (!checkin) { 15727 pw.println("Features:"); 15728 } 15729 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15730 while (it.hasNext()) { 15731 String name = it.next(); 15732 if (!checkin) { 15733 pw.print(" "); 15734 } else { 15735 pw.print("feat,"); 15736 } 15737 pw.println(name); 15738 } 15739 } 15740 15741 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15742 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15743 : "Activity Resolver Table:", " ", packageName, 15744 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15745 dumpState.setTitlePrinted(true); 15746 } 15747 } 15748 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15749 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15750 : "Receiver Resolver Table:", " ", packageName, 15751 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15752 dumpState.setTitlePrinted(true); 15753 } 15754 } 15755 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15756 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15757 : "Service Resolver Table:", " ", packageName, 15758 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15759 dumpState.setTitlePrinted(true); 15760 } 15761 } 15762 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15763 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15764 : "Provider Resolver Table:", " ", packageName, 15765 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15766 dumpState.setTitlePrinted(true); 15767 } 15768 } 15769 15770 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15771 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15772 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15773 int user = mSettings.mPreferredActivities.keyAt(i); 15774 if (pir.dump(pw, 15775 dumpState.getTitlePrinted() 15776 ? "\nPreferred Activities User " + user + ":" 15777 : "Preferred Activities User " + user + ":", " ", 15778 packageName, true, false)) { 15779 dumpState.setTitlePrinted(true); 15780 } 15781 } 15782 } 15783 15784 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15785 pw.flush(); 15786 FileOutputStream fout = new FileOutputStream(fd); 15787 BufferedOutputStream str = new BufferedOutputStream(fout); 15788 XmlSerializer serializer = new FastXmlSerializer(); 15789 try { 15790 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15791 serializer.startDocument(null, true); 15792 serializer.setFeature( 15793 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15794 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15795 serializer.endDocument(); 15796 serializer.flush(); 15797 } catch (IllegalArgumentException e) { 15798 pw.println("Failed writing: " + e); 15799 } catch (IllegalStateException e) { 15800 pw.println("Failed writing: " + e); 15801 } catch (IOException e) { 15802 pw.println("Failed writing: " + e); 15803 } 15804 } 15805 15806 if (!checkin 15807 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15808 && packageName == null) { 15809 pw.println(); 15810 int count = mSettings.mPackages.size(); 15811 if (count == 0) { 15812 pw.println("No applications!"); 15813 pw.println(); 15814 } else { 15815 final String prefix = " "; 15816 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15817 if (allPackageSettings.size() == 0) { 15818 pw.println("No domain preferred apps!"); 15819 pw.println(); 15820 } else { 15821 pw.println("App verification status:"); 15822 pw.println(); 15823 count = 0; 15824 for (PackageSetting ps : allPackageSettings) { 15825 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15826 if (ivi == null || ivi.getPackageName() == null) continue; 15827 pw.println(prefix + "Package: " + ivi.getPackageName()); 15828 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15829 pw.println(prefix + "Status: " + ivi.getStatusString()); 15830 pw.println(); 15831 count++; 15832 } 15833 if (count == 0) { 15834 pw.println(prefix + "No app verification established."); 15835 pw.println(); 15836 } 15837 for (int userId : sUserManager.getUserIds()) { 15838 pw.println("App linkages for user " + userId + ":"); 15839 pw.println(); 15840 count = 0; 15841 for (PackageSetting ps : allPackageSettings) { 15842 final long status = ps.getDomainVerificationStatusForUser(userId); 15843 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15844 continue; 15845 } 15846 pw.println(prefix + "Package: " + ps.name); 15847 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15848 String statusStr = IntentFilterVerificationInfo. 15849 getStatusStringFromValue(status); 15850 pw.println(prefix + "Status: " + statusStr); 15851 pw.println(); 15852 count++; 15853 } 15854 if (count == 0) { 15855 pw.println(prefix + "No configured app linkages."); 15856 pw.println(); 15857 } 15858 } 15859 } 15860 } 15861 } 15862 15863 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15864 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15865 if (packageName == null && permissionNames == null) { 15866 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15867 if (iperm == 0) { 15868 if (dumpState.onTitlePrinted()) 15869 pw.println(); 15870 pw.println("AppOp Permissions:"); 15871 } 15872 pw.print(" AppOp Permission "); 15873 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15874 pw.println(":"); 15875 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15876 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15877 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15878 } 15879 } 15880 } 15881 } 15882 15883 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15884 boolean printedSomething = false; 15885 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15886 if (packageName != null && !packageName.equals(p.info.packageName)) { 15887 continue; 15888 } 15889 if (!printedSomething) { 15890 if (dumpState.onTitlePrinted()) 15891 pw.println(); 15892 pw.println("Registered ContentProviders:"); 15893 printedSomething = true; 15894 } 15895 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15896 pw.print(" "); pw.println(p.toString()); 15897 } 15898 printedSomething = false; 15899 for (Map.Entry<String, PackageParser.Provider> entry : 15900 mProvidersByAuthority.entrySet()) { 15901 PackageParser.Provider p = entry.getValue(); 15902 if (packageName != null && !packageName.equals(p.info.packageName)) { 15903 continue; 15904 } 15905 if (!printedSomething) { 15906 if (dumpState.onTitlePrinted()) 15907 pw.println(); 15908 pw.println("ContentProvider Authorities:"); 15909 printedSomething = true; 15910 } 15911 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15912 pw.print(" "); pw.println(p.toString()); 15913 if (p.info != null && p.info.applicationInfo != null) { 15914 final String appInfo = p.info.applicationInfo.toString(); 15915 pw.print(" applicationInfo="); pw.println(appInfo); 15916 } 15917 } 15918 } 15919 15920 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15921 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15922 } 15923 15924 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15925 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15926 } 15927 15928 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15929 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15930 } 15931 15932 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15933 // XXX should handle packageName != null by dumping only install data that 15934 // the given package is involved with. 15935 if (dumpState.onTitlePrinted()) pw.println(); 15936 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15937 } 15938 15939 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15940 if (dumpState.onTitlePrinted()) pw.println(); 15941 mSettings.dumpReadMessagesLPr(pw, dumpState); 15942 15943 pw.println(); 15944 pw.println("Package warning messages:"); 15945 BufferedReader in = null; 15946 String line = null; 15947 try { 15948 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15949 while ((line = in.readLine()) != null) { 15950 if (line.contains("ignored: updated version")) continue; 15951 pw.println(line); 15952 } 15953 } catch (IOException ignored) { 15954 } finally { 15955 IoUtils.closeQuietly(in); 15956 } 15957 } 15958 15959 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15960 BufferedReader in = null; 15961 String line = null; 15962 try { 15963 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15964 while ((line = in.readLine()) != null) { 15965 if (line.contains("ignored: updated version")) continue; 15966 pw.print("msg,"); 15967 pw.println(line); 15968 } 15969 } catch (IOException ignored) { 15970 } finally { 15971 IoUtils.closeQuietly(in); 15972 } 15973 } 15974 } 15975 } 15976 15977 private String dumpDomainString(String packageName) { 15978 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15979 List<IntentFilter> filters = getAllIntentFilters(packageName); 15980 15981 ArraySet<String> result = new ArraySet<>(); 15982 if (iviList.size() > 0) { 15983 for (IntentFilterVerificationInfo ivi : iviList) { 15984 for (String host : ivi.getDomains()) { 15985 result.add(host); 15986 } 15987 } 15988 } 15989 if (filters != null && filters.size() > 0) { 15990 for (IntentFilter filter : filters) { 15991 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15992 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15993 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15994 result.addAll(filter.getHostsList()); 15995 } 15996 } 15997 } 15998 15999 StringBuilder sb = new StringBuilder(result.size() * 16); 16000 for (String domain : result) { 16001 if (sb.length() > 0) sb.append(" "); 16002 sb.append(domain); 16003 } 16004 return sb.toString(); 16005 } 16006 16007 // ------- apps on sdcard specific code ------- 16008 static final boolean DEBUG_SD_INSTALL = false; 16009 16010 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16011 16012 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16013 16014 private boolean mMediaMounted = false; 16015 16016 static String getEncryptKey() { 16017 try { 16018 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16019 SD_ENCRYPTION_KEYSTORE_NAME); 16020 if (sdEncKey == null) { 16021 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16022 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16023 if (sdEncKey == null) { 16024 Slog.e(TAG, "Failed to create encryption keys"); 16025 return null; 16026 } 16027 } 16028 return sdEncKey; 16029 } catch (NoSuchAlgorithmException nsae) { 16030 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16031 return null; 16032 } catch (IOException ioe) { 16033 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16034 return null; 16035 } 16036 } 16037 16038 /* 16039 * Update media status on PackageManager. 16040 */ 16041 @Override 16042 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16043 int callingUid = Binder.getCallingUid(); 16044 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16045 throw new SecurityException("Media status can only be updated by the system"); 16046 } 16047 // reader; this apparently protects mMediaMounted, but should probably 16048 // be a different lock in that case. 16049 synchronized (mPackages) { 16050 Log.i(TAG, "Updating external media status from " 16051 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16052 + (mediaStatus ? "mounted" : "unmounted")); 16053 if (DEBUG_SD_INSTALL) 16054 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16055 + ", mMediaMounted=" + mMediaMounted); 16056 if (mediaStatus == mMediaMounted) { 16057 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16058 : 0, -1); 16059 mHandler.sendMessage(msg); 16060 return; 16061 } 16062 mMediaMounted = mediaStatus; 16063 } 16064 // Queue up an async operation since the package installation may take a 16065 // little while. 16066 mHandler.post(new Runnable() { 16067 public void run() { 16068 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16069 } 16070 }); 16071 } 16072 16073 /** 16074 * Called by MountService when the initial ASECs to scan are available. 16075 * Should block until all the ASEC containers are finished being scanned. 16076 */ 16077 public void scanAvailableAsecs() { 16078 updateExternalMediaStatusInner(true, false, false); 16079 if (mShouldRestoreconData) { 16080 SELinuxMMAC.setRestoreconDone(); 16081 mShouldRestoreconData = false; 16082 } 16083 } 16084 16085 /* 16086 * Collect information of applications on external media, map them against 16087 * existing containers and update information based on current mount status. 16088 * Please note that we always have to report status if reportStatus has been 16089 * set to true especially when unloading packages. 16090 */ 16091 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16092 boolean externalStorage) { 16093 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16094 int[] uidArr = EmptyArray.INT; 16095 16096 final String[] list = PackageHelper.getSecureContainerList(); 16097 if (ArrayUtils.isEmpty(list)) { 16098 Log.i(TAG, "No secure containers found"); 16099 } else { 16100 // Process list of secure containers and categorize them 16101 // as active or stale based on their package internal state. 16102 16103 // reader 16104 synchronized (mPackages) { 16105 for (String cid : list) { 16106 // Leave stages untouched for now; installer service owns them 16107 if (PackageInstallerService.isStageName(cid)) continue; 16108 16109 if (DEBUG_SD_INSTALL) 16110 Log.i(TAG, "Processing container " + cid); 16111 String pkgName = getAsecPackageName(cid); 16112 if (pkgName == null) { 16113 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16114 continue; 16115 } 16116 if (DEBUG_SD_INSTALL) 16117 Log.i(TAG, "Looking for pkg : " + pkgName); 16118 16119 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16120 if (ps == null) { 16121 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16122 continue; 16123 } 16124 16125 /* 16126 * Skip packages that are not external if we're unmounting 16127 * external storage. 16128 */ 16129 if (externalStorage && !isMounted && !isExternal(ps)) { 16130 continue; 16131 } 16132 16133 final AsecInstallArgs args = new AsecInstallArgs(cid, 16134 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16135 // The package status is changed only if the code path 16136 // matches between settings and the container id. 16137 if (ps.codePathString != null 16138 && ps.codePathString.startsWith(args.getCodePath())) { 16139 if (DEBUG_SD_INSTALL) { 16140 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16141 + " at code path: " + ps.codePathString); 16142 } 16143 16144 // We do have a valid package installed on sdcard 16145 processCids.put(args, ps.codePathString); 16146 final int uid = ps.appId; 16147 if (uid != -1) { 16148 uidArr = ArrayUtils.appendInt(uidArr, uid); 16149 } 16150 } else { 16151 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16152 + ps.codePathString); 16153 } 16154 } 16155 } 16156 16157 Arrays.sort(uidArr); 16158 } 16159 16160 // Process packages with valid entries. 16161 if (isMounted) { 16162 if (DEBUG_SD_INSTALL) 16163 Log.i(TAG, "Loading packages"); 16164 loadMediaPackages(processCids, uidArr, externalStorage); 16165 startCleaningPackages(); 16166 mInstallerService.onSecureContainersAvailable(); 16167 } else { 16168 if (DEBUG_SD_INSTALL) 16169 Log.i(TAG, "Unloading packages"); 16170 unloadMediaPackages(processCids, uidArr, reportStatus); 16171 } 16172 } 16173 16174 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16175 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16176 final int size = infos.size(); 16177 final String[] packageNames = new String[size]; 16178 final int[] packageUids = new int[size]; 16179 for (int i = 0; i < size; i++) { 16180 final ApplicationInfo info = infos.get(i); 16181 packageNames[i] = info.packageName; 16182 packageUids[i] = info.uid; 16183 } 16184 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16185 finishedReceiver); 16186 } 16187 16188 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16189 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16190 sendResourcesChangedBroadcast(mediaStatus, replacing, 16191 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16192 } 16193 16194 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16195 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16196 int size = pkgList.length; 16197 if (size > 0) { 16198 // Send broadcasts here 16199 Bundle extras = new Bundle(); 16200 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16201 if (uidArr != null) { 16202 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16203 } 16204 if (replacing) { 16205 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16206 } 16207 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16208 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16209 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16210 } 16211 } 16212 16213 /* 16214 * Look at potentially valid container ids from processCids If package 16215 * information doesn't match the one on record or package scanning fails, 16216 * the cid is added to list of removeCids. We currently don't delete stale 16217 * containers. 16218 */ 16219 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16220 boolean externalStorage) { 16221 ArrayList<String> pkgList = new ArrayList<String>(); 16222 Set<AsecInstallArgs> keys = processCids.keySet(); 16223 16224 for (AsecInstallArgs args : keys) { 16225 String codePath = processCids.get(args); 16226 if (DEBUG_SD_INSTALL) 16227 Log.i(TAG, "Loading container : " + args.cid); 16228 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16229 try { 16230 // Make sure there are no container errors first. 16231 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16232 Slog.e(TAG, "Failed to mount cid : " + args.cid 16233 + " when installing from sdcard"); 16234 continue; 16235 } 16236 // Check code path here. 16237 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16238 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16239 + " does not match one in settings " + codePath); 16240 continue; 16241 } 16242 // Parse package 16243 int parseFlags = mDefParseFlags; 16244 if (args.isExternalAsec()) { 16245 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16246 } 16247 if (args.isFwdLocked()) { 16248 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16249 } 16250 16251 synchronized (mInstallLock) { 16252 PackageParser.Package pkg = null; 16253 try { 16254 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16255 } catch (PackageManagerException e) { 16256 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16257 } 16258 // Scan the package 16259 if (pkg != null) { 16260 /* 16261 * TODO why is the lock being held? doPostInstall is 16262 * called in other places without the lock. This needs 16263 * to be straightened out. 16264 */ 16265 // writer 16266 synchronized (mPackages) { 16267 retCode = PackageManager.INSTALL_SUCCEEDED; 16268 pkgList.add(pkg.packageName); 16269 // Post process args 16270 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16271 pkg.applicationInfo.uid); 16272 } 16273 } else { 16274 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16275 } 16276 } 16277 16278 } finally { 16279 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16280 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16281 } 16282 } 16283 } 16284 // writer 16285 synchronized (mPackages) { 16286 // If the platform SDK has changed since the last time we booted, 16287 // we need to re-grant app permission to catch any new ones that 16288 // appear. This is really a hack, and means that apps can in some 16289 // cases get permissions that the user didn't initially explicitly 16290 // allow... it would be nice to have some better way to handle 16291 // this situation. 16292 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16293 : mSettings.getInternalVersion(); 16294 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16295 : StorageManager.UUID_PRIVATE_INTERNAL; 16296 16297 int updateFlags = UPDATE_PERMISSIONS_ALL; 16298 if (ver.sdkVersion != mSdkVersion) { 16299 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16300 + mSdkVersion + "; regranting permissions for external"); 16301 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16302 } 16303 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16304 16305 // Yay, everything is now upgraded 16306 ver.forceCurrent(); 16307 16308 // can downgrade to reader 16309 // Persist settings 16310 mSettings.writeLPr(); 16311 } 16312 // Send a broadcast to let everyone know we are done processing 16313 if (pkgList.size() > 0) { 16314 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16315 } 16316 } 16317 16318 /* 16319 * Utility method to unload a list of specified containers 16320 */ 16321 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16322 // Just unmount all valid containers. 16323 for (AsecInstallArgs arg : cidArgs) { 16324 synchronized (mInstallLock) { 16325 arg.doPostDeleteLI(false); 16326 } 16327 } 16328 } 16329 16330 /* 16331 * Unload packages mounted on external media. This involves deleting package 16332 * data from internal structures, sending broadcasts about diabled packages, 16333 * gc'ing to free up references, unmounting all secure containers 16334 * corresponding to packages on external media, and posting a 16335 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16336 * that we always have to post this message if status has been requested no 16337 * matter what. 16338 */ 16339 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16340 final boolean reportStatus) { 16341 if (DEBUG_SD_INSTALL) 16342 Log.i(TAG, "unloading media packages"); 16343 ArrayList<String> pkgList = new ArrayList<String>(); 16344 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16345 final Set<AsecInstallArgs> keys = processCids.keySet(); 16346 for (AsecInstallArgs args : keys) { 16347 String pkgName = args.getPackageName(); 16348 if (DEBUG_SD_INSTALL) 16349 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16350 // Delete package internally 16351 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16352 synchronized (mInstallLock) { 16353 boolean res = deletePackageLI(pkgName, null, false, null, null, 16354 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16355 if (res) { 16356 pkgList.add(pkgName); 16357 } else { 16358 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16359 failedList.add(args); 16360 } 16361 } 16362 } 16363 16364 // reader 16365 synchronized (mPackages) { 16366 // We didn't update the settings after removing each package; 16367 // write them now for all packages. 16368 mSettings.writeLPr(); 16369 } 16370 16371 // We have to absolutely send UPDATED_MEDIA_STATUS only 16372 // after confirming that all the receivers processed the ordered 16373 // broadcast when packages get disabled, force a gc to clean things up. 16374 // and unload all the containers. 16375 if (pkgList.size() > 0) { 16376 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16377 new IIntentReceiver.Stub() { 16378 public void performReceive(Intent intent, int resultCode, String data, 16379 Bundle extras, boolean ordered, boolean sticky, 16380 int sendingUser) throws RemoteException { 16381 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16382 reportStatus ? 1 : 0, 1, keys); 16383 mHandler.sendMessage(msg); 16384 } 16385 }); 16386 } else { 16387 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16388 keys); 16389 mHandler.sendMessage(msg); 16390 } 16391 } 16392 16393 private void loadPrivatePackages(final VolumeInfo vol) { 16394 mHandler.post(new Runnable() { 16395 @Override 16396 public void run() { 16397 loadPrivatePackagesInner(vol); 16398 } 16399 }); 16400 } 16401 16402 private void loadPrivatePackagesInner(VolumeInfo vol) { 16403 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16404 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16405 16406 final VersionInfo ver; 16407 final List<PackageSetting> packages; 16408 synchronized (mPackages) { 16409 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16410 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16411 } 16412 16413 for (PackageSetting ps : packages) { 16414 synchronized (mInstallLock) { 16415 final PackageParser.Package pkg; 16416 try { 16417 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16418 loaded.add(pkg.applicationInfo); 16419 } catch (PackageManagerException e) { 16420 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16421 } 16422 16423 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16424 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16425 } 16426 } 16427 } 16428 16429 synchronized (mPackages) { 16430 int updateFlags = UPDATE_PERMISSIONS_ALL; 16431 if (ver.sdkVersion != mSdkVersion) { 16432 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16433 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16434 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16435 } 16436 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16437 16438 // Yay, everything is now upgraded 16439 ver.forceCurrent(); 16440 16441 mSettings.writeLPr(); 16442 } 16443 16444 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16445 sendResourcesChangedBroadcast(true, false, loaded, null); 16446 } 16447 16448 private void unloadPrivatePackages(final VolumeInfo vol) { 16449 mHandler.post(new Runnable() { 16450 @Override 16451 public void run() { 16452 unloadPrivatePackagesInner(vol); 16453 } 16454 }); 16455 } 16456 16457 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16458 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16459 synchronized (mInstallLock) { 16460 synchronized (mPackages) { 16461 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16462 for (PackageSetting ps : packages) { 16463 if (ps.pkg == null) continue; 16464 16465 final ApplicationInfo info = ps.pkg.applicationInfo; 16466 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16467 if (deletePackageLI(ps.name, null, false, null, null, 16468 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16469 unloaded.add(info); 16470 } else { 16471 Slog.w(TAG, "Failed to unload " + ps.codePath); 16472 } 16473 } 16474 16475 mSettings.writeLPr(); 16476 } 16477 } 16478 16479 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16480 sendResourcesChangedBroadcast(false, false, unloaded, null); 16481 } 16482 16483 /** 16484 * Examine all users present on given mounted volume, and destroy data 16485 * belonging to users that are no longer valid, or whose user ID has been 16486 * recycled. 16487 */ 16488 private void reconcileUsers(String volumeUuid) { 16489 final File[] files = FileUtils 16490 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16491 for (File file : files) { 16492 if (!file.isDirectory()) continue; 16493 16494 final int userId; 16495 final UserInfo info; 16496 try { 16497 userId = Integer.parseInt(file.getName()); 16498 info = sUserManager.getUserInfo(userId); 16499 } catch (NumberFormatException e) { 16500 Slog.w(TAG, "Invalid user directory " + file); 16501 continue; 16502 } 16503 16504 boolean destroyUser = false; 16505 if (info == null) { 16506 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16507 + " because no matching user was found"); 16508 destroyUser = true; 16509 } else { 16510 try { 16511 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16512 } catch (IOException e) { 16513 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16514 + " because we failed to enforce serial number: " + e); 16515 destroyUser = true; 16516 } 16517 } 16518 16519 if (destroyUser) { 16520 synchronized (mInstallLock) { 16521 mInstaller.removeUserDataDirs(volumeUuid, userId); 16522 } 16523 } 16524 } 16525 16526 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16527 final UserManager um = mContext.getSystemService(UserManager.class); 16528 for (UserInfo user : um.getUsers()) { 16529 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16530 if (userDir.exists()) continue; 16531 16532 try { 16533 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16534 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16535 } catch (IOException e) { 16536 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16537 } 16538 } 16539 } 16540 16541 /** 16542 * Examine all apps present on given mounted volume, and destroy apps that 16543 * aren't expected, either due to uninstallation or reinstallation on 16544 * another volume. 16545 */ 16546 private void reconcileApps(String volumeUuid) { 16547 final File[] files = FileUtils 16548 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16549 for (File file : files) { 16550 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16551 && !PackageInstallerService.isStageName(file.getName()); 16552 if (!isPackage) { 16553 // Ignore entries which are not packages 16554 continue; 16555 } 16556 16557 boolean destroyApp = false; 16558 String packageName = null; 16559 try { 16560 final PackageLite pkg = PackageParser.parsePackageLite(file, 16561 PackageParser.PARSE_MUST_BE_APK); 16562 packageName = pkg.packageName; 16563 16564 synchronized (mPackages) { 16565 final PackageSetting ps = mSettings.mPackages.get(packageName); 16566 if (ps == null) { 16567 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16568 + volumeUuid + " because we found no install record"); 16569 destroyApp = true; 16570 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16571 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16572 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16573 destroyApp = true; 16574 } 16575 } 16576 16577 } catch (PackageParserException e) { 16578 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16579 destroyApp = true; 16580 } 16581 16582 if (destroyApp) { 16583 synchronized (mInstallLock) { 16584 if (packageName != null) { 16585 removeDataDirsLI(volumeUuid, packageName); 16586 } 16587 if (file.isDirectory()) { 16588 mInstaller.rmPackageDir(file.getAbsolutePath()); 16589 } else { 16590 file.delete(); 16591 } 16592 } 16593 } 16594 } 16595 } 16596 16597 private void unfreezePackage(String packageName) { 16598 synchronized (mPackages) { 16599 final PackageSetting ps = mSettings.mPackages.get(packageName); 16600 if (ps != null) { 16601 ps.frozen = false; 16602 } 16603 } 16604 } 16605 16606 @Override 16607 public int movePackage(final String packageName, final String volumeUuid) { 16608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16609 16610 final int moveId = mNextMoveId.getAndIncrement(); 16611 mHandler.post(new Runnable() { 16612 @Override 16613 public void run() { 16614 try { 16615 movePackageInternal(packageName, volumeUuid, moveId); 16616 } catch (PackageManagerException e) { 16617 Slog.w(TAG, "Failed to move " + packageName, e); 16618 mMoveCallbacks.notifyStatusChanged(moveId, 16619 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16620 } 16621 } 16622 }); 16623 return moveId; 16624 } 16625 16626 private void movePackageInternal(final String packageName, final String volumeUuid, 16627 final int moveId) throws PackageManagerException { 16628 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16629 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16630 final PackageManager pm = mContext.getPackageManager(); 16631 16632 final boolean currentAsec; 16633 final String currentVolumeUuid; 16634 final File codeFile; 16635 final String installerPackageName; 16636 final String packageAbiOverride; 16637 final int appId; 16638 final String seinfo; 16639 final String label; 16640 16641 // reader 16642 synchronized (mPackages) { 16643 final PackageParser.Package pkg = mPackages.get(packageName); 16644 final PackageSetting ps = mSettings.mPackages.get(packageName); 16645 if (pkg == null || ps == null) { 16646 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16647 } 16648 16649 if (pkg.applicationInfo.isSystemApp()) { 16650 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16651 "Cannot move system application"); 16652 } 16653 16654 if (pkg.applicationInfo.isExternalAsec()) { 16655 currentAsec = true; 16656 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16657 } else if (pkg.applicationInfo.isForwardLocked()) { 16658 currentAsec = true; 16659 currentVolumeUuid = "forward_locked"; 16660 } else { 16661 currentAsec = false; 16662 currentVolumeUuid = ps.volumeUuid; 16663 16664 final File probe = new File(pkg.codePath); 16665 final File probeOat = new File(probe, "oat"); 16666 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16667 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16668 "Move only supported for modern cluster style installs"); 16669 } 16670 } 16671 16672 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16673 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16674 "Package already moved to " + volumeUuid); 16675 } 16676 16677 if (ps.frozen) { 16678 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16679 "Failed to move already frozen package"); 16680 } 16681 ps.frozen = true; 16682 16683 codeFile = new File(pkg.codePath); 16684 installerPackageName = ps.installerPackageName; 16685 packageAbiOverride = ps.cpuAbiOverrideString; 16686 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16687 seinfo = pkg.applicationInfo.seinfo; 16688 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16689 } 16690 16691 // Now that we're guarded by frozen state, kill app during move 16692 final long token = Binder.clearCallingIdentity(); 16693 try { 16694 killApplication(packageName, appId, "move pkg"); 16695 } finally { 16696 Binder.restoreCallingIdentity(token); 16697 } 16698 16699 final Bundle extras = new Bundle(); 16700 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16701 extras.putString(Intent.EXTRA_TITLE, label); 16702 mMoveCallbacks.notifyCreated(moveId, extras); 16703 16704 int installFlags; 16705 final boolean moveCompleteApp; 16706 final File measurePath; 16707 16708 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16709 installFlags = INSTALL_INTERNAL; 16710 moveCompleteApp = !currentAsec; 16711 measurePath = Environment.getDataAppDirectory(volumeUuid); 16712 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16713 installFlags = INSTALL_EXTERNAL; 16714 moveCompleteApp = false; 16715 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16716 } else { 16717 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16718 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16719 || !volume.isMountedWritable()) { 16720 unfreezePackage(packageName); 16721 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16722 "Move location not mounted private volume"); 16723 } 16724 16725 Preconditions.checkState(!currentAsec); 16726 16727 installFlags = INSTALL_INTERNAL; 16728 moveCompleteApp = true; 16729 measurePath = Environment.getDataAppDirectory(volumeUuid); 16730 } 16731 16732 final PackageStats stats = new PackageStats(null, -1); 16733 synchronized (mInstaller) { 16734 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16735 unfreezePackage(packageName); 16736 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16737 "Failed to measure package size"); 16738 } 16739 } 16740 16741 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16742 + stats.dataSize); 16743 16744 final long startFreeBytes = measurePath.getFreeSpace(); 16745 final long sizeBytes; 16746 if (moveCompleteApp) { 16747 sizeBytes = stats.codeSize + stats.dataSize; 16748 } else { 16749 sizeBytes = stats.codeSize; 16750 } 16751 16752 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16753 unfreezePackage(packageName); 16754 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16755 "Not enough free space to move"); 16756 } 16757 16758 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16759 16760 final CountDownLatch installedLatch = new CountDownLatch(1); 16761 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16762 @Override 16763 public void onUserActionRequired(Intent intent) throws RemoteException { 16764 throw new IllegalStateException(); 16765 } 16766 16767 @Override 16768 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16769 Bundle extras) throws RemoteException { 16770 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16771 + PackageManager.installStatusToString(returnCode, msg)); 16772 16773 installedLatch.countDown(); 16774 16775 // Regardless of success or failure of the move operation, 16776 // always unfreeze the package 16777 unfreezePackage(packageName); 16778 16779 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16780 switch (status) { 16781 case PackageInstaller.STATUS_SUCCESS: 16782 mMoveCallbacks.notifyStatusChanged(moveId, 16783 PackageManager.MOVE_SUCCEEDED); 16784 break; 16785 case PackageInstaller.STATUS_FAILURE_STORAGE: 16786 mMoveCallbacks.notifyStatusChanged(moveId, 16787 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16788 break; 16789 default: 16790 mMoveCallbacks.notifyStatusChanged(moveId, 16791 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16792 break; 16793 } 16794 } 16795 }; 16796 16797 final MoveInfo move; 16798 if (moveCompleteApp) { 16799 // Kick off a thread to report progress estimates 16800 new Thread() { 16801 @Override 16802 public void run() { 16803 while (true) { 16804 try { 16805 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16806 break; 16807 } 16808 } catch (InterruptedException ignored) { 16809 } 16810 16811 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16812 final int progress = 10 + (int) MathUtils.constrain( 16813 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16814 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16815 } 16816 } 16817 }.start(); 16818 16819 final String dataAppName = codeFile.getName(); 16820 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16821 dataAppName, appId, seinfo); 16822 } else { 16823 move = null; 16824 } 16825 16826 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16827 16828 final Message msg = mHandler.obtainMessage(INIT_COPY); 16829 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16830 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16831 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16832 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16833 msg.obj = params; 16834 16835 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16836 System.identityHashCode(msg.obj)); 16837 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16838 System.identityHashCode(msg.obj)); 16839 16840 mHandler.sendMessage(msg); 16841 } 16842 16843 @Override 16844 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16846 16847 final int realMoveId = mNextMoveId.getAndIncrement(); 16848 final Bundle extras = new Bundle(); 16849 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16850 mMoveCallbacks.notifyCreated(realMoveId, extras); 16851 16852 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16853 @Override 16854 public void onCreated(int moveId, Bundle extras) { 16855 // Ignored 16856 } 16857 16858 @Override 16859 public void onStatusChanged(int moveId, int status, long estMillis) { 16860 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16861 } 16862 }; 16863 16864 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16865 storage.setPrimaryStorageUuid(volumeUuid, callback); 16866 return realMoveId; 16867 } 16868 16869 @Override 16870 public int getMoveStatus(int moveId) { 16871 mContext.enforceCallingOrSelfPermission( 16872 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16873 return mMoveCallbacks.mLastStatus.get(moveId); 16874 } 16875 16876 @Override 16877 public void registerMoveCallback(IPackageMoveObserver callback) { 16878 mContext.enforceCallingOrSelfPermission( 16879 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16880 mMoveCallbacks.register(callback); 16881 } 16882 16883 @Override 16884 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16885 mContext.enforceCallingOrSelfPermission( 16886 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16887 mMoveCallbacks.unregister(callback); 16888 } 16889 16890 @Override 16891 public boolean setInstallLocation(int loc) { 16892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16893 null); 16894 if (getInstallLocation() == loc) { 16895 return true; 16896 } 16897 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16898 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16899 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16900 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16901 return true; 16902 } 16903 return false; 16904 } 16905 16906 @Override 16907 public int getInstallLocation() { 16908 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16909 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16910 PackageHelper.APP_INSTALL_AUTO); 16911 } 16912 16913 /** Called by UserManagerService */ 16914 void cleanUpUser(UserManagerService userManager, int userHandle) { 16915 synchronized (mPackages) { 16916 mDirtyUsers.remove(userHandle); 16917 mUserNeedsBadging.delete(userHandle); 16918 mSettings.removeUserLPw(userHandle); 16919 mPendingBroadcasts.remove(userHandle); 16920 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 16921 } 16922 synchronized (mInstallLock) { 16923 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16924 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16925 final String volumeUuid = vol.getFsUuid(); 16926 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16927 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16928 } 16929 synchronized (mPackages) { 16930 removeUnusedPackagesLILPw(userManager, userHandle); 16931 } 16932 } 16933 } 16934 16935 /** 16936 * We're removing userHandle and would like to remove any downloaded packages 16937 * that are no longer in use by any other user. 16938 * @param userHandle the user being removed 16939 */ 16940 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16941 final boolean DEBUG_CLEAN_APKS = false; 16942 int [] users = userManager.getUserIds(); 16943 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16944 while (psit.hasNext()) { 16945 PackageSetting ps = psit.next(); 16946 if (ps.pkg == null) { 16947 continue; 16948 } 16949 final String packageName = ps.pkg.packageName; 16950 // Skip over if system app 16951 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16952 continue; 16953 } 16954 if (DEBUG_CLEAN_APKS) { 16955 Slog.i(TAG, "Checking package " + packageName); 16956 } 16957 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16958 if (keep) { 16959 if (DEBUG_CLEAN_APKS) { 16960 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16961 } 16962 } else { 16963 for (int i = 0; i < users.length; i++) { 16964 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16965 keep = true; 16966 if (DEBUG_CLEAN_APKS) { 16967 Slog.i(TAG, " Keeping package " + packageName + " for user " 16968 + users[i]); 16969 } 16970 break; 16971 } 16972 } 16973 } 16974 if (!keep) { 16975 if (DEBUG_CLEAN_APKS) { 16976 Slog.i(TAG, " Removing package " + packageName); 16977 } 16978 mHandler.post(new Runnable() { 16979 public void run() { 16980 deletePackageX(packageName, userHandle, 0); 16981 } //end run 16982 }); 16983 } 16984 } 16985 } 16986 16987 /** Called by UserManagerService */ 16988 void createNewUser(int userHandle) { 16989 synchronized (mInstallLock) { 16990 mInstaller.createUserConfig(userHandle); 16991 mSettings.createNewUserLI(this, mInstaller, userHandle); 16992 } 16993 synchronized (mPackages) { 16994 applyFactoryDefaultBrowserLPw(userHandle); 16995 primeDomainVerificationsLPw(userHandle); 16996 } 16997 } 16998 16999 void newUserCreated(final int userHandle) { 17000 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17001 // If permission review for legacy apps is required, we represent 17002 // dagerous permissions for such apps as always granted runtime 17003 // permissions to keep per user flag state whether review is needed. 17004 // Hence, if a new user is added we have to propagate dangerous 17005 // permission grants for these legacy apps. 17006 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17007 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17008 | UPDATE_PERMISSIONS_REPLACE_ALL); 17009 } 17010 } 17011 17012 @Override 17013 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17014 mContext.enforceCallingOrSelfPermission( 17015 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17016 "Only package verification agents can read the verifier device identity"); 17017 17018 synchronized (mPackages) { 17019 return mSettings.getVerifierDeviceIdentityLPw(); 17020 } 17021 } 17022 17023 @Override 17024 public void setPermissionEnforced(String permission, boolean enforced) { 17025 // TODO: Now that we no longer change GID for storage, this should to away. 17026 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17027 "setPermissionEnforced"); 17028 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17029 synchronized (mPackages) { 17030 if (mSettings.mReadExternalStorageEnforced == null 17031 || mSettings.mReadExternalStorageEnforced != enforced) { 17032 mSettings.mReadExternalStorageEnforced = enforced; 17033 mSettings.writeLPr(); 17034 } 17035 } 17036 // kill any non-foreground processes so we restart them and 17037 // grant/revoke the GID. 17038 final IActivityManager am = ActivityManagerNative.getDefault(); 17039 if (am != null) { 17040 final long token = Binder.clearCallingIdentity(); 17041 try { 17042 am.killProcessesBelowForeground("setPermissionEnforcement"); 17043 } catch (RemoteException e) { 17044 } finally { 17045 Binder.restoreCallingIdentity(token); 17046 } 17047 } 17048 } else { 17049 throw new IllegalArgumentException("No selective enforcement for " + permission); 17050 } 17051 } 17052 17053 @Override 17054 @Deprecated 17055 public boolean isPermissionEnforced(String permission) { 17056 return true; 17057 } 17058 17059 @Override 17060 public boolean isStorageLow() { 17061 final long token = Binder.clearCallingIdentity(); 17062 try { 17063 final DeviceStorageMonitorInternal 17064 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17065 if (dsm != null) { 17066 return dsm.isMemoryLow(); 17067 } else { 17068 return false; 17069 } 17070 } finally { 17071 Binder.restoreCallingIdentity(token); 17072 } 17073 } 17074 17075 @Override 17076 public IPackageInstaller getPackageInstaller() { 17077 return mInstallerService; 17078 } 17079 17080 private boolean userNeedsBadging(int userId) { 17081 int index = mUserNeedsBadging.indexOfKey(userId); 17082 if (index < 0) { 17083 final UserInfo userInfo; 17084 final long token = Binder.clearCallingIdentity(); 17085 try { 17086 userInfo = sUserManager.getUserInfo(userId); 17087 } finally { 17088 Binder.restoreCallingIdentity(token); 17089 } 17090 final boolean b; 17091 if (userInfo != null && userInfo.isManagedProfile()) { 17092 b = true; 17093 } else { 17094 b = false; 17095 } 17096 mUserNeedsBadging.put(userId, b); 17097 return b; 17098 } 17099 return mUserNeedsBadging.valueAt(index); 17100 } 17101 17102 @Override 17103 public KeySet getKeySetByAlias(String packageName, String alias) { 17104 if (packageName == null || alias == null) { 17105 return null; 17106 } 17107 synchronized(mPackages) { 17108 final PackageParser.Package pkg = mPackages.get(packageName); 17109 if (pkg == null) { 17110 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17111 throw new IllegalArgumentException("Unknown package: " + packageName); 17112 } 17113 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17114 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17115 } 17116 } 17117 17118 @Override 17119 public KeySet getSigningKeySet(String packageName) { 17120 if (packageName == null) { 17121 return null; 17122 } 17123 synchronized(mPackages) { 17124 final PackageParser.Package pkg = mPackages.get(packageName); 17125 if (pkg == null) { 17126 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17127 throw new IllegalArgumentException("Unknown package: " + packageName); 17128 } 17129 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17130 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17131 throw new SecurityException("May not access signing KeySet of other apps."); 17132 } 17133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17134 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17135 } 17136 } 17137 17138 @Override 17139 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17140 if (packageName == null || ks == null) { 17141 return false; 17142 } 17143 synchronized(mPackages) { 17144 final PackageParser.Package pkg = mPackages.get(packageName); 17145 if (pkg == null) { 17146 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17147 throw new IllegalArgumentException("Unknown package: " + packageName); 17148 } 17149 IBinder ksh = ks.getToken(); 17150 if (ksh instanceof KeySetHandle) { 17151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17152 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17153 } 17154 return false; 17155 } 17156 } 17157 17158 @Override 17159 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17160 if (packageName == null || ks == null) { 17161 return false; 17162 } 17163 synchronized(mPackages) { 17164 final PackageParser.Package pkg = mPackages.get(packageName); 17165 if (pkg == null) { 17166 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 17167 throw new IllegalArgumentException("Unknown package: " + packageName); 17168 } 17169 IBinder ksh = ks.getToken(); 17170 if (ksh instanceof KeySetHandle) { 17171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17172 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17173 } 17174 return false; 17175 } 17176 } 17177 17178 private void deletePackageIfUnusedLPr(final String packageName) { 17179 PackageSetting ps = mSettings.mPackages.get(packageName); 17180 if (ps == null) { 17181 return; 17182 } 17183 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17184 // TODO Implement atomic delete if package is unused 17185 // It is currently possible that the package will be deleted even if it is installed 17186 // after this method returns. 17187 mHandler.post(new Runnable() { 17188 public void run() { 17189 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17190 } 17191 }); 17192 } 17193 } 17194 17195 /** 17196 * Check and throw if the given before/after packages would be considered a 17197 * downgrade. 17198 */ 17199 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17200 throws PackageManagerException { 17201 if (after.versionCode < before.mVersionCode) { 17202 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17203 "Update version code " + after.versionCode + " is older than current " 17204 + before.mVersionCode); 17205 } else if (after.versionCode == before.mVersionCode) { 17206 if (after.baseRevisionCode < before.baseRevisionCode) { 17207 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17208 "Update base revision code " + after.baseRevisionCode 17209 + " is older than current " + before.baseRevisionCode); 17210 } 17211 17212 if (!ArrayUtils.isEmpty(after.splitNames)) { 17213 for (int i = 0; i < after.splitNames.length; i++) { 17214 final String splitName = after.splitNames[i]; 17215 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17216 if (j != -1) { 17217 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17218 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17219 "Update split " + splitName + " revision code " 17220 + after.splitRevisionCodes[i] + " is older than current " 17221 + before.splitRevisionCodes[j]); 17222 } 17223 } 17224 } 17225 } 17226 } 17227 } 17228 17229 private static class MoveCallbacks extends Handler { 17230 private static final int MSG_CREATED = 1; 17231 private static final int MSG_STATUS_CHANGED = 2; 17232 17233 private final RemoteCallbackList<IPackageMoveObserver> 17234 mCallbacks = new RemoteCallbackList<>(); 17235 17236 private final SparseIntArray mLastStatus = new SparseIntArray(); 17237 17238 public MoveCallbacks(Looper looper) { 17239 super(looper); 17240 } 17241 17242 public void register(IPackageMoveObserver callback) { 17243 mCallbacks.register(callback); 17244 } 17245 17246 public void unregister(IPackageMoveObserver callback) { 17247 mCallbacks.unregister(callback); 17248 } 17249 17250 @Override 17251 public void handleMessage(Message msg) { 17252 final SomeArgs args = (SomeArgs) msg.obj; 17253 final int n = mCallbacks.beginBroadcast(); 17254 for (int i = 0; i < n; i++) { 17255 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17256 try { 17257 invokeCallback(callback, msg.what, args); 17258 } catch (RemoteException ignored) { 17259 } 17260 } 17261 mCallbacks.finishBroadcast(); 17262 args.recycle(); 17263 } 17264 17265 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17266 throws RemoteException { 17267 switch (what) { 17268 case MSG_CREATED: { 17269 callback.onCreated(args.argi1, (Bundle) args.arg2); 17270 break; 17271 } 17272 case MSG_STATUS_CHANGED: { 17273 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17274 break; 17275 } 17276 } 17277 } 17278 17279 private void notifyCreated(int moveId, Bundle extras) { 17280 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17281 17282 final SomeArgs args = SomeArgs.obtain(); 17283 args.argi1 = moveId; 17284 args.arg2 = extras; 17285 obtainMessage(MSG_CREATED, args).sendToTarget(); 17286 } 17287 17288 private void notifyStatusChanged(int moveId, int status) { 17289 notifyStatusChanged(moveId, status, -1); 17290 } 17291 17292 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17293 Slog.v(TAG, "Move " + moveId + " status " + status); 17294 17295 final SomeArgs args = SomeArgs.obtain(); 17296 args.argi1 = moveId; 17297 args.argi2 = status; 17298 args.arg3 = estMillis; 17299 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17300 17301 synchronized (mLastStatus) { 17302 mLastStatus.put(moveId, status); 17303 } 17304 } 17305 } 17306 17307 private final static class OnPermissionChangeListeners extends Handler { 17308 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17309 17310 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17311 new RemoteCallbackList<>(); 17312 17313 public OnPermissionChangeListeners(Looper looper) { 17314 super(looper); 17315 } 17316 17317 @Override 17318 public void handleMessage(Message msg) { 17319 switch (msg.what) { 17320 case MSG_ON_PERMISSIONS_CHANGED: { 17321 final int uid = msg.arg1; 17322 handleOnPermissionsChanged(uid); 17323 } break; 17324 } 17325 } 17326 17327 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17328 mPermissionListeners.register(listener); 17329 17330 } 17331 17332 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17333 mPermissionListeners.unregister(listener); 17334 } 17335 17336 public void onPermissionsChanged(int uid) { 17337 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17338 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17339 } 17340 } 17341 17342 private void handleOnPermissionsChanged(int uid) { 17343 final int count = mPermissionListeners.beginBroadcast(); 17344 try { 17345 for (int i = 0; i < count; i++) { 17346 IOnPermissionsChangeListener callback = mPermissionListeners 17347 .getBroadcastItem(i); 17348 try { 17349 callback.onPermissionsChanged(uid); 17350 } catch (RemoteException e) { 17351 Log.e(TAG, "Permission listener is dead", e); 17352 } 17353 } 17354 } finally { 17355 mPermissionListeners.finishBroadcast(); 17356 } 17357 } 17358 } 17359 17360 private class PackageManagerInternalImpl extends PackageManagerInternal { 17361 @Override 17362 public void setLocationPackagesProvider(PackagesProvider provider) { 17363 synchronized (mPackages) { 17364 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17365 } 17366 } 17367 17368 @Override 17369 public void setImePackagesProvider(PackagesProvider provider) { 17370 synchronized (mPackages) { 17371 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17372 } 17373 } 17374 17375 @Override 17376 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17377 synchronized (mPackages) { 17378 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17379 } 17380 } 17381 17382 @Override 17383 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17384 synchronized (mPackages) { 17385 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17386 } 17387 } 17388 17389 @Override 17390 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17391 synchronized (mPackages) { 17392 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17393 } 17394 } 17395 17396 @Override 17397 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17398 synchronized (mPackages) { 17399 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17400 } 17401 } 17402 17403 @Override 17404 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17405 synchronized (mPackages) { 17406 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17407 } 17408 } 17409 17410 @Override 17411 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17412 synchronized (mPackages) { 17413 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17414 packageName, userId); 17415 } 17416 } 17417 17418 @Override 17419 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17420 synchronized (mPackages) { 17421 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17422 packageName, userId); 17423 } 17424 } 17425 17426 @Override 17427 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17428 synchronized (mPackages) { 17429 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17430 packageName, userId); 17431 } 17432 } 17433 17434 @Override 17435 public void setKeepUninstalledPackages(final List<String> packageList) { 17436 Preconditions.checkNotNull(packageList); 17437 List<String> removedFromList = null; 17438 synchronized (mPackages) { 17439 if (mKeepUninstalledPackages != null) { 17440 final int packagesCount = mKeepUninstalledPackages.size(); 17441 for (int i = 0; i < packagesCount; i++) { 17442 String oldPackage = mKeepUninstalledPackages.get(i); 17443 if (packageList != null && packageList.contains(oldPackage)) { 17444 continue; 17445 } 17446 if (removedFromList == null) { 17447 removedFromList = new ArrayList<>(); 17448 } 17449 removedFromList.add(oldPackage); 17450 } 17451 } 17452 mKeepUninstalledPackages = new ArrayList<>(packageList); 17453 if (removedFromList != null) { 17454 final int removedCount = removedFromList.size(); 17455 for (int i = 0; i < removedCount; i++) { 17456 deletePackageIfUnusedLPr(removedFromList.get(i)); 17457 } 17458 } 17459 } 17460 } 17461 17462 @Override 17463 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17464 synchronized (mPackages) { 17465 // If we do not support permission review, done. 17466 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17467 return false; 17468 } 17469 17470 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17471 if (packageSetting == null) { 17472 return false; 17473 } 17474 17475 // Permission review applies only to apps not supporting the new permission model. 17476 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17477 return false; 17478 } 17479 17480 // Legacy apps have the permission and get user consent on launch. 17481 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17482 return permissionsState.isPermissionReviewRequired(userId); 17483 } 17484 } 17485 } 17486 17487 @Override 17488 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17489 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17490 synchronized (mPackages) { 17491 final long identity = Binder.clearCallingIdentity(); 17492 try { 17493 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17494 packageNames, userId); 17495 } finally { 17496 Binder.restoreCallingIdentity(identity); 17497 } 17498 } 17499 } 17500 17501 private static void enforceSystemOrPhoneCaller(String tag) { 17502 int callingUid = Binder.getCallingUid(); 17503 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17504 throw new SecurityException( 17505 "Cannot call " + tag + " from UID " + callingUid); 17506 } 17507 } 17508} 17509