PackageManagerService.java revision f7d47f91feeffb75761b339cb14c631cc18d3728
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.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE; 66import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 67import static android.content.pm.PackageManager.MATCH_ENCRYPTION_UNAWARE; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.admin.IDevicePolicyManager; 107import android.app.backup.IBackupManager; 108import android.content.BroadcastReceiver; 109import android.content.ComponentName; 110import android.content.Context; 111import android.content.IIntentReceiver; 112import android.content.Intent; 113import android.content.IntentFilter; 114import android.content.IntentSender; 115import android.content.IntentSender.SendIntentException; 116import android.content.ServiceConnection; 117import android.content.pm.ActivityInfo; 118import android.content.pm.ApplicationInfo; 119import android.content.pm.AppsQueryHelper; 120import android.content.pm.ComponentInfo; 121import android.content.pm.EphemeralApplicationInfo; 122import android.content.pm.EphemeralResolveInfo; 123import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 124import android.content.pm.FeatureInfo; 125import android.content.pm.IOnPermissionsChangeListener; 126import android.content.pm.IPackageDataObserver; 127import android.content.pm.IPackageDeleteObserver; 128import android.content.pm.IPackageDeleteObserver2; 129import android.content.pm.IPackageInstallObserver2; 130import android.content.pm.IPackageInstaller; 131import android.content.pm.IPackageManager; 132import android.content.pm.IPackageMoveObserver; 133import android.content.pm.IPackageStatsObserver; 134import android.content.pm.InstrumentationInfo; 135import android.content.pm.IntentFilterVerificationInfo; 136import android.content.pm.KeySet; 137import android.content.pm.PackageCleanItem; 138import android.content.pm.PackageInfo; 139import android.content.pm.PackageInfoLite; 140import android.content.pm.PackageInstaller; 141import android.content.pm.PackageManager; 142import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 143import android.content.pm.PackageManagerInternal; 144import android.content.pm.PackageParser; 145import android.content.pm.PackageParser.ActivityIntentInfo; 146import android.content.pm.PackageParser.PackageLite; 147import android.content.pm.PackageParser.PackageParserException; 148import android.content.pm.PackageStats; 149import android.content.pm.PackageUserState; 150import android.content.pm.ParceledListSlice; 151import android.content.pm.PermissionGroupInfo; 152import android.content.pm.PermissionInfo; 153import android.content.pm.ProviderInfo; 154import android.content.pm.ResolveInfo; 155import android.content.pm.ServiceInfo; 156import android.content.pm.Signature; 157import android.content.pm.UserInfo; 158import android.content.pm.VerifierDeviceIdentity; 159import android.content.pm.VerifierInfo; 160import android.content.res.Resources; 161import android.graphics.Bitmap; 162import android.hardware.display.DisplayManager; 163import android.net.Uri; 164import android.os.Binder; 165import android.os.Build; 166import android.os.Bundle; 167import android.os.Debug; 168import android.os.Environment; 169import android.os.Environment.UserEnvironment; 170import android.os.FileUtils; 171import android.os.Handler; 172import android.os.IBinder; 173import android.os.Looper; 174import android.os.Message; 175import android.os.Parcel; 176import android.os.ParcelFileDescriptor; 177import android.os.Parcelable; 178import android.os.Process; 179import android.os.RemoteCallbackList; 180import android.os.RemoteException; 181import android.os.ResultReceiver; 182import android.os.SELinux; 183import android.os.ServiceManager; 184import android.os.SystemClock; 185import android.os.SystemProperties; 186import android.os.Trace; 187import android.os.UserHandle; 188import android.os.UserManager; 189import android.os.storage.IMountService; 190import android.os.storage.MountServiceInternal; 191import android.os.storage.StorageEventListener; 192import android.os.storage.StorageManager; 193import android.os.storage.VolumeInfo; 194import android.os.storage.VolumeRecord; 195import android.security.KeyStore; 196import android.security.SystemKeyStore; 197import android.system.ErrnoException; 198import android.system.Os; 199import android.text.TextUtils; 200import android.text.format.DateUtils; 201import android.util.ArrayMap; 202import android.util.ArraySet; 203import android.util.AtomicFile; 204import android.util.DisplayMetrics; 205import android.util.EventLog; 206import android.util.ExceptionUtils; 207import android.util.Log; 208import android.util.LogPrinter; 209import android.util.MathUtils; 210import android.util.PrintStreamPrinter; 211import android.util.Slog; 212import android.util.SparseArray; 213import android.util.SparseBooleanArray; 214import android.util.SparseIntArray; 215import android.util.Xml; 216import android.view.Display; 217 218import com.android.internal.R; 219import com.android.internal.annotations.GuardedBy; 220import com.android.internal.app.IMediaContainerService; 221import com.android.internal.app.ResolverActivity; 222import com.android.internal.content.NativeLibraryHelper; 223import com.android.internal.content.PackageHelper; 224import com.android.internal.os.IParcelFileDescriptorFactory; 225import com.android.internal.os.InstallerConnection.InstallerException; 226import com.android.internal.os.SomeArgs; 227import com.android.internal.os.Zygote; 228import com.android.internal.util.ArrayUtils; 229import com.android.internal.util.FastPrintWriter; 230import com.android.internal.util.FastXmlSerializer; 231import com.android.internal.util.IndentingPrintWriter; 232import com.android.internal.util.Preconditions; 233import com.android.internal.util.XmlUtils; 234import com.android.server.EventLogTags; 235import com.android.server.FgThread; 236import com.android.server.IntentResolver; 237import com.android.server.LocalServices; 238import com.android.server.ServiceThread; 239import com.android.server.SystemConfig; 240import com.android.server.Watchdog; 241import com.android.server.pm.PermissionsState.PermissionState; 242import com.android.server.pm.Settings.DatabaseVersion; 243import com.android.server.pm.Settings.VersionInfo; 244import com.android.server.storage.DeviceStorageMonitorInternal; 245 246import dalvik.system.DexFile; 247import dalvik.system.VMRuntime; 248 249import libcore.io.IoUtils; 250import libcore.util.EmptyArray; 251 252import org.xmlpull.v1.XmlPullParser; 253import org.xmlpull.v1.XmlPullParserException; 254import org.xmlpull.v1.XmlSerializer; 255 256import java.io.BufferedInputStream; 257import java.io.BufferedOutputStream; 258import java.io.BufferedReader; 259import java.io.ByteArrayInputStream; 260import java.io.ByteArrayOutputStream; 261import java.io.File; 262import java.io.FileDescriptor; 263import java.io.FileNotFoundException; 264import java.io.FileOutputStream; 265import java.io.FileReader; 266import java.io.FilenameFilter; 267import java.io.IOException; 268import java.io.InputStream; 269import java.io.PrintWriter; 270import java.nio.charset.StandardCharsets; 271import java.security.MessageDigest; 272import java.security.NoSuchAlgorithmException; 273import java.security.PublicKey; 274import java.security.cert.CertificateEncodingException; 275import java.security.cert.CertificateException; 276import java.text.SimpleDateFormat; 277import java.util.ArrayList; 278import java.util.Arrays; 279import java.util.Collection; 280import java.util.Collections; 281import java.util.Comparator; 282import java.util.Date; 283import java.util.HashSet; 284import java.util.Iterator; 285import java.util.List; 286import java.util.Map; 287import java.util.Objects; 288import java.util.Set; 289import java.util.concurrent.CountDownLatch; 290import java.util.concurrent.TimeUnit; 291import java.util.concurrent.atomic.AtomicBoolean; 292import java.util.concurrent.atomic.AtomicInteger; 293import java.util.concurrent.atomic.AtomicLong; 294 295/** 296 * Keep track of all those .apks everywhere. 297 * 298 * This is very central to the platform's security; please run the unit 299 * tests whenever making modifications here: 300 * 301runtest -c android.content.pm.PackageManagerTests frameworks-core 302 * 303 * {@hide} 304 */ 305public class PackageManagerService extends IPackageManager.Stub { 306 static final String TAG = "PackageManager"; 307 static final boolean DEBUG_SETTINGS = false; 308 static final boolean DEBUG_PREFERRED = false; 309 static final boolean DEBUG_UPGRADE = false; 310 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 311 private static final boolean DEBUG_BACKUP = false; 312 private static final boolean DEBUG_INSTALL = false; 313 private static final boolean DEBUG_REMOVE = false; 314 private static final boolean DEBUG_BROADCASTS = false; 315 private static final boolean DEBUG_SHOW_INFO = false; 316 private static final boolean DEBUG_PACKAGE_INFO = false; 317 private static final boolean DEBUG_INTENT_MATCHING = false; 318 private static final boolean DEBUG_PACKAGE_SCANNING = false; 319 private static final boolean DEBUG_VERIFY = false; 320 321 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 322 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 323 // user, but by default initialize to this. 324 static final boolean DEBUG_DEXOPT = false; 325 326 private static final boolean DEBUG_ABI_SELECTION = false; 327 private static final boolean DEBUG_EPHEMERAL = false; 328 private static final boolean DEBUG_TRIAGED_MISSING = false; 329 private static final boolean DEBUG_APP_DATA = false; 330 331 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 332 333 private static final boolean DISABLE_EPHEMERAL_APPS = true; 334 335 private static final int RADIO_UID = Process.PHONE_UID; 336 private static final int LOG_UID = Process.LOG_UID; 337 private static final int NFC_UID = Process.NFC_UID; 338 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 339 private static final int SHELL_UID = Process.SHELL_UID; 340 341 // Cap the size of permission trees that 3rd party apps can define 342 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 343 344 // Suffix used during package installation when copying/moving 345 // package apks to install directory. 346 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 347 348 static final int SCAN_NO_DEX = 1<<1; 349 static final int SCAN_FORCE_DEX = 1<<2; 350 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 351 static final int SCAN_NEW_INSTALL = 1<<4; 352 static final int SCAN_NO_PATHS = 1<<5; 353 static final int SCAN_UPDATE_TIME = 1<<6; 354 static final int SCAN_DEFER_DEX = 1<<7; 355 static final int SCAN_BOOTING = 1<<8; 356 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 357 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 358 static final int SCAN_REPLACING = 1<<11; 359 static final int SCAN_REQUIRE_KNOWN = 1<<12; 360 static final int SCAN_MOVE = 1<<13; 361 static final int SCAN_INITIAL = 1<<14; 362 static final int SCAN_CHECK_ONLY = 1<<15; 363 364 static final int REMOVE_CHATTY = 1<<16; 365 366 private static final int[] EMPTY_INT_ARRAY = new int[0]; 367 368 /** 369 * Timeout (in milliseconds) after which the watchdog should declare that 370 * our handler thread is wedged. The usual default for such things is one 371 * minute but we sometimes do very lengthy I/O operations on this thread, 372 * such as installing multi-gigabyte applications, so ours needs to be longer. 373 */ 374 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 375 376 /** 377 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 378 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 379 * settings entry if available, otherwise we use the hardcoded default. If it's been 380 * more than this long since the last fstrim, we force one during the boot sequence. 381 * 382 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 383 * one gets run at the next available charging+idle time. This final mandatory 384 * no-fstrim check kicks in only of the other scheduling criteria is never met. 385 */ 386 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 387 388 /** 389 * Whether verification is enabled by default. 390 */ 391 private static final boolean DEFAULT_VERIFY_ENABLE = true; 392 393 /** 394 * The default maximum time to wait for the verification agent to return in 395 * milliseconds. 396 */ 397 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 398 399 /** 400 * The default response for package verification timeout. 401 * 402 * This can be either PackageManager.VERIFICATION_ALLOW or 403 * PackageManager.VERIFICATION_REJECT. 404 */ 405 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 406 407 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 408 409 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 410 DEFAULT_CONTAINER_PACKAGE, 411 "com.android.defcontainer.DefaultContainerService"); 412 413 private static final String KILL_APP_REASON_GIDS_CHANGED = 414 "permission grant or revoke changed gids"; 415 416 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 417 "permissions revoked"; 418 419 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 420 421 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 422 423 /** Permission grant: not grant the permission. */ 424 private static final int GRANT_DENIED = 1; 425 426 /** Permission grant: grant the permission as an install permission. */ 427 private static final int GRANT_INSTALL = 2; 428 429 /** Permission grant: grant the permission as a runtime one. */ 430 private static final int GRANT_RUNTIME = 3; 431 432 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 433 private static final int GRANT_UPGRADE = 4; 434 435 /** Canonical intent used to identify what counts as a "web browser" app */ 436 private static final Intent sBrowserIntent; 437 static { 438 sBrowserIntent = new Intent(); 439 sBrowserIntent.setAction(Intent.ACTION_VIEW); 440 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 441 sBrowserIntent.setData(Uri.parse("http:")); 442 } 443 444 final ServiceThread mHandlerThread; 445 446 final PackageHandler mHandler; 447 448 /** 449 * Messages for {@link #mHandler} that need to wait for system ready before 450 * being dispatched. 451 */ 452 private ArrayList<Message> mPostSystemReadyMessages; 453 454 final int mSdkVersion = Build.VERSION.SDK_INT; 455 456 final Context mContext; 457 final boolean mFactoryTest; 458 final boolean mOnlyCore; 459 final DisplayMetrics mMetrics; 460 final int mDefParseFlags; 461 final String[] mSeparateProcesses; 462 final boolean mIsUpgrade; 463 464 /** The location for ASEC container files on internal storage. */ 465 final String mAsecInternalPath; 466 467 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 468 // LOCK HELD. Can be called with mInstallLock held. 469 @GuardedBy("mInstallLock") 470 final Installer mInstaller; 471 472 /** Directory where installed third-party apps stored */ 473 final File mAppInstallDir; 474 final File mEphemeralInstallDir; 475 476 /** 477 * Directory to which applications installed internally have their 478 * 32 bit native libraries copied. 479 */ 480 private File mAppLib32InstallDir; 481 482 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 483 // apps. 484 final File mDrmAppPrivateInstallDir; 485 486 // ---------------------------------------------------------------- 487 488 // Lock for state used when installing and doing other long running 489 // operations. Methods that must be called with this lock held have 490 // the suffix "LI". 491 final Object mInstallLock = new Object(); 492 493 // ---------------------------------------------------------------- 494 495 // Keys are String (package name), values are Package. This also serves 496 // as the lock for the global state. Methods that must be called with 497 // this lock held have the prefix "LP". 498 @GuardedBy("mPackages") 499 final ArrayMap<String, PackageParser.Package> mPackages = 500 new ArrayMap<String, PackageParser.Package>(); 501 502 // Tracks available target package names -> overlay package paths. 503 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 504 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 505 506 /** 507 * Tracks new system packages [received in an OTA] that we expect to 508 * find updated user-installed versions. Keys are package name, values 509 * are package location. 510 */ 511 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 512 513 /** 514 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 515 */ 516 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 517 /** 518 * Whether or not system app permissions should be promoted from install to runtime. 519 */ 520 boolean mPromoteSystemApps; 521 522 final Settings mSettings; 523 boolean mRestoredSettings; 524 525 // System configuration read by SystemConfig. 526 final int[] mGlobalGids; 527 final SparseArray<ArraySet<String>> mSystemPermissions; 528 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 529 530 // If mac_permissions.xml was found for seinfo labeling. 531 boolean mFoundPolicyFile; 532 533 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 534 535 public static final class SharedLibraryEntry { 536 public final String path; 537 public final String apk; 538 539 SharedLibraryEntry(String _path, String _apk) { 540 path = _path; 541 apk = _apk; 542 } 543 } 544 545 // Currently known shared libraries. 546 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 547 new ArrayMap<String, SharedLibraryEntry>(); 548 549 // All available activities, for your resolving pleasure. 550 final ActivityIntentResolver mActivities = 551 new ActivityIntentResolver(); 552 553 // All available receivers, for your resolving pleasure. 554 final ActivityIntentResolver mReceivers = 555 new ActivityIntentResolver(); 556 557 // All available services, for your resolving pleasure. 558 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 559 560 // All available providers, for your resolving pleasure. 561 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 562 563 // Mapping from provider base names (first directory in content URI codePath) 564 // to the provider information. 565 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 566 new ArrayMap<String, PackageParser.Provider>(); 567 568 // Mapping from instrumentation class names to info about them. 569 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 570 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 571 572 // Mapping from permission names to info about them. 573 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 574 new ArrayMap<String, PackageParser.PermissionGroup>(); 575 576 // Packages whose data we have transfered into another package, thus 577 // should no longer exist. 578 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 579 580 // Broadcast actions that are only available to the system. 581 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 582 583 /** List of packages waiting for verification. */ 584 final SparseArray<PackageVerificationState> mPendingVerification 585 = new SparseArray<PackageVerificationState>(); 586 587 /** Set of packages associated with each app op permission. */ 588 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 589 590 final PackageInstallerService mInstallerService; 591 592 private final PackageDexOptimizer mPackageDexOptimizer; 593 594 private AtomicInteger mNextMoveId = new AtomicInteger(); 595 private final MoveCallbacks mMoveCallbacks; 596 597 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 598 599 // Cache of users who need badging. 600 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 601 602 /** Token for keys in mPendingVerification. */ 603 private int mPendingVerificationToken = 0; 604 605 volatile boolean mSystemReady; 606 volatile boolean mSafeMode; 607 volatile boolean mHasSystemUidErrors; 608 609 ApplicationInfo mAndroidApplication; 610 final ActivityInfo mResolveActivity = new ActivityInfo(); 611 final ResolveInfo mResolveInfo = new ResolveInfo(); 612 ComponentName mResolveComponentName; 613 PackageParser.Package mPlatformPackage; 614 ComponentName mCustomResolverComponentName; 615 616 boolean mResolverReplaced = false; 617 618 private final @Nullable ComponentName mIntentFilterVerifierComponent; 619 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 620 621 private int mIntentFilterVerificationToken = 0; 622 623 /** Component that knows whether or not an ephemeral application exists */ 624 final ComponentName mEphemeralResolverComponent; 625 /** The service connection to the ephemeral resolver */ 626 final EphemeralResolverConnection mEphemeralResolverConnection; 627 628 /** Component used to install ephemeral applications */ 629 final ComponentName mEphemeralInstallerComponent; 630 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 631 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 632 633 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 634 = new SparseArray<IntentFilterVerificationState>(); 635 636 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 637 new DefaultPermissionGrantPolicy(this); 638 639 // List of packages names to keep cached, even if they are uninstalled for all users 640 private List<String> mKeepUninstalledPackages; 641 642 private boolean mUseJitProfiles = 643 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 644 645 private static class IFVerificationParams { 646 PackageParser.Package pkg; 647 boolean replacing; 648 int userId; 649 int verifierUid; 650 651 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 652 int _userId, int _verifierUid) { 653 pkg = _pkg; 654 replacing = _replacing; 655 userId = _userId; 656 replacing = _replacing; 657 verifierUid = _verifierUid; 658 } 659 } 660 661 private interface IntentFilterVerifier<T extends IntentFilter> { 662 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 663 T filter, String packageName); 664 void startVerifications(int userId); 665 void receiveVerificationResponse(int verificationId); 666 } 667 668 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 669 private Context mContext; 670 private ComponentName mIntentFilterVerifierComponent; 671 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 672 673 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 674 mContext = context; 675 mIntentFilterVerifierComponent = verifierComponent; 676 } 677 678 private String getDefaultScheme() { 679 return IntentFilter.SCHEME_HTTPS; 680 } 681 682 @Override 683 public void startVerifications(int userId) { 684 // Launch verifications requests 685 int count = mCurrentIntentFilterVerifications.size(); 686 for (int n=0; n<count; n++) { 687 int verificationId = mCurrentIntentFilterVerifications.get(n); 688 final IntentFilterVerificationState ivs = 689 mIntentFilterVerificationStates.get(verificationId); 690 691 String packageName = ivs.getPackageName(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int filterCount = filters.size(); 695 ArraySet<String> domainsSet = new ArraySet<>(); 696 for (int m=0; m<filterCount; m++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(m); 698 domainsSet.addAll(filter.getHostsList()); 699 } 700 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 701 synchronized (mPackages) { 702 if (mSettings.createIntentFilterVerificationIfNeededLPw( 703 packageName, domainsList) != null) { 704 scheduleWriteSettingsLocked(); 705 } 706 } 707 sendVerificationRequest(userId, verificationId, ivs); 708 } 709 mCurrentIntentFilterVerifications.clear(); 710 } 711 712 private void sendVerificationRequest(int userId, int verificationId, 713 IntentFilterVerificationState ivs) { 714 715 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 716 verificationIntent.putExtra( 717 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 718 verificationId); 719 verificationIntent.putExtra( 720 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 721 getDefaultScheme()); 722 verificationIntent.putExtra( 723 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 724 ivs.getHostsString()); 725 verificationIntent.putExtra( 726 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 727 ivs.getPackageName()); 728 verificationIntent.setComponent(mIntentFilterVerifierComponent); 729 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 730 731 UserHandle user = new UserHandle(userId); 732 mContext.sendBroadcastAsUser(verificationIntent, user); 733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 734 "Sending IntentFilter verification broadcast"); 735 } 736 737 public void receiveVerificationResponse(int verificationId) { 738 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 739 740 final boolean verified = ivs.isVerified(); 741 742 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 743 final int count = filters.size(); 744 if (DEBUG_DOMAIN_VERIFICATION) { 745 Slog.i(TAG, "Received verification response " + verificationId 746 + " for " + count + " filters, verified=" + verified); 747 } 748 for (int n=0; n<count; n++) { 749 PackageParser.ActivityIntentInfo filter = filters.get(n); 750 filter.setVerified(verified); 751 752 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 753 + " verified with result:" + verified + " and hosts:" 754 + ivs.getHostsString()); 755 } 756 757 mIntentFilterVerificationStates.remove(verificationId); 758 759 final String packageName = ivs.getPackageName(); 760 IntentFilterVerificationInfo ivi = null; 761 762 synchronized (mPackages) { 763 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 764 } 765 if (ivi == null) { 766 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 767 + verificationId + " packageName:" + packageName); 768 return; 769 } 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 771 "Updating IntentFilterVerificationInfo for package " + packageName 772 +" verificationId:" + verificationId); 773 774 synchronized (mPackages) { 775 if (verified) { 776 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 777 } else { 778 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 779 } 780 scheduleWriteSettingsLocked(); 781 782 final int userId = ivs.getUserId(); 783 if (userId != UserHandle.USER_ALL) { 784 final int userStatus = 785 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 786 787 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 788 boolean needUpdate = false; 789 790 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 791 // already been set by the User thru the Disambiguation dialog 792 switch (userStatus) { 793 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 794 if (verified) { 795 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 796 } else { 797 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 798 } 799 needUpdate = true; 800 break; 801 802 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 803 if (verified) { 804 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 805 needUpdate = true; 806 } 807 break; 808 809 default: 810 // Nothing to do 811 } 812 813 if (needUpdate) { 814 mSettings.updateIntentFilterVerificationStatusLPw( 815 packageName, updatedStatus, userId); 816 scheduleWritePackageRestrictionsLocked(userId); 817 } 818 } 819 } 820 } 821 822 @Override 823 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 824 ActivityIntentInfo filter, String packageName) { 825 if (!hasValidDomains(filter)) { 826 return false; 827 } 828 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 829 if (ivs == null) { 830 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 831 packageName); 832 } 833 if (DEBUG_DOMAIN_VERIFICATION) { 834 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 835 } 836 ivs.addFilter(filter); 837 return true; 838 } 839 840 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 841 int userId, int verificationId, String packageName) { 842 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 843 verifierUid, userId, packageName); 844 ivs.setPendingState(); 845 synchronized (mPackages) { 846 mIntentFilterVerificationStates.append(verificationId, ivs); 847 mCurrentIntentFilterVerifications.add(verificationId); 848 } 849 return ivs; 850 } 851 } 852 853 private static boolean hasValidDomains(ActivityIntentInfo filter) { 854 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 855 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 856 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 857 } 858 859 // Set of pending broadcasts for aggregating enable/disable of components. 860 static class PendingPackageBroadcasts { 861 // for each user id, a map of <package name -> components within that package> 862 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 863 864 public PendingPackageBroadcasts() { 865 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 866 } 867 868 public ArrayList<String> get(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 870 return packages.get(packageName); 871 } 872 873 public void put(int userId, String packageName, ArrayList<String> components) { 874 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 875 packages.put(packageName, components); 876 } 877 878 public void remove(int userId, String packageName) { 879 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 880 if (packages != null) { 881 packages.remove(packageName); 882 } 883 } 884 885 public void remove(int userId) { 886 mUidMap.remove(userId); 887 } 888 889 public int userIdCount() { 890 return mUidMap.size(); 891 } 892 893 public int userIdAt(int n) { 894 return mUidMap.keyAt(n); 895 } 896 897 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 898 return mUidMap.get(userId); 899 } 900 901 public int size() { 902 // total number of pending broadcast entries across all userIds 903 int num = 0; 904 for (int i = 0; i< mUidMap.size(); i++) { 905 num += mUidMap.valueAt(i).size(); 906 } 907 return num; 908 } 909 910 public void clear() { 911 mUidMap.clear(); 912 } 913 914 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 915 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 916 if (map == null) { 917 map = new ArrayMap<String, ArrayList<String>>(); 918 mUidMap.put(userId, map); 919 } 920 return map; 921 } 922 } 923 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 924 925 // Service Connection to remote media container service to copy 926 // package uri's from external media onto secure containers 927 // or internal storage. 928 private IMediaContainerService mContainerService = null; 929 930 static final int SEND_PENDING_BROADCAST = 1; 931 static final int MCS_BOUND = 3; 932 static final int END_COPY = 4; 933 static final int INIT_COPY = 5; 934 static final int MCS_UNBIND = 6; 935 static final int START_CLEANING_PACKAGE = 7; 936 static final int FIND_INSTALL_LOC = 8; 937 static final int POST_INSTALL = 9; 938 static final int MCS_RECONNECT = 10; 939 static final int MCS_GIVE_UP = 11; 940 static final int UPDATED_MEDIA_STATUS = 12; 941 static final int WRITE_SETTINGS = 13; 942 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 943 static final int PACKAGE_VERIFIED = 15; 944 static final int CHECK_PENDING_VERIFICATION = 16; 945 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 946 static final int INTENT_FILTER_VERIFIED = 18; 947 948 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 949 950 // Delay time in millisecs 951 static final int BROADCAST_DELAY = 10 * 1000; 952 953 static UserManagerService sUserManager; 954 955 // Stores a list of users whose package restrictions file needs to be updated 956 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 957 958 final private DefaultContainerConnection mDefContainerConn = 959 new DefaultContainerConnection(); 960 class DefaultContainerConnection implements ServiceConnection { 961 public void onServiceConnected(ComponentName name, IBinder service) { 962 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 963 IMediaContainerService imcs = 964 IMediaContainerService.Stub.asInterface(service); 965 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 966 } 967 968 public void onServiceDisconnected(ComponentName name) { 969 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 970 } 971 } 972 973 // Recordkeeping of restore-after-install operations that are currently in flight 974 // between the Package Manager and the Backup Manager 975 static class PostInstallData { 976 public InstallArgs args; 977 public PackageInstalledInfo res; 978 979 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 980 args = _a; 981 res = _r; 982 } 983 } 984 985 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 986 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 987 988 // XML tags for backup/restore of various bits of state 989 private static final String TAG_PREFERRED_BACKUP = "pa"; 990 private static final String TAG_DEFAULT_APPS = "da"; 991 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 992 993 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 994 private static final String TAG_ALL_GRANTS = "rt-grants"; 995 private static final String TAG_GRANT = "grant"; 996 private static final String ATTR_PACKAGE_NAME = "pkg"; 997 998 private static final String TAG_PERMISSION = "perm"; 999 private static final String ATTR_PERMISSION_NAME = "name"; 1000 private static final String ATTR_IS_GRANTED = "g"; 1001 private static final String ATTR_USER_SET = "set"; 1002 private static final String ATTR_USER_FIXED = "fixed"; 1003 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1004 1005 // System/policy permission grants are not backed up 1006 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1007 FLAG_PERMISSION_POLICY_FIXED 1008 | FLAG_PERMISSION_SYSTEM_FIXED 1009 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1010 1011 // And we back up these user-adjusted states 1012 private static final int USER_RUNTIME_GRANT_MASK = 1013 FLAG_PERMISSION_USER_SET 1014 | FLAG_PERMISSION_USER_FIXED 1015 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1016 1017 final @Nullable String mRequiredVerifierPackage; 1018 final @Nullable String mRequiredInstallerPackage; 1019 1020 private final PackageUsage mPackageUsage = new PackageUsage(); 1021 1022 private class PackageUsage { 1023 private static final int WRITE_INTERVAL 1024 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1025 1026 private final Object mFileLock = new Object(); 1027 private final AtomicLong mLastWritten = new AtomicLong(0); 1028 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1029 1030 private boolean mIsHistoricalPackageUsageAvailable = true; 1031 1032 boolean isHistoricalPackageUsageAvailable() { 1033 return mIsHistoricalPackageUsageAvailable; 1034 } 1035 1036 void write(boolean force) { 1037 if (force) { 1038 writeInternal(); 1039 return; 1040 } 1041 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1042 && !DEBUG_DEXOPT) { 1043 return; 1044 } 1045 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1046 new Thread("PackageUsage_DiskWriter") { 1047 @Override 1048 public void run() { 1049 try { 1050 writeInternal(); 1051 } finally { 1052 mBackgroundWriteRunning.set(false); 1053 } 1054 } 1055 }.start(); 1056 } 1057 } 1058 1059 private void writeInternal() { 1060 synchronized (mPackages) { 1061 synchronized (mFileLock) { 1062 AtomicFile file = getFile(); 1063 FileOutputStream f = null; 1064 try { 1065 f = file.startWrite(); 1066 BufferedOutputStream out = new BufferedOutputStream(f); 1067 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1068 StringBuilder sb = new StringBuilder(); 1069 for (PackageParser.Package pkg : mPackages.values()) { 1070 if (pkg.mLastPackageUsageTimeInMills == 0) { 1071 continue; 1072 } 1073 sb.setLength(0); 1074 sb.append(pkg.packageName); 1075 sb.append(' '); 1076 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1077 sb.append('\n'); 1078 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1079 } 1080 out.flush(); 1081 file.finishWrite(f); 1082 } catch (IOException e) { 1083 if (f != null) { 1084 file.failWrite(f); 1085 } 1086 Log.e(TAG, "Failed to write package usage times", e); 1087 } 1088 } 1089 } 1090 mLastWritten.set(SystemClock.elapsedRealtime()); 1091 } 1092 1093 void readLP() { 1094 synchronized (mFileLock) { 1095 AtomicFile file = getFile(); 1096 BufferedInputStream in = null; 1097 try { 1098 in = new BufferedInputStream(file.openRead()); 1099 StringBuffer sb = new StringBuffer(); 1100 while (true) { 1101 String packageName = readToken(in, sb, ' '); 1102 if (packageName == null) { 1103 break; 1104 } 1105 String timeInMillisString = readToken(in, sb, '\n'); 1106 if (timeInMillisString == null) { 1107 throw new IOException("Failed to find last usage time for package " 1108 + packageName); 1109 } 1110 PackageParser.Package pkg = mPackages.get(packageName); 1111 if (pkg == null) { 1112 continue; 1113 } 1114 long timeInMillis; 1115 try { 1116 timeInMillis = Long.parseLong(timeInMillisString); 1117 } catch (NumberFormatException e) { 1118 throw new IOException("Failed to parse " + timeInMillisString 1119 + " as a long.", e); 1120 } 1121 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1122 } 1123 } catch (FileNotFoundException expected) { 1124 mIsHistoricalPackageUsageAvailable = false; 1125 } catch (IOException e) { 1126 Log.w(TAG, "Failed to read package usage times", e); 1127 } finally { 1128 IoUtils.closeQuietly(in); 1129 } 1130 } 1131 mLastWritten.set(SystemClock.elapsedRealtime()); 1132 } 1133 1134 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1135 throws IOException { 1136 sb.setLength(0); 1137 while (true) { 1138 int ch = in.read(); 1139 if (ch == -1) { 1140 if (sb.length() == 0) { 1141 return null; 1142 } 1143 throw new IOException("Unexpected EOF"); 1144 } 1145 if (ch == endOfToken) { 1146 return sb.toString(); 1147 } 1148 sb.append((char)ch); 1149 } 1150 } 1151 1152 private AtomicFile getFile() { 1153 File dataDir = Environment.getDataDirectory(); 1154 File systemDir = new File(dataDir, "system"); 1155 File fname = new File(systemDir, "package-usage.list"); 1156 return new AtomicFile(fname); 1157 } 1158 } 1159 1160 class PackageHandler extends Handler { 1161 private boolean mBound = false; 1162 final ArrayList<HandlerParams> mPendingInstalls = 1163 new ArrayList<HandlerParams>(); 1164 1165 private boolean connectToService() { 1166 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1167 " DefaultContainerService"); 1168 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1170 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1171 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1173 mBound = true; 1174 return true; 1175 } 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1177 return false; 1178 } 1179 1180 private void disconnectService() { 1181 mContainerService = null; 1182 mBound = false; 1183 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1184 mContext.unbindService(mDefContainerConn); 1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1186 } 1187 1188 PackageHandler(Looper looper) { 1189 super(looper); 1190 } 1191 1192 public void handleMessage(Message msg) { 1193 try { 1194 doHandleMessage(msg); 1195 } finally { 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1197 } 1198 } 1199 1200 void doHandleMessage(Message msg) { 1201 switch (msg.what) { 1202 case INIT_COPY: { 1203 HandlerParams params = (HandlerParams) msg.obj; 1204 int idx = mPendingInstalls.size(); 1205 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1206 // If a bind was already initiated we dont really 1207 // need to do anything. The pending install 1208 // will be processed later on. 1209 if (!mBound) { 1210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 // If this is the only one pending we might 1213 // have to bind to the service again. 1214 if (!connectToService()) { 1215 Slog.e(TAG, "Failed to bind to media container service"); 1216 params.serviceError(); 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1218 System.identityHashCode(mHandler)); 1219 if (params.traceMethod != null) { 1220 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1221 params.traceCookie); 1222 } 1223 return; 1224 } else { 1225 // Once we bind to the service, the first 1226 // pending request will be processed. 1227 mPendingInstalls.add(idx, params); 1228 } 1229 } else { 1230 mPendingInstalls.add(idx, params); 1231 // Already bound to the service. Just make 1232 // sure we trigger off processing the first request. 1233 if (idx == 0) { 1234 mHandler.sendEmptyMessage(MCS_BOUND); 1235 } 1236 } 1237 break; 1238 } 1239 case MCS_BOUND: { 1240 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1241 if (msg.obj != null) { 1242 mContainerService = (IMediaContainerService) msg.obj; 1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1244 System.identityHashCode(mHandler)); 1245 } 1246 if (mContainerService == null) { 1247 if (!mBound) { 1248 // Something seriously wrong since we are not bound and we are not 1249 // waiting for connection. Bail out. 1250 Slog.e(TAG, "Cannot bind to media container service"); 1251 for (HandlerParams params : mPendingInstalls) { 1252 // Indicate service bind error 1253 params.serviceError(); 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1255 System.identityHashCode(params)); 1256 if (params.traceMethod != null) { 1257 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1258 params.traceMethod, params.traceCookie); 1259 } 1260 return; 1261 } 1262 mPendingInstalls.clear(); 1263 } else { 1264 Slog.w(TAG, "Waiting to connect to media container service"); 1265 } 1266 } else if (mPendingInstalls.size() > 0) { 1267 HandlerParams params = mPendingInstalls.get(0); 1268 if (params != null) { 1269 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1270 System.identityHashCode(params)); 1271 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1272 if (params.startCopy()) { 1273 // We are done... look for more work or to 1274 // go idle. 1275 if (DEBUG_SD_INSTALL) Log.i(TAG, 1276 "Checking for more work or unbind..."); 1277 // Delete pending install 1278 if (mPendingInstalls.size() > 0) { 1279 mPendingInstalls.remove(0); 1280 } 1281 if (mPendingInstalls.size() == 0) { 1282 if (mBound) { 1283 if (DEBUG_SD_INSTALL) Log.i(TAG, 1284 "Posting delayed MCS_UNBIND"); 1285 removeMessages(MCS_UNBIND); 1286 Message ubmsg = obtainMessage(MCS_UNBIND); 1287 // Unbind after a little delay, to avoid 1288 // continual thrashing. 1289 sendMessageDelayed(ubmsg, 10000); 1290 } 1291 } else { 1292 // There are more pending requests in queue. 1293 // Just post MCS_BOUND message to trigger processing 1294 // of next pending install. 1295 if (DEBUG_SD_INSTALL) Log.i(TAG, 1296 "Posting MCS_BOUND for next work"); 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 } 1300 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1301 } 1302 } else { 1303 // Should never happen ideally. 1304 Slog.w(TAG, "Empty queue"); 1305 } 1306 break; 1307 } 1308 case MCS_RECONNECT: { 1309 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1310 if (mPendingInstalls.size() > 0) { 1311 if (mBound) { 1312 disconnectService(); 1313 } 1314 if (!connectToService()) { 1315 Slog.e(TAG, "Failed to bind to media container service"); 1316 for (HandlerParams params : mPendingInstalls) { 1317 // Indicate service bind error 1318 params.serviceError(); 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 } 1322 mPendingInstalls.clear(); 1323 } 1324 } 1325 break; 1326 } 1327 case MCS_UNBIND: { 1328 // If there is no actual work left, then time to unbind. 1329 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1330 1331 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1332 if (mBound) { 1333 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1334 1335 disconnectService(); 1336 } 1337 } else if (mPendingInstalls.size() > 0) { 1338 // There are more pending requests in queue. 1339 // Just post MCS_BOUND message to trigger processing 1340 // of next pending install. 1341 mHandler.sendEmptyMessage(MCS_BOUND); 1342 } 1343 1344 break; 1345 } 1346 case MCS_GIVE_UP: { 1347 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1348 HandlerParams params = mPendingInstalls.remove(0); 1349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1350 System.identityHashCode(params)); 1351 break; 1352 } 1353 case SEND_PENDING_BROADCAST: { 1354 String packages[]; 1355 ArrayList<String> components[]; 1356 int size = 0; 1357 int uids[]; 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1359 synchronized (mPackages) { 1360 if (mPendingBroadcasts == null) { 1361 return; 1362 } 1363 size = mPendingBroadcasts.size(); 1364 if (size <= 0) { 1365 // Nothing to be done. Just return 1366 return; 1367 } 1368 packages = new String[size]; 1369 components = new ArrayList[size]; 1370 uids = new int[size]; 1371 int i = 0; // filling out the above arrays 1372 1373 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1374 int packageUserId = mPendingBroadcasts.userIdAt(n); 1375 Iterator<Map.Entry<String, ArrayList<String>>> it 1376 = mPendingBroadcasts.packagesForUserId(packageUserId) 1377 .entrySet().iterator(); 1378 while (it.hasNext() && i < size) { 1379 Map.Entry<String, ArrayList<String>> ent = it.next(); 1380 packages[i] = ent.getKey(); 1381 components[i] = ent.getValue(); 1382 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1383 uids[i] = (ps != null) 1384 ? UserHandle.getUid(packageUserId, ps.appId) 1385 : -1; 1386 i++; 1387 } 1388 } 1389 size = i; 1390 mPendingBroadcasts.clear(); 1391 } 1392 // Send broadcasts 1393 for (int i = 0; i < size; i++) { 1394 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1395 } 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1397 break; 1398 } 1399 case START_CLEANING_PACKAGE: { 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1401 final String packageName = (String)msg.obj; 1402 final int userId = msg.arg1; 1403 final boolean andCode = msg.arg2 != 0; 1404 synchronized (mPackages) { 1405 if (userId == UserHandle.USER_ALL) { 1406 int[] users = sUserManager.getUserIds(); 1407 for (int user : users) { 1408 mSettings.addPackageToCleanLPw( 1409 new PackageCleanItem(user, packageName, andCode)); 1410 } 1411 } else { 1412 mSettings.addPackageToCleanLPw( 1413 new PackageCleanItem(userId, packageName, andCode)); 1414 } 1415 } 1416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1417 startCleaningPackages(); 1418 } break; 1419 case POST_INSTALL: { 1420 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1421 1422 PostInstallData data = mRunningInstalls.get(msg.arg1); 1423 mRunningInstalls.delete(msg.arg1); 1424 1425 if (data != null) { 1426 InstallArgs args = data.args; 1427 PackageInstalledInfo parentRes = data.res; 1428 1429 final boolean grantPermissions = (args.installFlags 1430 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1431 final String[] grantedPermissions = args.installGrantPermissions; 1432 1433 // Handle the parent package 1434 handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions, 1435 args.observer); 1436 1437 // Handle the child packages 1438 final int childCount = (parentRes.addedChildPackages != null) 1439 ? parentRes.addedChildPackages.size() : 0; 1440 for (int i = 0; i < childCount; i++) { 1441 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1442 handlePackagePostInstall(childRes, grantPermissions, grantedPermissions, 1443 args.observer); 1444 } 1445 1446 // Log tracing if needed 1447 if (args.traceMethod != null) { 1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1449 args.traceCookie); 1450 } 1451 } else { 1452 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1453 } 1454 1455 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1456 } break; 1457 case UPDATED_MEDIA_STATUS: { 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1459 boolean reportStatus = msg.arg1 == 1; 1460 boolean doGc = msg.arg2 == 1; 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1462 if (doGc) { 1463 // Force a gc to clear up stale containers. 1464 Runtime.getRuntime().gc(); 1465 } 1466 if (msg.obj != null) { 1467 @SuppressWarnings("unchecked") 1468 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1470 // Unload containers 1471 unloadAllContainers(args); 1472 } 1473 if (reportStatus) { 1474 try { 1475 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1476 PackageHelper.getMountService().finishMediaUpdate(); 1477 } catch (RemoteException e) { 1478 Log.e(TAG, "MountService not running?"); 1479 } 1480 } 1481 } break; 1482 case WRITE_SETTINGS: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 synchronized (mPackages) { 1485 removeMessages(WRITE_SETTINGS); 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 mSettings.writeLPr(); 1488 mDirtyUsers.clear(); 1489 } 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1491 } break; 1492 case WRITE_PACKAGE_RESTRICTIONS: { 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1494 synchronized (mPackages) { 1495 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1496 for (int userId : mDirtyUsers) { 1497 mSettings.writePackageRestrictionsLPr(userId); 1498 } 1499 mDirtyUsers.clear(); 1500 } 1501 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1502 } break; 1503 case CHECK_PENDING_VERIFICATION: { 1504 final int verificationId = msg.arg1; 1505 final PackageVerificationState state = mPendingVerification.get(verificationId); 1506 1507 if ((state != null) && !state.timeoutExtended()) { 1508 final InstallArgs args = state.getInstallArgs(); 1509 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1510 1511 Slog.i(TAG, "Verification timed out for " + originUri); 1512 mPendingVerification.remove(verificationId); 1513 1514 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1515 1516 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1517 Slog.i(TAG, "Continuing with installation of " + originUri); 1518 state.setVerifierResponse(Binder.getCallingUid(), 1519 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1520 broadcastPackageVerified(verificationId, originUri, 1521 PackageManager.VERIFICATION_ALLOW, 1522 state.getInstallArgs().getUser()); 1523 try { 1524 ret = args.copyApk(mContainerService, true); 1525 } catch (RemoteException e) { 1526 Slog.e(TAG, "Could not contact the ContainerService"); 1527 } 1528 } else { 1529 broadcastPackageVerified(verificationId, originUri, 1530 PackageManager.VERIFICATION_REJECT, 1531 state.getInstallArgs().getUser()); 1532 } 1533 1534 Trace.asyncTraceEnd( 1535 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1536 1537 processPendingInstall(args, ret); 1538 mHandler.sendEmptyMessage(MCS_UNBIND); 1539 } 1540 break; 1541 } 1542 case PACKAGE_VERIFIED: { 1543 final int verificationId = msg.arg1; 1544 1545 final PackageVerificationState state = mPendingVerification.get(verificationId); 1546 if (state == null) { 1547 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1548 break; 1549 } 1550 1551 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1552 1553 state.setVerifierResponse(response.callerUid, response.code); 1554 1555 if (state.isVerificationComplete()) { 1556 mPendingVerification.remove(verificationId); 1557 1558 final InstallArgs args = state.getInstallArgs(); 1559 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1560 1561 int ret; 1562 if (state.isInstallAllowed()) { 1563 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1564 broadcastPackageVerified(verificationId, originUri, 1565 response.code, state.getInstallArgs().getUser()); 1566 try { 1567 ret = args.copyApk(mContainerService, true); 1568 } catch (RemoteException e) { 1569 Slog.e(TAG, "Could not contact the ContainerService"); 1570 } 1571 } else { 1572 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1573 } 1574 1575 Trace.asyncTraceEnd( 1576 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1577 1578 processPendingInstall(args, ret); 1579 mHandler.sendEmptyMessage(MCS_UNBIND); 1580 } 1581 1582 break; 1583 } 1584 case START_INTENT_FILTER_VERIFICATIONS: { 1585 IFVerificationParams params = (IFVerificationParams) msg.obj; 1586 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1587 params.replacing, params.pkg); 1588 break; 1589 } 1590 case INTENT_FILTER_VERIFIED: { 1591 final int verificationId = msg.arg1; 1592 1593 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1594 verificationId); 1595 if (state == null) { 1596 Slog.w(TAG, "Invalid IntentFilter verification token " 1597 + verificationId + " received"); 1598 break; 1599 } 1600 1601 final int userId = state.getUserId(); 1602 1603 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1604 "Processing IntentFilter verification with token:" 1605 + verificationId + " and userId:" + userId); 1606 1607 final IntentFilterVerificationResponse response = 1608 (IntentFilterVerificationResponse) msg.obj; 1609 1610 state.setVerifierResponse(response.callerUid, response.code); 1611 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "IntentFilter verification with token:" + verificationId 1614 + " and userId:" + userId 1615 + " is settings verifier response with response code:" 1616 + response.code); 1617 1618 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1620 + response.getFailedDomainsString()); 1621 } 1622 1623 if (state.isVerificationComplete()) { 1624 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1625 } else { 1626 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1627 "IntentFilter verification with token:" + verificationId 1628 + " was not said to be complete"); 1629 } 1630 1631 break; 1632 } 1633 } 1634 } 1635 } 1636 1637 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1638 String[] grantedPermissions, IPackageInstallObserver2 installObserver) { 1639 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1640 // Send the removed broadcasts 1641 if (res.removedInfo != null) { 1642 res.removedInfo.sendPackageRemovedBroadcasts(); 1643 } 1644 1645 // Now that we successfully installed the package, grant runtime 1646 // permissions if requested before broadcasting the install. 1647 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1648 >= Build.VERSION_CODES.M) { 1649 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1650 } 1651 1652 final boolean update = res.removedInfo != null 1653 && res.removedInfo.removedPackage != null; 1654 1655 // If this is the first time we have child packages for a disabled privileged 1656 // app that had no children, we grant requested runtime permissions to the new 1657 // children if the parent on the system image had them already granted. 1658 if (res.pkg.parentPackage != null) { 1659 synchronized (mPackages) { 1660 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1661 } 1662 } 1663 1664 synchronized (mPackages) { 1665 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1666 } 1667 1668 final String packageName = res.pkg.applicationInfo.packageName; 1669 Bundle extras = new Bundle(1); 1670 extras.putInt(Intent.EXTRA_UID, res.uid); 1671 1672 // Determine the set of users who are adding this package for 1673 // the first time vs. those who are seeing an update. 1674 int[] firstUsers = EMPTY_INT_ARRAY; 1675 int[] updateUsers = EMPTY_INT_ARRAY; 1676 if (res.origUsers == null || res.origUsers.length == 0) { 1677 firstUsers = res.newUsers; 1678 } else { 1679 for (int newUser : res.newUsers) { 1680 boolean isNew = true; 1681 for (int origUser : res.origUsers) { 1682 if (origUser == newUser) { 1683 isNew = false; 1684 break; 1685 } 1686 } 1687 if (isNew) { 1688 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1689 } else { 1690 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1691 } 1692 } 1693 } 1694 1695 // Send installed broadcasts if the install/update is not ephemeral 1696 if (!isEphemeral(res.pkg)) { 1697 // Send added for users that see the package for the first time 1698 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1699 extras, 0 /*flags*/, null /*targetPackage*/, 1700 null /*finishedReceiver*/, firstUsers); 1701 1702 // Send added for users that don't see the package for the first time 1703 if (update) { 1704 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1705 } 1706 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1707 extras, 0 /*flags*/, null /*targetPackage*/, 1708 null /*finishedReceiver*/, updateUsers); 1709 1710 // Send replaced for users that don't see the package for the first time 1711 if (update) { 1712 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1713 packageName, extras, 0 /*flags*/, 1714 null /*targetPackage*/, null /*finishedReceiver*/, 1715 updateUsers); 1716 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1717 null /*package*/, null /*extras*/, 0 /*flags*/, 1718 packageName /*targetPackage*/, 1719 null /*finishedReceiver*/, updateUsers); 1720 } 1721 1722 // Send broadcast package appeared if forward locked/external for all users 1723 // treat asec-hosted packages like removable media on upgrade 1724 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1725 if (DEBUG_INSTALL) { 1726 Slog.i(TAG, "upgrading pkg " + res.pkg 1727 + " is ASEC-hosted -> AVAILABLE"); 1728 } 1729 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1730 ArrayList<String> pkgList = new ArrayList<>(1); 1731 pkgList.add(packageName); 1732 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1733 } 1734 } 1735 1736 // Work that needs to happen on first install within each user 1737 if (firstUsers != null && firstUsers.length > 0) { 1738 synchronized (mPackages) { 1739 for (int userId : firstUsers) { 1740 // If this app is a browser and it's newly-installed for some 1741 // users, clear any default-browser state in those users. The 1742 // app's nature doesn't depend on the user, so we can just check 1743 // its browser nature in any user and generalize. 1744 if (packageIsBrowser(packageName, userId)) { 1745 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1746 } 1747 1748 // We may also need to apply pending (restored) runtime 1749 // permission grants within these users. 1750 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1751 } 1752 } 1753 } 1754 1755 // Log current value of "unknown sources" setting 1756 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1757 getUnknownSourcesSettings()); 1758 1759 // Force a gc to clear up things 1760 Runtime.getRuntime().gc(); 1761 1762 // Remove the replaced package's older resources safely now 1763 // We delete after a gc for applications on sdcard. 1764 if (res.removedInfo != null && res.removedInfo.args != null) { 1765 synchronized (mInstallLock) { 1766 res.removedInfo.args.doPostDeleteLI(true); 1767 } 1768 } 1769 } 1770 1771 // If someone is watching installs - notify them 1772 if (installObserver != null) { 1773 try { 1774 Bundle extras = extrasForInstallResult(res); 1775 installObserver.onPackageInstalled(res.name, res.returnCode, 1776 res.returnMsg, extras); 1777 } catch (RemoteException e) { 1778 Slog.i(TAG, "Observer no longer exists."); 1779 } 1780 } 1781 } 1782 1783 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1784 PackageParser.Package pkg) { 1785 if (pkg.parentPackage == null) { 1786 return; 1787 } 1788 if (pkg.requestedPermissions == null) { 1789 return; 1790 } 1791 final PackageSetting disabledSysParentPs = mSettings 1792 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1793 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1794 || !disabledSysParentPs.isPrivileged() 1795 || (disabledSysParentPs.childPackageNames != null 1796 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1797 return; 1798 } 1799 final int[] allUserIds = sUserManager.getUserIds(); 1800 final int permCount = pkg.requestedPermissions.size(); 1801 for (int i = 0; i < permCount; i++) { 1802 String permission = pkg.requestedPermissions.get(i); 1803 BasePermission bp = mSettings.mPermissions.get(permission); 1804 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1805 continue; 1806 } 1807 for (int userId : allUserIds) { 1808 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1809 permission, userId)) { 1810 grantRuntimePermission(pkg.packageName, permission, userId); 1811 } 1812 } 1813 } 1814 } 1815 1816 private StorageEventListener mStorageListener = new StorageEventListener() { 1817 @Override 1818 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1819 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1820 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1821 final String volumeUuid = vol.getFsUuid(); 1822 1823 // Clean up any users or apps that were removed or recreated 1824 // while this volume was missing 1825 reconcileUsers(volumeUuid); 1826 reconcileApps(volumeUuid); 1827 1828 // Clean up any install sessions that expired or were 1829 // cancelled while this volume was missing 1830 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1831 1832 loadPrivatePackages(vol); 1833 1834 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1835 unloadPrivatePackages(vol); 1836 } 1837 } 1838 1839 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1840 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1841 updateExternalMediaStatus(true, false); 1842 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1843 updateExternalMediaStatus(false, false); 1844 } 1845 } 1846 } 1847 1848 @Override 1849 public void onVolumeForgotten(String fsUuid) { 1850 if (TextUtils.isEmpty(fsUuid)) { 1851 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1852 return; 1853 } 1854 1855 // Remove any apps installed on the forgotten volume 1856 synchronized (mPackages) { 1857 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1858 for (PackageSetting ps : packages) { 1859 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1860 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1861 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1862 } 1863 1864 mSettings.onVolumeForgotten(fsUuid); 1865 mSettings.writeLPr(); 1866 } 1867 } 1868 }; 1869 1870 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1871 String[] grantedPermissions) { 1872 for (int userId : userIds) { 1873 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1874 } 1875 1876 // We could have touched GID membership, so flush out packages.list 1877 synchronized (mPackages) { 1878 mSettings.writePackageListLPr(); 1879 } 1880 } 1881 1882 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1883 String[] grantedPermissions) { 1884 SettingBase sb = (SettingBase) pkg.mExtras; 1885 if (sb == null) { 1886 return; 1887 } 1888 1889 PermissionsState permissionsState = sb.getPermissionsState(); 1890 1891 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1892 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1893 1894 synchronized (mPackages) { 1895 for (String permission : pkg.requestedPermissions) { 1896 BasePermission bp = mSettings.mPermissions.get(permission); 1897 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1898 && (grantedPermissions == null 1899 || ArrayUtils.contains(grantedPermissions, permission))) { 1900 final int flags = permissionsState.getPermissionFlags(permission, userId); 1901 // Installer cannot change immutable permissions. 1902 if ((flags & immutableFlags) == 0) { 1903 grantRuntimePermission(pkg.packageName, permission, userId); 1904 } 1905 } 1906 } 1907 } 1908 } 1909 1910 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1911 Bundle extras = null; 1912 switch (res.returnCode) { 1913 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1914 extras = new Bundle(); 1915 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1916 res.origPermission); 1917 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1918 res.origPackage); 1919 break; 1920 } 1921 case PackageManager.INSTALL_SUCCEEDED: { 1922 extras = new Bundle(); 1923 extras.putBoolean(Intent.EXTRA_REPLACING, 1924 res.removedInfo != null && res.removedInfo.removedPackage != null); 1925 break; 1926 } 1927 } 1928 return extras; 1929 } 1930 1931 void scheduleWriteSettingsLocked() { 1932 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1933 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1934 } 1935 } 1936 1937 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1938 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1939 scheduleWritePackageRestrictionsLocked(userId); 1940 } 1941 1942 void scheduleWritePackageRestrictionsLocked(int userId) { 1943 final int[] userIds = (userId == UserHandle.USER_ALL) 1944 ? sUserManager.getUserIds() : new int[]{userId}; 1945 for (int nextUserId : userIds) { 1946 if (!sUserManager.exists(nextUserId)) return; 1947 mDirtyUsers.add(nextUserId); 1948 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1949 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1950 } 1951 } 1952 } 1953 1954 public static PackageManagerService main(Context context, Installer installer, 1955 boolean factoryTest, boolean onlyCore) { 1956 PackageManagerService m = new PackageManagerService(context, installer, 1957 factoryTest, onlyCore); 1958 m.enableSystemUserPackages(); 1959 ServiceManager.addService("package", m); 1960 return m; 1961 } 1962 1963 private void enableSystemUserPackages() { 1964 if (!UserManager.isSplitSystemUser()) { 1965 return; 1966 } 1967 // For system user, enable apps based on the following conditions: 1968 // - app is whitelisted or belong to one of these groups: 1969 // -- system app which has no launcher icons 1970 // -- system app which has INTERACT_ACROSS_USERS permission 1971 // -- system IME app 1972 // - app is not in the blacklist 1973 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1974 Set<String> enableApps = new ArraySet<>(); 1975 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1976 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1977 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1978 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1979 enableApps.addAll(wlApps); 1980 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1981 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1982 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1983 enableApps.removeAll(blApps); 1984 Log.i(TAG, "Applications installed for system user: " + enableApps); 1985 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1986 UserHandle.SYSTEM); 1987 final int allAppsSize = allAps.size(); 1988 synchronized (mPackages) { 1989 for (int i = 0; i < allAppsSize; i++) { 1990 String pName = allAps.get(i); 1991 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1992 // Should not happen, but we shouldn't be failing if it does 1993 if (pkgSetting == null) { 1994 continue; 1995 } 1996 boolean install = enableApps.contains(pName); 1997 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1998 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1999 + " for system user"); 2000 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2001 } 2002 } 2003 } 2004 } 2005 2006 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2007 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2008 Context.DISPLAY_SERVICE); 2009 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2010 } 2011 2012 public PackageManagerService(Context context, Installer installer, 2013 boolean factoryTest, boolean onlyCore) { 2014 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2015 SystemClock.uptimeMillis()); 2016 2017 if (mSdkVersion <= 0) { 2018 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2019 } 2020 2021 mContext = context; 2022 mFactoryTest = factoryTest; 2023 mOnlyCore = onlyCore; 2024 mMetrics = new DisplayMetrics(); 2025 mSettings = new Settings(mPackages); 2026 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2027 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2028 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2029 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2030 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2031 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2032 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2033 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2034 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2035 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2036 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2037 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2038 2039 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2040 if (separateProcesses != null && separateProcesses.length() > 0) { 2041 if ("*".equals(separateProcesses)) { 2042 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2043 mSeparateProcesses = null; 2044 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2045 } else { 2046 mDefParseFlags = 0; 2047 mSeparateProcesses = separateProcesses.split(","); 2048 Slog.w(TAG, "Running with debug.separate_processes: " 2049 + separateProcesses); 2050 } 2051 } else { 2052 mDefParseFlags = 0; 2053 mSeparateProcesses = null; 2054 } 2055 2056 mInstaller = installer; 2057 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2058 "*dexopt*"); 2059 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2060 2061 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2062 FgThread.get().getLooper()); 2063 2064 getDefaultDisplayMetrics(context, mMetrics); 2065 2066 SystemConfig systemConfig = SystemConfig.getInstance(); 2067 mGlobalGids = systemConfig.getGlobalGids(); 2068 mSystemPermissions = systemConfig.getSystemPermissions(); 2069 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2070 2071 synchronized (mInstallLock) { 2072 // writer 2073 synchronized (mPackages) { 2074 mHandlerThread = new ServiceThread(TAG, 2075 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2076 mHandlerThread.start(); 2077 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2078 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2079 2080 File dataDir = Environment.getDataDirectory(); 2081 mAppInstallDir = new File(dataDir, "app"); 2082 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2083 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2084 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2085 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2086 2087 sUserManager = new UserManagerService(context, this, mPackages); 2088 2089 // Propagate permission configuration in to package manager. 2090 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2091 = systemConfig.getPermissions(); 2092 for (int i=0; i<permConfig.size(); i++) { 2093 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2094 BasePermission bp = mSettings.mPermissions.get(perm.name); 2095 if (bp == null) { 2096 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2097 mSettings.mPermissions.put(perm.name, bp); 2098 } 2099 if (perm.gids != null) { 2100 bp.setGids(perm.gids, perm.perUser); 2101 } 2102 } 2103 2104 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2105 for (int i=0; i<libConfig.size(); i++) { 2106 mSharedLibraries.put(libConfig.keyAt(i), 2107 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2108 } 2109 2110 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2111 2112 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2113 2114 String customResolverActivity = Resources.getSystem().getString( 2115 R.string.config_customResolverActivity); 2116 if (TextUtils.isEmpty(customResolverActivity)) { 2117 customResolverActivity = null; 2118 } else { 2119 mCustomResolverComponentName = ComponentName.unflattenFromString( 2120 customResolverActivity); 2121 } 2122 2123 long startTime = SystemClock.uptimeMillis(); 2124 2125 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2126 startTime); 2127 2128 // Set flag to monitor and not change apk file paths when 2129 // scanning install directories. 2130 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2131 2132 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2133 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2134 2135 if (bootClassPath == null) { 2136 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2137 } 2138 2139 if (systemServerClassPath == null) { 2140 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2141 } 2142 2143 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2144 final String[] dexCodeInstructionSets = 2145 getDexCodeInstructionSets( 2146 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2147 2148 /** 2149 * Ensure all external libraries have had dexopt run on them. 2150 */ 2151 if (mSharedLibraries.size() > 0) { 2152 // NOTE: For now, we're compiling these system "shared libraries" 2153 // (and framework jars) into all available architectures. It's possible 2154 // to compile them only when we come across an app that uses them (there's 2155 // already logic for that in scanPackageLI) but that adds some complexity. 2156 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2157 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2158 final String lib = libEntry.path; 2159 if (lib == null) { 2160 continue; 2161 } 2162 2163 try { 2164 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2165 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2166 // Shared libraries do not have profiles so we perform a full 2167 // AOT compilation. 2168 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2169 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2170 StorageManager.UUID_PRIVATE_INTERNAL, 2171 false /*useProfiles*/); 2172 } 2173 } catch (FileNotFoundException e) { 2174 Slog.w(TAG, "Library not found: " + lib); 2175 } catch (IOException | InstallerException e) { 2176 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2177 + e.getMessage()); 2178 } 2179 } 2180 } 2181 } 2182 2183 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2184 2185 final VersionInfo ver = mSettings.getInternalVersion(); 2186 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2187 // when upgrading from pre-M, promote system app permissions from install to runtime 2188 mPromoteSystemApps = 2189 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2190 2191 // save off the names of pre-existing system packages prior to scanning; we don't 2192 // want to automatically grant runtime permissions for new system apps 2193 if (mPromoteSystemApps) { 2194 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2195 while (pkgSettingIter.hasNext()) { 2196 PackageSetting ps = pkgSettingIter.next(); 2197 if (isSystemApp(ps)) { 2198 mExistingSystemPackages.add(ps.name); 2199 } 2200 } 2201 } 2202 2203 // Collect vendor overlay packages. 2204 // (Do this before scanning any apps.) 2205 // For security and version matching reason, only consider 2206 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2207 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2208 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2209 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2210 2211 // Find base frameworks (resource packages without code). 2212 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2213 | PackageParser.PARSE_IS_SYSTEM_DIR 2214 | PackageParser.PARSE_IS_PRIVILEGED, 2215 scanFlags | SCAN_NO_DEX, 0); 2216 2217 // Collected privileged system packages. 2218 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2219 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2220 | PackageParser.PARSE_IS_SYSTEM_DIR 2221 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2222 2223 // Collect ordinary system packages. 2224 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2225 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2226 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2227 2228 // Collect all vendor packages. 2229 File vendorAppDir = new File("/vendor/app"); 2230 try { 2231 vendorAppDir = vendorAppDir.getCanonicalFile(); 2232 } catch (IOException e) { 2233 // failed to look up canonical path, continue with original one 2234 } 2235 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2236 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2237 2238 // Collect all OEM packages. 2239 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2240 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2241 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2242 2243 // Prune any system packages that no longer exist. 2244 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2245 if (!mOnlyCore) { 2246 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2247 while (psit.hasNext()) { 2248 PackageSetting ps = psit.next(); 2249 2250 /* 2251 * If this is not a system app, it can't be a 2252 * disable system app. 2253 */ 2254 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2255 continue; 2256 } 2257 2258 /* 2259 * If the package is scanned, it's not erased. 2260 */ 2261 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2262 if (scannedPkg != null) { 2263 /* 2264 * If the system app is both scanned and in the 2265 * disabled packages list, then it must have been 2266 * added via OTA. Remove it from the currently 2267 * scanned package so the previously user-installed 2268 * application can be scanned. 2269 */ 2270 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2271 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2272 + ps.name + "; removing system app. Last known codePath=" 2273 + ps.codePathString + ", installStatus=" + ps.installStatus 2274 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2275 + scannedPkg.mVersionCode); 2276 removePackageLI(scannedPkg, true); 2277 mExpectingBetter.put(ps.name, ps.codePath); 2278 } 2279 2280 continue; 2281 } 2282 2283 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2284 psit.remove(); 2285 logCriticalInfo(Log.WARN, "System package " + ps.name 2286 + " no longer exists; wiping its data"); 2287 removeDataDirsLI(null, ps.name); 2288 } else { 2289 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2290 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2291 possiblyDeletedUpdatedSystemApps.add(ps.name); 2292 } 2293 } 2294 } 2295 } 2296 2297 //look for any incomplete package installations 2298 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2299 //clean up list 2300 for(int i = 0; i < deletePkgsList.size(); i++) { 2301 //clean up here 2302 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2303 } 2304 //delete tmp files 2305 deleteTempPackageFiles(); 2306 2307 // Remove any shared userIDs that have no associated packages 2308 mSettings.pruneSharedUsersLPw(); 2309 2310 if (!mOnlyCore) { 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2312 SystemClock.uptimeMillis()); 2313 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2314 2315 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2316 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2317 2318 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2319 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2320 2321 /** 2322 * Remove disable package settings for any updated system 2323 * apps that were removed via an OTA. If they're not a 2324 * previously-updated app, remove them completely. 2325 * Otherwise, just revoke their system-level permissions. 2326 */ 2327 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2328 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2329 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2330 2331 String msg; 2332 if (deletedPkg == null) { 2333 msg = "Updated system package " + deletedAppName 2334 + " no longer exists; wiping its data"; 2335 removeDataDirsLI(null, deletedAppName); 2336 } else { 2337 msg = "Updated system app + " + deletedAppName 2338 + " no longer present; removing system privileges for " 2339 + deletedAppName; 2340 2341 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2342 2343 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2344 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2345 } 2346 logCriticalInfo(Log.WARN, msg); 2347 } 2348 2349 /** 2350 * Make sure all system apps that we expected to appear on 2351 * the userdata partition actually showed up. If they never 2352 * appeared, crawl back and revive the system version. 2353 */ 2354 for (int i = 0; i < mExpectingBetter.size(); i++) { 2355 final String packageName = mExpectingBetter.keyAt(i); 2356 if (!mPackages.containsKey(packageName)) { 2357 final File scanFile = mExpectingBetter.valueAt(i); 2358 2359 logCriticalInfo(Log.WARN, "Expected better " + packageName 2360 + " but never showed up; reverting to system"); 2361 2362 final int reparseFlags; 2363 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2364 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2365 | PackageParser.PARSE_IS_SYSTEM_DIR 2366 | PackageParser.PARSE_IS_PRIVILEGED; 2367 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2368 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2369 | PackageParser.PARSE_IS_SYSTEM_DIR; 2370 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2371 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2372 | PackageParser.PARSE_IS_SYSTEM_DIR; 2373 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2374 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2375 | PackageParser.PARSE_IS_SYSTEM_DIR; 2376 } else { 2377 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2378 continue; 2379 } 2380 2381 mSettings.enableSystemPackageLPw(packageName); 2382 2383 try { 2384 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2385 } catch (PackageManagerException e) { 2386 Slog.e(TAG, "Failed to parse original system package: " 2387 + e.getMessage()); 2388 } 2389 } 2390 } 2391 } 2392 mExpectingBetter.clear(); 2393 2394 // Now that we know all of the shared libraries, update all clients to have 2395 // the correct library paths. 2396 updateAllSharedLibrariesLPw(); 2397 2398 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2399 // NOTE: We ignore potential failures here during a system scan (like 2400 // the rest of the commands above) because there's precious little we 2401 // can do about it. A settings error is reported, though. 2402 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2403 false /* boot complete */); 2404 } 2405 2406 // Now that we know all the packages we are keeping, 2407 // read and update their last usage times. 2408 mPackageUsage.readLP(); 2409 2410 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2411 SystemClock.uptimeMillis()); 2412 Slog.i(TAG, "Time to scan packages: " 2413 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2414 + " seconds"); 2415 2416 // If the platform SDK has changed since the last time we booted, 2417 // we need to re-grant app permission to catch any new ones that 2418 // appear. This is really a hack, and means that apps can in some 2419 // cases get permissions that the user didn't initially explicitly 2420 // allow... it would be nice to have some better way to handle 2421 // this situation. 2422 int updateFlags = UPDATE_PERMISSIONS_ALL; 2423 if (ver.sdkVersion != mSdkVersion) { 2424 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2425 + mSdkVersion + "; regranting permissions for internal storage"); 2426 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2427 } 2428 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2429 ver.sdkVersion = mSdkVersion; 2430 2431 // If this is the first boot or an update from pre-M, and it is a normal 2432 // boot, then we need to initialize the default preferred apps across 2433 // all defined users. 2434 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2435 for (UserInfo user : sUserManager.getUsers(true)) { 2436 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2437 applyFactoryDefaultBrowserLPw(user.id); 2438 primeDomainVerificationsLPw(user.id); 2439 } 2440 } 2441 2442 // Prepare storage for system user really early during boot, 2443 // since core system apps like SettingsProvider and SystemUI 2444 // can't wait for user to start 2445 final int storageFlags; 2446 if (StorageManager.isFileBasedEncryptionEnabled()) { 2447 storageFlags = StorageManager.FLAG_STORAGE_DE; 2448 } else { 2449 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2450 } 2451 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2452 storageFlags); 2453 2454 // If this is first boot after an OTA, and a normal boot, then 2455 // we need to clear code cache directories. 2456 if (mIsUpgrade && !onlyCore) { 2457 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2458 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2459 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2460 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2461 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2462 } 2463 } 2464 ver.fingerprint = Build.FINGERPRINT; 2465 } 2466 2467 checkDefaultBrowser(); 2468 2469 // clear only after permissions and other defaults have been updated 2470 mExistingSystemPackages.clear(); 2471 mPromoteSystemApps = false; 2472 2473 // All the changes are done during package scanning. 2474 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2475 2476 // can downgrade to reader 2477 mSettings.writeLPr(); 2478 2479 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2480 SystemClock.uptimeMillis()); 2481 2482 if (!mOnlyCore) { 2483 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2484 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2485 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2486 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2487 mIntentFilterVerifierComponent); 2488 } else { 2489 mRequiredVerifierPackage = null; 2490 mRequiredInstallerPackage = null; 2491 mIntentFilterVerifierComponent = null; 2492 mIntentFilterVerifier = null; 2493 } 2494 2495 mInstallerService = new PackageInstallerService(context, this); 2496 2497 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2498 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2499 // both the installer and resolver must be present to enable ephemeral 2500 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2501 if (DEBUG_EPHEMERAL) { 2502 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2503 + " installer:" + ephemeralInstallerComponent); 2504 } 2505 mEphemeralResolverComponent = ephemeralResolverComponent; 2506 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2507 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2508 mEphemeralResolverConnection = 2509 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2510 } else { 2511 if (DEBUG_EPHEMERAL) { 2512 final String missingComponent = 2513 (ephemeralResolverComponent == null) 2514 ? (ephemeralInstallerComponent == null) 2515 ? "resolver and installer" 2516 : "resolver" 2517 : "installer"; 2518 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2519 } 2520 mEphemeralResolverComponent = null; 2521 mEphemeralInstallerComponent = null; 2522 mEphemeralResolverConnection = null; 2523 } 2524 2525 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2526 } // synchronized (mPackages) 2527 } // synchronized (mInstallLock) 2528 2529 // Now after opening every single application zip, make sure they 2530 // are all flushed. Not really needed, but keeps things nice and 2531 // tidy. 2532 Runtime.getRuntime().gc(); 2533 2534 // The initial scanning above does many calls into installd while 2535 // holding the mPackages lock, but we're mostly interested in yelling 2536 // once we have a booted system. 2537 mInstaller.setWarnIfHeld(mPackages); 2538 2539 // Expose private service for system components to use. 2540 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2541 } 2542 2543 @Override 2544 public boolean isFirstBoot() { 2545 return !mRestoredSettings; 2546 } 2547 2548 @Override 2549 public boolean isOnlyCoreApps() { 2550 return mOnlyCore; 2551 } 2552 2553 @Override 2554 public boolean isUpgrade() { 2555 return mIsUpgrade; 2556 } 2557 2558 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2559 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2560 2561 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2562 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2563 if (matches.size() == 1) { 2564 return matches.get(0).getComponentInfo().packageName; 2565 } else { 2566 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2567 return null; 2568 } 2569 } 2570 2571 private @NonNull String getRequiredInstallerLPr() { 2572 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2573 intent.addCategory(Intent.CATEGORY_DEFAULT); 2574 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2575 2576 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2577 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2578 if (matches.size() == 1) { 2579 return matches.get(0).getComponentInfo().packageName; 2580 } else { 2581 throw new RuntimeException("There must be exactly one installer; found " + matches); 2582 } 2583 } 2584 2585 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2586 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2587 2588 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2589 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2590 ResolveInfo best = null; 2591 final int N = matches.size(); 2592 for (int i = 0; i < N; i++) { 2593 final ResolveInfo cur = matches.get(i); 2594 final String packageName = cur.getComponentInfo().packageName; 2595 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2596 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2597 continue; 2598 } 2599 2600 if (best == null || cur.priority > best.priority) { 2601 best = cur; 2602 } 2603 } 2604 2605 if (best != null) { 2606 return best.getComponentInfo().getComponentName(); 2607 } else { 2608 throw new RuntimeException("There must be at least one intent filter verifier"); 2609 } 2610 } 2611 2612 private @Nullable ComponentName getEphemeralResolverLPr() { 2613 final String[] packageArray = 2614 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2615 if (packageArray.length == 0) { 2616 if (DEBUG_EPHEMERAL) { 2617 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2618 } 2619 return null; 2620 } 2621 2622 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2623 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2624 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2625 2626 final int N = resolvers.size(); 2627 if (N == 0) { 2628 if (DEBUG_EPHEMERAL) { 2629 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2630 } 2631 return null; 2632 } 2633 2634 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2635 for (int i = 0; i < N; i++) { 2636 final ResolveInfo info = resolvers.get(i); 2637 2638 if (info.serviceInfo == null) { 2639 continue; 2640 } 2641 2642 final String packageName = info.serviceInfo.packageName; 2643 if (!possiblePackages.contains(packageName)) { 2644 if (DEBUG_EPHEMERAL) { 2645 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2646 + " pkg: " + packageName + ", info:" + info); 2647 } 2648 continue; 2649 } 2650 2651 if (DEBUG_EPHEMERAL) { 2652 Slog.v(TAG, "Ephemeral resolver found;" 2653 + " pkg: " + packageName + ", info:" + info); 2654 } 2655 return new ComponentName(packageName, info.serviceInfo.name); 2656 } 2657 if (DEBUG_EPHEMERAL) { 2658 Slog.v(TAG, "Ephemeral resolver NOT found"); 2659 } 2660 return null; 2661 } 2662 2663 private @Nullable ComponentName getEphemeralInstallerLPr() { 2664 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2665 intent.addCategory(Intent.CATEGORY_DEFAULT); 2666 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2667 2668 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2669 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2670 if (matches.size() == 0) { 2671 return null; 2672 } else if (matches.size() == 1) { 2673 return matches.get(0).getComponentInfo().getComponentName(); 2674 } else { 2675 throw new RuntimeException( 2676 "There must be at most one ephemeral installer; found " + matches); 2677 } 2678 } 2679 2680 private void primeDomainVerificationsLPw(int userId) { 2681 if (DEBUG_DOMAIN_VERIFICATION) { 2682 Slog.d(TAG, "Priming domain verifications in user " + userId); 2683 } 2684 2685 SystemConfig systemConfig = SystemConfig.getInstance(); 2686 ArraySet<String> packages = systemConfig.getLinkedApps(); 2687 ArraySet<String> domains = new ArraySet<String>(); 2688 2689 for (String packageName : packages) { 2690 PackageParser.Package pkg = mPackages.get(packageName); 2691 if (pkg != null) { 2692 if (!pkg.isSystemApp()) { 2693 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2694 continue; 2695 } 2696 2697 domains.clear(); 2698 for (PackageParser.Activity a : pkg.activities) { 2699 for (ActivityIntentInfo filter : a.intents) { 2700 if (hasValidDomains(filter)) { 2701 domains.addAll(filter.getHostsList()); 2702 } 2703 } 2704 } 2705 2706 if (domains.size() > 0) { 2707 if (DEBUG_DOMAIN_VERIFICATION) { 2708 Slog.v(TAG, " + " + packageName); 2709 } 2710 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2711 // state w.r.t. the formal app-linkage "no verification attempted" state; 2712 // and then 'always' in the per-user state actually used for intent resolution. 2713 final IntentFilterVerificationInfo ivi; 2714 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2715 new ArrayList<String>(domains)); 2716 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2717 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2718 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2719 } else { 2720 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2721 + "' does not handle web links"); 2722 } 2723 } else { 2724 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2725 } 2726 } 2727 2728 scheduleWritePackageRestrictionsLocked(userId); 2729 scheduleWriteSettingsLocked(); 2730 } 2731 2732 private void applyFactoryDefaultBrowserLPw(int userId) { 2733 // The default browser app's package name is stored in a string resource, 2734 // with a product-specific overlay used for vendor customization. 2735 String browserPkg = mContext.getResources().getString( 2736 com.android.internal.R.string.default_browser); 2737 if (!TextUtils.isEmpty(browserPkg)) { 2738 // non-empty string => required to be a known package 2739 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2740 if (ps == null) { 2741 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2742 browserPkg = null; 2743 } else { 2744 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2745 } 2746 } 2747 2748 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2749 // default. If there's more than one, just leave everything alone. 2750 if (browserPkg == null) { 2751 calculateDefaultBrowserLPw(userId); 2752 } 2753 } 2754 2755 private void calculateDefaultBrowserLPw(int userId) { 2756 List<String> allBrowsers = resolveAllBrowserApps(userId); 2757 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2758 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2759 } 2760 2761 private List<String> resolveAllBrowserApps(int userId) { 2762 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2763 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2764 PackageManager.MATCH_ALL, userId); 2765 2766 final int count = list.size(); 2767 List<String> result = new ArrayList<String>(count); 2768 for (int i=0; i<count; i++) { 2769 ResolveInfo info = list.get(i); 2770 if (info.activityInfo == null 2771 || !info.handleAllWebDataURI 2772 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2773 || result.contains(info.activityInfo.packageName)) { 2774 continue; 2775 } 2776 result.add(info.activityInfo.packageName); 2777 } 2778 2779 return result; 2780 } 2781 2782 private boolean packageIsBrowser(String packageName, int userId) { 2783 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2784 PackageManager.MATCH_ALL, userId); 2785 final int N = list.size(); 2786 for (int i = 0; i < N; i++) { 2787 ResolveInfo info = list.get(i); 2788 if (packageName.equals(info.activityInfo.packageName)) { 2789 return true; 2790 } 2791 } 2792 return false; 2793 } 2794 2795 private void checkDefaultBrowser() { 2796 final int myUserId = UserHandle.myUserId(); 2797 final String packageName = getDefaultBrowserPackageName(myUserId); 2798 if (packageName != null) { 2799 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2800 if (info == null) { 2801 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2802 synchronized (mPackages) { 2803 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2804 } 2805 } 2806 } 2807 } 2808 2809 @Override 2810 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2811 throws RemoteException { 2812 try { 2813 return super.onTransact(code, data, reply, flags); 2814 } catch (RuntimeException e) { 2815 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2816 Slog.wtf(TAG, "Package Manager Crash", e); 2817 } 2818 throw e; 2819 } 2820 } 2821 2822 void cleanupInstallFailedPackage(PackageSetting ps) { 2823 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2824 2825 removeDataDirsLI(ps.volumeUuid, ps.name); 2826 if (ps.codePath != null) { 2827 removeCodePathLI(ps.codePath); 2828 } 2829 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2830 if (ps.resourcePath.isDirectory()) { 2831 FileUtils.deleteContents(ps.resourcePath); 2832 } 2833 ps.resourcePath.delete(); 2834 } 2835 mSettings.removePackageLPw(ps.name); 2836 } 2837 2838 static int[] appendInts(int[] cur, int[] add) { 2839 if (add == null) return cur; 2840 if (cur == null) return add; 2841 final int N = add.length; 2842 for (int i=0; i<N; i++) { 2843 cur = appendInt(cur, add[i]); 2844 } 2845 return cur; 2846 } 2847 2848 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2849 if (!sUserManager.exists(userId)) return null; 2850 final PackageSetting ps = (PackageSetting) p.mExtras; 2851 if (ps == null) { 2852 return null; 2853 } 2854 2855 final PermissionsState permissionsState = ps.getPermissionsState(); 2856 2857 final int[] gids = permissionsState.computeGids(userId); 2858 final Set<String> permissions = permissionsState.getPermissions(userId); 2859 final PackageUserState state = ps.readUserState(userId); 2860 2861 return PackageParser.generatePackageInfo(p, gids, flags, 2862 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2863 } 2864 2865 @Override 2866 public void checkPackageStartable(String packageName, int userId) { 2867 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2868 2869 synchronized (mPackages) { 2870 final PackageSetting ps = mSettings.mPackages.get(packageName); 2871 if (ps == null) { 2872 throw new SecurityException("Package " + packageName + " was not found!"); 2873 } 2874 2875 if (mSafeMode && !ps.isSystem()) { 2876 throw new SecurityException("Package " + packageName + " not a system app!"); 2877 } 2878 2879 if (ps.frozen) { 2880 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2881 } 2882 2883 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2884 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2885 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2886 } 2887 } 2888 } 2889 2890 @Override 2891 public boolean isPackageAvailable(String packageName, int userId) { 2892 if (!sUserManager.exists(userId)) return false; 2893 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2894 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2895 synchronized (mPackages) { 2896 PackageParser.Package p = mPackages.get(packageName); 2897 if (p != null) { 2898 final PackageSetting ps = (PackageSetting) p.mExtras; 2899 if (ps != null) { 2900 final PackageUserState state = ps.readUserState(userId); 2901 if (state != null) { 2902 return PackageParser.isAvailable(state); 2903 } 2904 } 2905 } 2906 } 2907 return false; 2908 } 2909 2910 @Override 2911 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2912 if (!sUserManager.exists(userId)) return null; 2913 flags = updateFlagsForPackage(flags, userId, packageName); 2914 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2915 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2916 // reader 2917 synchronized (mPackages) { 2918 PackageParser.Package p = mPackages.get(packageName); 2919 if (DEBUG_PACKAGE_INFO) 2920 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2921 if (p != null) { 2922 return generatePackageInfo(p, flags, userId); 2923 } 2924 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2925 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2926 } 2927 } 2928 return null; 2929 } 2930 2931 @Override 2932 public String[] currentToCanonicalPackageNames(String[] names) { 2933 String[] out = new String[names.length]; 2934 // reader 2935 synchronized (mPackages) { 2936 for (int i=names.length-1; i>=0; i--) { 2937 PackageSetting ps = mSettings.mPackages.get(names[i]); 2938 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2939 } 2940 } 2941 return out; 2942 } 2943 2944 @Override 2945 public String[] canonicalToCurrentPackageNames(String[] names) { 2946 String[] out = new String[names.length]; 2947 // reader 2948 synchronized (mPackages) { 2949 for (int i=names.length-1; i>=0; i--) { 2950 String cur = mSettings.mRenamedPackages.get(names[i]); 2951 out[i] = cur != null ? cur : names[i]; 2952 } 2953 } 2954 return out; 2955 } 2956 2957 @Override 2958 public int getPackageUid(String packageName, int flags, int userId) { 2959 if (!sUserManager.exists(userId)) return -1; 2960 flags = updateFlagsForPackage(flags, userId, packageName); 2961 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2962 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2963 2964 // reader 2965 synchronized (mPackages) { 2966 final PackageParser.Package p = mPackages.get(packageName); 2967 if (p != null && p.isMatch(flags)) { 2968 return UserHandle.getUid(userId, p.applicationInfo.uid); 2969 } 2970 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2971 final PackageSetting ps = mSettings.mPackages.get(packageName); 2972 if (ps != null && ps.isMatch(flags)) { 2973 return UserHandle.getUid(userId, ps.appId); 2974 } 2975 } 2976 } 2977 2978 return -1; 2979 } 2980 2981 @Override 2982 public int[] getPackageGids(String packageName, int flags, int userId) { 2983 if (!sUserManager.exists(userId)) return null; 2984 flags = updateFlagsForPackage(flags, userId, packageName); 2985 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2986 false /* requireFullPermission */, false /* checkShell */, 2987 "getPackageGids"); 2988 2989 // reader 2990 synchronized (mPackages) { 2991 final PackageParser.Package p = mPackages.get(packageName); 2992 if (p != null && p.isMatch(flags)) { 2993 PackageSetting ps = (PackageSetting) p.mExtras; 2994 return ps.getPermissionsState().computeGids(userId); 2995 } 2996 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2997 final PackageSetting ps = mSettings.mPackages.get(packageName); 2998 if (ps != null && ps.isMatch(flags)) { 2999 return ps.getPermissionsState().computeGids(userId); 3000 } 3001 } 3002 } 3003 3004 return null; 3005 } 3006 3007 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3008 if (bp.perm != null) { 3009 return PackageParser.generatePermissionInfo(bp.perm, flags); 3010 } 3011 PermissionInfo pi = new PermissionInfo(); 3012 pi.name = bp.name; 3013 pi.packageName = bp.sourcePackage; 3014 pi.nonLocalizedLabel = bp.name; 3015 pi.protectionLevel = bp.protectionLevel; 3016 return pi; 3017 } 3018 3019 @Override 3020 public PermissionInfo getPermissionInfo(String name, int flags) { 3021 // reader 3022 synchronized (mPackages) { 3023 final BasePermission p = mSettings.mPermissions.get(name); 3024 if (p != null) { 3025 return generatePermissionInfo(p, flags); 3026 } 3027 return null; 3028 } 3029 } 3030 3031 @Override 3032 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3033 // reader 3034 synchronized (mPackages) { 3035 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3036 for (BasePermission p : mSettings.mPermissions.values()) { 3037 if (group == null) { 3038 if (p.perm == null || p.perm.info.group == null) { 3039 out.add(generatePermissionInfo(p, flags)); 3040 } 3041 } else { 3042 if (p.perm != null && group.equals(p.perm.info.group)) { 3043 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3044 } 3045 } 3046 } 3047 3048 if (out.size() > 0) { 3049 return out; 3050 } 3051 return mPermissionGroups.containsKey(group) ? out : null; 3052 } 3053 } 3054 3055 @Override 3056 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3057 // reader 3058 synchronized (mPackages) { 3059 return PackageParser.generatePermissionGroupInfo( 3060 mPermissionGroups.get(name), flags); 3061 } 3062 } 3063 3064 @Override 3065 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3066 // reader 3067 synchronized (mPackages) { 3068 final int N = mPermissionGroups.size(); 3069 ArrayList<PermissionGroupInfo> out 3070 = new ArrayList<PermissionGroupInfo>(N); 3071 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3072 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3073 } 3074 return out; 3075 } 3076 } 3077 3078 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3079 int userId) { 3080 if (!sUserManager.exists(userId)) return null; 3081 PackageSetting ps = mSettings.mPackages.get(packageName); 3082 if (ps != null) { 3083 if (ps.pkg == null) { 3084 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3085 flags, userId); 3086 if (pInfo != null) { 3087 return pInfo.applicationInfo; 3088 } 3089 return null; 3090 } 3091 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3092 ps.readUserState(userId), userId); 3093 } 3094 return null; 3095 } 3096 3097 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3098 int userId) { 3099 if (!sUserManager.exists(userId)) return null; 3100 PackageSetting ps = mSettings.mPackages.get(packageName); 3101 if (ps != null) { 3102 PackageParser.Package pkg = ps.pkg; 3103 if (pkg == null) { 3104 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3105 return null; 3106 } 3107 // Only data remains, so we aren't worried about code paths 3108 pkg = new PackageParser.Package(packageName); 3109 pkg.applicationInfo.packageName = packageName; 3110 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3111 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3112 pkg.applicationInfo.uid = ps.appId; 3113 pkg.applicationInfo.initForUser(userId); 3114 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3115 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3116 } 3117 return generatePackageInfo(pkg, flags, userId); 3118 } 3119 return null; 3120 } 3121 3122 @Override 3123 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3124 if (!sUserManager.exists(userId)) return null; 3125 flags = updateFlagsForApplication(flags, userId, packageName); 3126 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3127 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3128 // writer 3129 synchronized (mPackages) { 3130 PackageParser.Package p = mPackages.get(packageName); 3131 if (DEBUG_PACKAGE_INFO) Log.v( 3132 TAG, "getApplicationInfo " + packageName 3133 + ": " + p); 3134 if (p != null) { 3135 PackageSetting ps = mSettings.mPackages.get(packageName); 3136 if (ps == null) return null; 3137 // Note: isEnabledLP() does not apply here - always return info 3138 return PackageParser.generateApplicationInfo( 3139 p, flags, ps.readUserState(userId), userId); 3140 } 3141 if ("android".equals(packageName)||"system".equals(packageName)) { 3142 return mAndroidApplication; 3143 } 3144 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3145 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3146 } 3147 } 3148 return null; 3149 } 3150 3151 @Override 3152 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3153 final IPackageDataObserver observer) { 3154 mContext.enforceCallingOrSelfPermission( 3155 android.Manifest.permission.CLEAR_APP_CACHE, null); 3156 // Queue up an async operation since clearing cache may take a little while. 3157 mHandler.post(new Runnable() { 3158 public void run() { 3159 mHandler.removeCallbacks(this); 3160 boolean success = true; 3161 synchronized (mInstallLock) { 3162 try { 3163 mInstaller.freeCache(volumeUuid, freeStorageSize); 3164 } catch (InstallerException e) { 3165 Slog.w(TAG, "Couldn't clear application caches: " + e); 3166 success = false; 3167 } 3168 } 3169 if (observer != null) { 3170 try { 3171 observer.onRemoveCompleted(null, success); 3172 } catch (RemoteException e) { 3173 Slog.w(TAG, "RemoveException when invoking call back"); 3174 } 3175 } 3176 } 3177 }); 3178 } 3179 3180 @Override 3181 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3182 final IntentSender pi) { 3183 mContext.enforceCallingOrSelfPermission( 3184 android.Manifest.permission.CLEAR_APP_CACHE, null); 3185 // Queue up an async operation since clearing cache may take a little while. 3186 mHandler.post(new Runnable() { 3187 public void run() { 3188 mHandler.removeCallbacks(this); 3189 boolean success = true; 3190 synchronized (mInstallLock) { 3191 try { 3192 mInstaller.freeCache(volumeUuid, freeStorageSize); 3193 } catch (InstallerException e) { 3194 Slog.w(TAG, "Couldn't clear application caches: " + e); 3195 success = false; 3196 } 3197 } 3198 if(pi != null) { 3199 try { 3200 // Callback via pending intent 3201 int code = success ? 1 : 0; 3202 pi.sendIntent(null, code, null, 3203 null, null); 3204 } catch (SendIntentException e1) { 3205 Slog.i(TAG, "Failed to send pending intent"); 3206 } 3207 } 3208 } 3209 }); 3210 } 3211 3212 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3213 synchronized (mInstallLock) { 3214 try { 3215 mInstaller.freeCache(volumeUuid, freeStorageSize); 3216 } catch (InstallerException e) { 3217 throw new IOException("Failed to free enough space", e); 3218 } 3219 } 3220 } 3221 3222 /** 3223 * Return if the user key is currently unlocked. 3224 */ 3225 private boolean isUserKeyUnlocked(int userId) { 3226 if (StorageManager.isFileBasedEncryptionEnabled()) { 3227 final IMountService mount = IMountService.Stub 3228 .asInterface(ServiceManager.getService("mount")); 3229 if (mount == null) { 3230 Slog.w(TAG, "Early during boot, assuming locked"); 3231 return false; 3232 } 3233 final long token = Binder.clearCallingIdentity(); 3234 try { 3235 return mount.isUserKeyUnlocked(userId); 3236 } catch (RemoteException e) { 3237 throw e.rethrowAsRuntimeException(); 3238 } finally { 3239 Binder.restoreCallingIdentity(token); 3240 } 3241 } else { 3242 return true; 3243 } 3244 } 3245 3246 /** 3247 * Update given flags based on encryption status of current user. 3248 */ 3249 private int updateFlags(int flags, int userId) { 3250 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3251 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3252 // Caller expressed an explicit opinion about what encryption 3253 // aware/unaware components they want to see, so fall through and 3254 // give them what they want 3255 } else { 3256 // Caller expressed no opinion, so match based on user state 3257 if (isUserKeyUnlocked(userId)) { 3258 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3259 } else { 3260 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3261 } 3262 } 3263 return flags; 3264 } 3265 3266 /** 3267 * Update given flags when being used to request {@link PackageInfo}. 3268 */ 3269 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3270 boolean triaged = true; 3271 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3272 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3273 // Caller is asking for component details, so they'd better be 3274 // asking for specific encryption matching behavior, or be triaged 3275 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3276 | PackageManager.MATCH_ENCRYPTION_AWARE 3277 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3278 triaged = false; 3279 } 3280 } 3281 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3282 | PackageManager.MATCH_SYSTEM_ONLY 3283 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3284 triaged = false; 3285 } 3286 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3287 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3288 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3289 } 3290 return updateFlags(flags, userId); 3291 } 3292 3293 /** 3294 * Update given flags when being used to request {@link ApplicationInfo}. 3295 */ 3296 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3297 return updateFlagsForPackage(flags, userId, cookie); 3298 } 3299 3300 /** 3301 * Update given flags when being used to request {@link ComponentInfo}. 3302 */ 3303 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3304 if (cookie instanceof Intent) { 3305 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3306 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3307 } 3308 } 3309 3310 boolean triaged = true; 3311 // Caller is asking for component details, so they'd better be 3312 // asking for specific encryption matching behavior, or be triaged 3313 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3314 | PackageManager.MATCH_ENCRYPTION_AWARE 3315 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3316 triaged = false; 3317 } 3318 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3319 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3320 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3321 } 3322 3323 return updateFlags(flags, userId); 3324 } 3325 3326 /** 3327 * Update given flags when being used to request {@link ResolveInfo}. 3328 */ 3329 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3330 // Safe mode means we shouldn't match any third-party components 3331 if (mSafeMode) { 3332 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3333 } 3334 3335 return updateFlagsForComponent(flags, userId, cookie); 3336 } 3337 3338 @Override 3339 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3340 if (!sUserManager.exists(userId)) return null; 3341 flags = updateFlagsForComponent(flags, userId, component); 3342 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3343 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3344 synchronized (mPackages) { 3345 PackageParser.Activity a = mActivities.mActivities.get(component); 3346 3347 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3348 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3349 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3350 if (ps == null) return null; 3351 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3352 userId); 3353 } 3354 if (mResolveComponentName.equals(component)) { 3355 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3356 new PackageUserState(), userId); 3357 } 3358 } 3359 return null; 3360 } 3361 3362 @Override 3363 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3364 String resolvedType) { 3365 synchronized (mPackages) { 3366 if (component.equals(mResolveComponentName)) { 3367 // The resolver supports EVERYTHING! 3368 return true; 3369 } 3370 PackageParser.Activity a = mActivities.mActivities.get(component); 3371 if (a == null) { 3372 return false; 3373 } 3374 for (int i=0; i<a.intents.size(); i++) { 3375 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3376 intent.getData(), intent.getCategories(), TAG) >= 0) { 3377 return true; 3378 } 3379 } 3380 return false; 3381 } 3382 } 3383 3384 @Override 3385 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3386 if (!sUserManager.exists(userId)) return null; 3387 flags = updateFlagsForComponent(flags, userId, component); 3388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3389 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3390 synchronized (mPackages) { 3391 PackageParser.Activity a = mReceivers.mActivities.get(component); 3392 if (DEBUG_PACKAGE_INFO) Log.v( 3393 TAG, "getReceiverInfo " + component + ": " + a); 3394 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3395 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3396 if (ps == null) return null; 3397 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3398 userId); 3399 } 3400 } 3401 return null; 3402 } 3403 3404 @Override 3405 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3406 if (!sUserManager.exists(userId)) return null; 3407 flags = updateFlagsForComponent(flags, userId, component); 3408 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3409 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3410 synchronized (mPackages) { 3411 PackageParser.Service s = mServices.mServices.get(component); 3412 if (DEBUG_PACKAGE_INFO) Log.v( 3413 TAG, "getServiceInfo " + component + ": " + s); 3414 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3415 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3416 if (ps == null) return null; 3417 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3418 userId); 3419 } 3420 } 3421 return null; 3422 } 3423 3424 @Override 3425 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3426 if (!sUserManager.exists(userId)) return null; 3427 flags = updateFlagsForComponent(flags, userId, component); 3428 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3429 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3430 synchronized (mPackages) { 3431 PackageParser.Provider p = mProviders.mProviders.get(component); 3432 if (DEBUG_PACKAGE_INFO) Log.v( 3433 TAG, "getProviderInfo " + component + ": " + p); 3434 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3435 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3436 if (ps == null) return null; 3437 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3438 userId); 3439 } 3440 } 3441 return null; 3442 } 3443 3444 @Override 3445 public String[] getSystemSharedLibraryNames() { 3446 Set<String> libSet; 3447 synchronized (mPackages) { 3448 libSet = mSharedLibraries.keySet(); 3449 int size = libSet.size(); 3450 if (size > 0) { 3451 String[] libs = new String[size]; 3452 libSet.toArray(libs); 3453 return libs; 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3461 synchronized (mPackages) { 3462 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3463 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3464 if (libraryEntry != null) { 3465 return libraryEntry.apk; 3466 } 3467 } 3468 return null; 3469 } 3470 3471 @Override 3472 public FeatureInfo[] getSystemAvailableFeatures() { 3473 Collection<FeatureInfo> featSet; 3474 synchronized (mPackages) { 3475 featSet = mAvailableFeatures.values(); 3476 int size = featSet.size(); 3477 if (size > 0) { 3478 FeatureInfo[] features = new FeatureInfo[size+1]; 3479 featSet.toArray(features); 3480 FeatureInfo fi = new FeatureInfo(); 3481 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3482 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3483 features[size] = fi; 3484 return features; 3485 } 3486 } 3487 return null; 3488 } 3489 3490 @Override 3491 public boolean hasSystemFeature(String name, int version) { 3492 synchronized (mPackages) { 3493 final FeatureInfo feat = mAvailableFeatures.get(name); 3494 if (feat == null) { 3495 return false; 3496 } else { 3497 return feat.version >= version; 3498 } 3499 } 3500 } 3501 3502 @Override 3503 public int checkPermission(String permName, String pkgName, int userId) { 3504 if (!sUserManager.exists(userId)) { 3505 return PackageManager.PERMISSION_DENIED; 3506 } 3507 3508 synchronized (mPackages) { 3509 final PackageParser.Package p = mPackages.get(pkgName); 3510 if (p != null && p.mExtras != null) { 3511 final PackageSetting ps = (PackageSetting) p.mExtras; 3512 final PermissionsState permissionsState = ps.getPermissionsState(); 3513 if (permissionsState.hasPermission(permName, userId)) { 3514 return PackageManager.PERMISSION_GRANTED; 3515 } 3516 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3517 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3518 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3519 return PackageManager.PERMISSION_GRANTED; 3520 } 3521 } 3522 } 3523 3524 return PackageManager.PERMISSION_DENIED; 3525 } 3526 3527 @Override 3528 public int checkUidPermission(String permName, int uid) { 3529 final int userId = UserHandle.getUserId(uid); 3530 3531 if (!sUserManager.exists(userId)) { 3532 return PackageManager.PERMISSION_DENIED; 3533 } 3534 3535 synchronized (mPackages) { 3536 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3537 if (obj != null) { 3538 final SettingBase ps = (SettingBase) obj; 3539 final PermissionsState permissionsState = ps.getPermissionsState(); 3540 if (permissionsState.hasPermission(permName, userId)) { 3541 return PackageManager.PERMISSION_GRANTED; 3542 } 3543 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3544 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3545 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3546 return PackageManager.PERMISSION_GRANTED; 3547 } 3548 } else { 3549 ArraySet<String> perms = mSystemPermissions.get(uid); 3550 if (perms != null) { 3551 if (perms.contains(permName)) { 3552 return PackageManager.PERMISSION_GRANTED; 3553 } 3554 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3555 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3556 return PackageManager.PERMISSION_GRANTED; 3557 } 3558 } 3559 } 3560 } 3561 3562 return PackageManager.PERMISSION_DENIED; 3563 } 3564 3565 @Override 3566 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3567 if (UserHandle.getCallingUserId() != userId) { 3568 mContext.enforceCallingPermission( 3569 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3570 "isPermissionRevokedByPolicy for user " + userId); 3571 } 3572 3573 if (checkPermission(permission, packageName, userId) 3574 == PackageManager.PERMISSION_GRANTED) { 3575 return false; 3576 } 3577 3578 final long identity = Binder.clearCallingIdentity(); 3579 try { 3580 final int flags = getPermissionFlags(permission, packageName, userId); 3581 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3582 } finally { 3583 Binder.restoreCallingIdentity(identity); 3584 } 3585 } 3586 3587 @Override 3588 public String getPermissionControllerPackageName() { 3589 synchronized (mPackages) { 3590 return mRequiredInstallerPackage; 3591 } 3592 } 3593 3594 /** 3595 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3596 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3597 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3598 * @param message the message to log on security exception 3599 */ 3600 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3601 boolean checkShell, String message) { 3602 if (userId < 0) { 3603 throw new IllegalArgumentException("Invalid userId " + userId); 3604 } 3605 if (checkShell) { 3606 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3607 } 3608 if (userId == UserHandle.getUserId(callingUid)) return; 3609 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3610 if (requireFullPermission) { 3611 mContext.enforceCallingOrSelfPermission( 3612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3613 } else { 3614 try { 3615 mContext.enforceCallingOrSelfPermission( 3616 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3617 } catch (SecurityException se) { 3618 mContext.enforceCallingOrSelfPermission( 3619 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3620 } 3621 } 3622 } 3623 } 3624 3625 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3626 if (callingUid == Process.SHELL_UID) { 3627 if (userHandle >= 0 3628 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3629 throw new SecurityException("Shell does not have permission to access user " 3630 + userHandle); 3631 } else if (userHandle < 0) { 3632 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3633 + Debug.getCallers(3)); 3634 } 3635 } 3636 } 3637 3638 private BasePermission findPermissionTreeLP(String permName) { 3639 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3640 if (permName.startsWith(bp.name) && 3641 permName.length() > bp.name.length() && 3642 permName.charAt(bp.name.length()) == '.') { 3643 return bp; 3644 } 3645 } 3646 return null; 3647 } 3648 3649 private BasePermission checkPermissionTreeLP(String permName) { 3650 if (permName != null) { 3651 BasePermission bp = findPermissionTreeLP(permName); 3652 if (bp != null) { 3653 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3654 return bp; 3655 } 3656 throw new SecurityException("Calling uid " 3657 + Binder.getCallingUid() 3658 + " is not allowed to add to permission tree " 3659 + bp.name + " owned by uid " + bp.uid); 3660 } 3661 } 3662 throw new SecurityException("No permission tree found for " + permName); 3663 } 3664 3665 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3666 if (s1 == null) { 3667 return s2 == null; 3668 } 3669 if (s2 == null) { 3670 return false; 3671 } 3672 if (s1.getClass() != s2.getClass()) { 3673 return false; 3674 } 3675 return s1.equals(s2); 3676 } 3677 3678 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3679 if (pi1.icon != pi2.icon) return false; 3680 if (pi1.logo != pi2.logo) return false; 3681 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3682 if (!compareStrings(pi1.name, pi2.name)) return false; 3683 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3684 // We'll take care of setting this one. 3685 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3686 // These are not currently stored in settings. 3687 //if (!compareStrings(pi1.group, pi2.group)) return false; 3688 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3689 //if (pi1.labelRes != pi2.labelRes) return false; 3690 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3691 return true; 3692 } 3693 3694 int permissionInfoFootprint(PermissionInfo info) { 3695 int size = info.name.length(); 3696 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3697 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3698 return size; 3699 } 3700 3701 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3702 int size = 0; 3703 for (BasePermission perm : mSettings.mPermissions.values()) { 3704 if (perm.uid == tree.uid) { 3705 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3706 } 3707 } 3708 return size; 3709 } 3710 3711 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3712 // We calculate the max size of permissions defined by this uid and throw 3713 // if that plus the size of 'info' would exceed our stated maximum. 3714 if (tree.uid != Process.SYSTEM_UID) { 3715 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3716 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3717 throw new SecurityException("Permission tree size cap exceeded"); 3718 } 3719 } 3720 } 3721 3722 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3723 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3724 throw new SecurityException("Label must be specified in permission"); 3725 } 3726 BasePermission tree = checkPermissionTreeLP(info.name); 3727 BasePermission bp = mSettings.mPermissions.get(info.name); 3728 boolean added = bp == null; 3729 boolean changed = true; 3730 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3731 if (added) { 3732 enforcePermissionCapLocked(info, tree); 3733 bp = new BasePermission(info.name, tree.sourcePackage, 3734 BasePermission.TYPE_DYNAMIC); 3735 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3736 throw new SecurityException( 3737 "Not allowed to modify non-dynamic permission " 3738 + info.name); 3739 } else { 3740 if (bp.protectionLevel == fixedLevel 3741 && bp.perm.owner.equals(tree.perm.owner) 3742 && bp.uid == tree.uid 3743 && comparePermissionInfos(bp.perm.info, info)) { 3744 changed = false; 3745 } 3746 } 3747 bp.protectionLevel = fixedLevel; 3748 info = new PermissionInfo(info); 3749 info.protectionLevel = fixedLevel; 3750 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3751 bp.perm.info.packageName = tree.perm.info.packageName; 3752 bp.uid = tree.uid; 3753 if (added) { 3754 mSettings.mPermissions.put(info.name, bp); 3755 } 3756 if (changed) { 3757 if (!async) { 3758 mSettings.writeLPr(); 3759 } else { 3760 scheduleWriteSettingsLocked(); 3761 } 3762 } 3763 return added; 3764 } 3765 3766 @Override 3767 public boolean addPermission(PermissionInfo info) { 3768 synchronized (mPackages) { 3769 return addPermissionLocked(info, false); 3770 } 3771 } 3772 3773 @Override 3774 public boolean addPermissionAsync(PermissionInfo info) { 3775 synchronized (mPackages) { 3776 return addPermissionLocked(info, true); 3777 } 3778 } 3779 3780 @Override 3781 public void removePermission(String name) { 3782 synchronized (mPackages) { 3783 checkPermissionTreeLP(name); 3784 BasePermission bp = mSettings.mPermissions.get(name); 3785 if (bp != null) { 3786 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3787 throw new SecurityException( 3788 "Not allowed to modify non-dynamic permission " 3789 + name); 3790 } 3791 mSettings.mPermissions.remove(name); 3792 mSettings.writeLPr(); 3793 } 3794 } 3795 } 3796 3797 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3798 BasePermission bp) { 3799 int index = pkg.requestedPermissions.indexOf(bp.name); 3800 if (index == -1) { 3801 throw new SecurityException("Package " + pkg.packageName 3802 + " has not requested permission " + bp.name); 3803 } 3804 if (!bp.isRuntime() && !bp.isDevelopment()) { 3805 throw new SecurityException("Permission " + bp.name 3806 + " is not a changeable permission type"); 3807 } 3808 } 3809 3810 @Override 3811 public void grantRuntimePermission(String packageName, String name, final int userId) { 3812 if (!sUserManager.exists(userId)) { 3813 Log.e(TAG, "No such user:" + userId); 3814 return; 3815 } 3816 3817 mContext.enforceCallingOrSelfPermission( 3818 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3819 "grantRuntimePermission"); 3820 3821 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3822 true /* requireFullPermission */, true /* checkShell */, 3823 "grantRuntimePermission"); 3824 3825 final int uid; 3826 final SettingBase sb; 3827 3828 synchronized (mPackages) { 3829 final PackageParser.Package pkg = mPackages.get(packageName); 3830 if (pkg == null) { 3831 throw new IllegalArgumentException("Unknown package: " + packageName); 3832 } 3833 3834 final BasePermission bp = mSettings.mPermissions.get(name); 3835 if (bp == null) { 3836 throw new IllegalArgumentException("Unknown permission: " + name); 3837 } 3838 3839 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3840 3841 // If a permission review is required for legacy apps we represent 3842 // their permissions as always granted runtime ones since we need 3843 // to keep the review required permission flag per user while an 3844 // install permission's state is shared across all users. 3845 if (Build.PERMISSIONS_REVIEW_REQUIRED 3846 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3847 && bp.isRuntime()) { 3848 return; 3849 } 3850 3851 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3852 sb = (SettingBase) pkg.mExtras; 3853 if (sb == null) { 3854 throw new IllegalArgumentException("Unknown package: " + packageName); 3855 } 3856 3857 final PermissionsState permissionsState = sb.getPermissionsState(); 3858 3859 final int flags = permissionsState.getPermissionFlags(name, userId); 3860 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3861 throw new SecurityException("Cannot grant system fixed permission " 3862 + name + " for package " + packageName); 3863 } 3864 3865 if (bp.isDevelopment()) { 3866 // Development permissions must be handled specially, since they are not 3867 // normal runtime permissions. For now they apply to all users. 3868 if (permissionsState.grantInstallPermission(bp) != 3869 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3870 scheduleWriteSettingsLocked(); 3871 } 3872 return; 3873 } 3874 3875 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3876 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3877 return; 3878 } 3879 3880 final int result = permissionsState.grantRuntimePermission(bp, userId); 3881 switch (result) { 3882 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3883 return; 3884 } 3885 3886 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3887 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3888 mHandler.post(new Runnable() { 3889 @Override 3890 public void run() { 3891 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3892 } 3893 }); 3894 } 3895 break; 3896 } 3897 3898 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3899 3900 // Not critical if that is lost - app has to request again. 3901 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3902 } 3903 3904 // Only need to do this if user is initialized. Otherwise it's a new user 3905 // and there are no processes running as the user yet and there's no need 3906 // to make an expensive call to remount processes for the changed permissions. 3907 if (READ_EXTERNAL_STORAGE.equals(name) 3908 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3909 final long token = Binder.clearCallingIdentity(); 3910 try { 3911 if (sUserManager.isInitialized(userId)) { 3912 MountServiceInternal mountServiceInternal = LocalServices.getService( 3913 MountServiceInternal.class); 3914 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3915 } 3916 } finally { 3917 Binder.restoreCallingIdentity(token); 3918 } 3919 } 3920 } 3921 3922 @Override 3923 public void revokeRuntimePermission(String packageName, String name, int userId) { 3924 if (!sUserManager.exists(userId)) { 3925 Log.e(TAG, "No such user:" + userId); 3926 return; 3927 } 3928 3929 mContext.enforceCallingOrSelfPermission( 3930 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3931 "revokeRuntimePermission"); 3932 3933 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3934 true /* requireFullPermission */, true /* checkShell */, 3935 "revokeRuntimePermission"); 3936 3937 final int appId; 3938 3939 synchronized (mPackages) { 3940 final PackageParser.Package pkg = mPackages.get(packageName); 3941 if (pkg == null) { 3942 throw new IllegalArgumentException("Unknown package: " + packageName); 3943 } 3944 3945 final BasePermission bp = mSettings.mPermissions.get(name); 3946 if (bp == null) { 3947 throw new IllegalArgumentException("Unknown permission: " + name); 3948 } 3949 3950 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3951 3952 // If a permission review is required for legacy apps we represent 3953 // their permissions as always granted runtime ones since we need 3954 // to keep the review required permission flag per user while an 3955 // install permission's state is shared across all users. 3956 if (Build.PERMISSIONS_REVIEW_REQUIRED 3957 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3958 && bp.isRuntime()) { 3959 return; 3960 } 3961 3962 SettingBase sb = (SettingBase) pkg.mExtras; 3963 if (sb == null) { 3964 throw new IllegalArgumentException("Unknown package: " + packageName); 3965 } 3966 3967 final PermissionsState permissionsState = sb.getPermissionsState(); 3968 3969 final int flags = permissionsState.getPermissionFlags(name, userId); 3970 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3971 throw new SecurityException("Cannot revoke system fixed permission " 3972 + name + " for package " + packageName); 3973 } 3974 3975 if (bp.isDevelopment()) { 3976 // Development permissions must be handled specially, since they are not 3977 // normal runtime permissions. For now they apply to all users. 3978 if (permissionsState.revokeInstallPermission(bp) != 3979 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3980 scheduleWriteSettingsLocked(); 3981 } 3982 return; 3983 } 3984 3985 if (permissionsState.revokeRuntimePermission(bp, userId) == 3986 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3987 return; 3988 } 3989 3990 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3991 3992 // Critical, after this call app should never have the permission. 3993 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3994 3995 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3996 } 3997 3998 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3999 } 4000 4001 @Override 4002 public void resetRuntimePermissions() { 4003 mContext.enforceCallingOrSelfPermission( 4004 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4005 "revokeRuntimePermission"); 4006 4007 int callingUid = Binder.getCallingUid(); 4008 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4009 mContext.enforceCallingOrSelfPermission( 4010 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4011 "resetRuntimePermissions"); 4012 } 4013 4014 synchronized (mPackages) { 4015 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4016 for (int userId : UserManagerService.getInstance().getUserIds()) { 4017 final int packageCount = mPackages.size(); 4018 for (int i = 0; i < packageCount; i++) { 4019 PackageParser.Package pkg = mPackages.valueAt(i); 4020 if (!(pkg.mExtras instanceof PackageSetting)) { 4021 continue; 4022 } 4023 PackageSetting ps = (PackageSetting) pkg.mExtras; 4024 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4025 } 4026 } 4027 } 4028 } 4029 4030 @Override 4031 public int getPermissionFlags(String name, String packageName, int userId) { 4032 if (!sUserManager.exists(userId)) { 4033 return 0; 4034 } 4035 4036 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4037 4038 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4039 true /* requireFullPermission */, false /* checkShell */, 4040 "getPermissionFlags"); 4041 4042 synchronized (mPackages) { 4043 final PackageParser.Package pkg = mPackages.get(packageName); 4044 if (pkg == null) { 4045 throw new IllegalArgumentException("Unknown package: " + packageName); 4046 } 4047 4048 final BasePermission bp = mSettings.mPermissions.get(name); 4049 if (bp == null) { 4050 throw new IllegalArgumentException("Unknown permission: " + name); 4051 } 4052 4053 SettingBase sb = (SettingBase) pkg.mExtras; 4054 if (sb == null) { 4055 throw new IllegalArgumentException("Unknown package: " + packageName); 4056 } 4057 4058 PermissionsState permissionsState = sb.getPermissionsState(); 4059 return permissionsState.getPermissionFlags(name, userId); 4060 } 4061 } 4062 4063 @Override 4064 public void updatePermissionFlags(String name, String packageName, int flagMask, 4065 int flagValues, int userId) { 4066 if (!sUserManager.exists(userId)) { 4067 return; 4068 } 4069 4070 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4071 4072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4073 true /* requireFullPermission */, true /* checkShell */, 4074 "updatePermissionFlags"); 4075 4076 // Only the system can change these flags and nothing else. 4077 if (getCallingUid() != Process.SYSTEM_UID) { 4078 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4079 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4080 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4081 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4082 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4083 } 4084 4085 synchronized (mPackages) { 4086 final PackageParser.Package pkg = mPackages.get(packageName); 4087 if (pkg == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final BasePermission bp = mSettings.mPermissions.get(name); 4092 if (bp == null) { 4093 throw new IllegalArgumentException("Unknown permission: " + name); 4094 } 4095 4096 SettingBase sb = (SettingBase) pkg.mExtras; 4097 if (sb == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 PermissionsState permissionsState = sb.getPermissionsState(); 4102 4103 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4104 4105 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4106 // Install and runtime permissions are stored in different places, 4107 // so figure out what permission changed and persist the change. 4108 if (permissionsState.getInstallPermissionState(name) != null) { 4109 scheduleWriteSettingsLocked(); 4110 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4111 || hadState) { 4112 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4113 } 4114 } 4115 } 4116 } 4117 4118 /** 4119 * Update the permission flags for all packages and runtime permissions of a user in order 4120 * to allow device or profile owner to remove POLICY_FIXED. 4121 */ 4122 @Override 4123 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4124 if (!sUserManager.exists(userId)) { 4125 return; 4126 } 4127 4128 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4129 4130 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4131 true /* requireFullPermission */, true /* checkShell */, 4132 "updatePermissionFlagsForAllApps"); 4133 4134 // Only the system can change system fixed flags. 4135 if (getCallingUid() != Process.SYSTEM_UID) { 4136 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4137 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4138 } 4139 4140 synchronized (mPackages) { 4141 boolean changed = false; 4142 final int packageCount = mPackages.size(); 4143 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4144 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4145 SettingBase sb = (SettingBase) pkg.mExtras; 4146 if (sb == null) { 4147 continue; 4148 } 4149 PermissionsState permissionsState = sb.getPermissionsState(); 4150 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4151 userId, flagMask, flagValues); 4152 } 4153 if (changed) { 4154 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4155 } 4156 } 4157 } 4158 4159 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4160 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4161 != PackageManager.PERMISSION_GRANTED 4162 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4163 != PackageManager.PERMISSION_GRANTED) { 4164 throw new SecurityException(message + " requires " 4165 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4166 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4167 } 4168 } 4169 4170 @Override 4171 public boolean shouldShowRequestPermissionRationale(String permissionName, 4172 String packageName, int userId) { 4173 if (UserHandle.getCallingUserId() != userId) { 4174 mContext.enforceCallingPermission( 4175 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4176 "canShowRequestPermissionRationale for user " + userId); 4177 } 4178 4179 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4180 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4181 return false; 4182 } 4183 4184 if (checkPermission(permissionName, packageName, userId) 4185 == PackageManager.PERMISSION_GRANTED) { 4186 return false; 4187 } 4188 4189 final int flags; 4190 4191 final long identity = Binder.clearCallingIdentity(); 4192 try { 4193 flags = getPermissionFlags(permissionName, 4194 packageName, userId); 4195 } finally { 4196 Binder.restoreCallingIdentity(identity); 4197 } 4198 4199 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4200 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4201 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4202 4203 if ((flags & fixedFlags) != 0) { 4204 return false; 4205 } 4206 4207 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4208 } 4209 4210 @Override 4211 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4212 mContext.enforceCallingOrSelfPermission( 4213 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4214 "addOnPermissionsChangeListener"); 4215 4216 synchronized (mPackages) { 4217 mOnPermissionChangeListeners.addListenerLocked(listener); 4218 } 4219 } 4220 4221 @Override 4222 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4223 synchronized (mPackages) { 4224 mOnPermissionChangeListeners.removeListenerLocked(listener); 4225 } 4226 } 4227 4228 @Override 4229 public boolean isProtectedBroadcast(String actionName) { 4230 synchronized (mPackages) { 4231 if (mProtectedBroadcasts.contains(actionName)) { 4232 return true; 4233 } else if (actionName != null) { 4234 // TODO: remove these terrible hacks 4235 if (actionName.startsWith("android.net.netmon.lingerExpired") 4236 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4237 || actionName.startsWith("com.android.internal.telephony.data-reconnect")) { 4238 return true; 4239 } 4240 } 4241 } 4242 return false; 4243 } 4244 4245 @Override 4246 public int checkSignatures(String pkg1, String pkg2) { 4247 synchronized (mPackages) { 4248 final PackageParser.Package p1 = mPackages.get(pkg1); 4249 final PackageParser.Package p2 = mPackages.get(pkg2); 4250 if (p1 == null || p1.mExtras == null 4251 || p2 == null || p2.mExtras == null) { 4252 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4253 } 4254 return compareSignatures(p1.mSignatures, p2.mSignatures); 4255 } 4256 } 4257 4258 @Override 4259 public int checkUidSignatures(int uid1, int uid2) { 4260 // Map to base uids. 4261 uid1 = UserHandle.getAppId(uid1); 4262 uid2 = UserHandle.getAppId(uid2); 4263 // reader 4264 synchronized (mPackages) { 4265 Signature[] s1; 4266 Signature[] s2; 4267 Object obj = mSettings.getUserIdLPr(uid1); 4268 if (obj != null) { 4269 if (obj instanceof SharedUserSetting) { 4270 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4271 } else if (obj instanceof PackageSetting) { 4272 s1 = ((PackageSetting)obj).signatures.mSignatures; 4273 } else { 4274 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4275 } 4276 } else { 4277 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4278 } 4279 obj = mSettings.getUserIdLPr(uid2); 4280 if (obj != null) { 4281 if (obj instanceof SharedUserSetting) { 4282 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4283 } else if (obj instanceof PackageSetting) { 4284 s2 = ((PackageSetting)obj).signatures.mSignatures; 4285 } else { 4286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4287 } 4288 } else { 4289 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4290 } 4291 return compareSignatures(s1, s2); 4292 } 4293 } 4294 4295 private void killUid(int appId, int userId, String reason) { 4296 final long identity = Binder.clearCallingIdentity(); 4297 try { 4298 IActivityManager am = ActivityManagerNative.getDefault(); 4299 if (am != null) { 4300 try { 4301 am.killUid(appId, userId, reason); 4302 } catch (RemoteException e) { 4303 /* ignore - same process */ 4304 } 4305 } 4306 } finally { 4307 Binder.restoreCallingIdentity(identity); 4308 } 4309 } 4310 4311 /** 4312 * Compares two sets of signatures. Returns: 4313 * <br /> 4314 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4315 * <br /> 4316 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4317 * <br /> 4318 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4319 * <br /> 4320 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4321 * <br /> 4322 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4323 */ 4324 static int compareSignatures(Signature[] s1, Signature[] s2) { 4325 if (s1 == null) { 4326 return s2 == null 4327 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4328 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4329 } 4330 4331 if (s2 == null) { 4332 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4333 } 4334 4335 if (s1.length != s2.length) { 4336 return PackageManager.SIGNATURE_NO_MATCH; 4337 } 4338 4339 // Since both signature sets are of size 1, we can compare without HashSets. 4340 if (s1.length == 1) { 4341 return s1[0].equals(s2[0]) ? 4342 PackageManager.SIGNATURE_MATCH : 4343 PackageManager.SIGNATURE_NO_MATCH; 4344 } 4345 4346 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4347 for (Signature sig : s1) { 4348 set1.add(sig); 4349 } 4350 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4351 for (Signature sig : s2) { 4352 set2.add(sig); 4353 } 4354 // Make sure s2 contains all signatures in s1. 4355 if (set1.equals(set2)) { 4356 return PackageManager.SIGNATURE_MATCH; 4357 } 4358 return PackageManager.SIGNATURE_NO_MATCH; 4359 } 4360 4361 /** 4362 * If the database version for this type of package (internal storage or 4363 * external storage) is less than the version where package signatures 4364 * were updated, return true. 4365 */ 4366 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4367 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4368 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4369 } 4370 4371 /** 4372 * Used for backward compatibility to make sure any packages with 4373 * certificate chains get upgraded to the new style. {@code existingSigs} 4374 * will be in the old format (since they were stored on disk from before the 4375 * system upgrade) and {@code scannedSigs} will be in the newer format. 4376 */ 4377 private int compareSignaturesCompat(PackageSignatures existingSigs, 4378 PackageParser.Package scannedPkg) { 4379 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4380 return PackageManager.SIGNATURE_NO_MATCH; 4381 } 4382 4383 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4384 for (Signature sig : existingSigs.mSignatures) { 4385 existingSet.add(sig); 4386 } 4387 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4388 for (Signature sig : scannedPkg.mSignatures) { 4389 try { 4390 Signature[] chainSignatures = sig.getChainSignatures(); 4391 for (Signature chainSig : chainSignatures) { 4392 scannedCompatSet.add(chainSig); 4393 } 4394 } catch (CertificateEncodingException e) { 4395 scannedCompatSet.add(sig); 4396 } 4397 } 4398 /* 4399 * Make sure the expanded scanned set contains all signatures in the 4400 * existing one. 4401 */ 4402 if (scannedCompatSet.equals(existingSet)) { 4403 // Migrate the old signatures to the new scheme. 4404 existingSigs.assignSignatures(scannedPkg.mSignatures); 4405 // The new KeySets will be re-added later in the scanning process. 4406 synchronized (mPackages) { 4407 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4408 } 4409 return PackageManager.SIGNATURE_MATCH; 4410 } 4411 return PackageManager.SIGNATURE_NO_MATCH; 4412 } 4413 4414 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4415 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4416 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4417 } 4418 4419 private int compareSignaturesRecover(PackageSignatures existingSigs, 4420 PackageParser.Package scannedPkg) { 4421 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4422 return PackageManager.SIGNATURE_NO_MATCH; 4423 } 4424 4425 String msg = null; 4426 try { 4427 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4428 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4429 + scannedPkg.packageName); 4430 return PackageManager.SIGNATURE_MATCH; 4431 } 4432 } catch (CertificateException e) { 4433 msg = e.getMessage(); 4434 } 4435 4436 logCriticalInfo(Log.INFO, 4437 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4438 return PackageManager.SIGNATURE_NO_MATCH; 4439 } 4440 4441 @Override 4442 public String[] getPackagesForUid(int uid) { 4443 uid = UserHandle.getAppId(uid); 4444 // reader 4445 synchronized (mPackages) { 4446 Object obj = mSettings.getUserIdLPr(uid); 4447 if (obj instanceof SharedUserSetting) { 4448 final SharedUserSetting sus = (SharedUserSetting) obj; 4449 final int N = sus.packages.size(); 4450 final String[] res = new String[N]; 4451 final Iterator<PackageSetting> it = sus.packages.iterator(); 4452 int i = 0; 4453 while (it.hasNext()) { 4454 res[i++] = it.next().name; 4455 } 4456 return res; 4457 } else if (obj instanceof PackageSetting) { 4458 final PackageSetting ps = (PackageSetting) obj; 4459 return new String[] { ps.name }; 4460 } 4461 } 4462 return null; 4463 } 4464 4465 @Override 4466 public String getNameForUid(int uid) { 4467 // reader 4468 synchronized (mPackages) { 4469 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4470 if (obj instanceof SharedUserSetting) { 4471 final SharedUserSetting sus = (SharedUserSetting) obj; 4472 return sus.name + ":" + sus.userId; 4473 } else if (obj instanceof PackageSetting) { 4474 final PackageSetting ps = (PackageSetting) obj; 4475 return ps.name; 4476 } 4477 } 4478 return null; 4479 } 4480 4481 @Override 4482 public int getUidForSharedUser(String sharedUserName) { 4483 if(sharedUserName == null) { 4484 return -1; 4485 } 4486 // reader 4487 synchronized (mPackages) { 4488 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4489 if (suid == null) { 4490 return -1; 4491 } 4492 return suid.userId; 4493 } 4494 } 4495 4496 @Override 4497 public int getFlagsForUid(int uid) { 4498 synchronized (mPackages) { 4499 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4500 if (obj instanceof SharedUserSetting) { 4501 final SharedUserSetting sus = (SharedUserSetting) obj; 4502 return sus.pkgFlags; 4503 } else if (obj instanceof PackageSetting) { 4504 final PackageSetting ps = (PackageSetting) obj; 4505 return ps.pkgFlags; 4506 } 4507 } 4508 return 0; 4509 } 4510 4511 @Override 4512 public int getPrivateFlagsForUid(int uid) { 4513 synchronized (mPackages) { 4514 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4515 if (obj instanceof SharedUserSetting) { 4516 final SharedUserSetting sus = (SharedUserSetting) obj; 4517 return sus.pkgPrivateFlags; 4518 } else if (obj instanceof PackageSetting) { 4519 final PackageSetting ps = (PackageSetting) obj; 4520 return ps.pkgPrivateFlags; 4521 } 4522 } 4523 return 0; 4524 } 4525 4526 @Override 4527 public boolean isUidPrivileged(int uid) { 4528 uid = UserHandle.getAppId(uid); 4529 // reader 4530 synchronized (mPackages) { 4531 Object obj = mSettings.getUserIdLPr(uid); 4532 if (obj instanceof SharedUserSetting) { 4533 final SharedUserSetting sus = (SharedUserSetting) obj; 4534 final Iterator<PackageSetting> it = sus.packages.iterator(); 4535 while (it.hasNext()) { 4536 if (it.next().isPrivileged()) { 4537 return true; 4538 } 4539 } 4540 } else if (obj instanceof PackageSetting) { 4541 final PackageSetting ps = (PackageSetting) obj; 4542 return ps.isPrivileged(); 4543 } 4544 } 4545 return false; 4546 } 4547 4548 @Override 4549 public String[] getAppOpPermissionPackages(String permissionName) { 4550 synchronized (mPackages) { 4551 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4552 if (pkgs == null) { 4553 return null; 4554 } 4555 return pkgs.toArray(new String[pkgs.size()]); 4556 } 4557 } 4558 4559 @Override 4560 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4561 int flags, int userId) { 4562 if (!sUserManager.exists(userId)) return null; 4563 flags = updateFlagsForResolve(flags, userId, intent); 4564 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4565 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4566 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4567 final ResolveInfo bestChoice = 4568 chooseBestActivity(intent, resolvedType, flags, query, userId); 4569 4570 if (isEphemeralAllowed(intent, query, userId)) { 4571 final EphemeralResolveInfo ai = 4572 getEphemeralResolveInfo(intent, resolvedType, userId); 4573 if (ai != null) { 4574 if (DEBUG_EPHEMERAL) { 4575 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4576 } 4577 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4578 bestChoice.ephemeralResolveInfo = ai; 4579 } 4580 } 4581 return bestChoice; 4582 } 4583 4584 @Override 4585 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4586 IntentFilter filter, int match, ComponentName activity) { 4587 final int userId = UserHandle.getCallingUserId(); 4588 if (DEBUG_PREFERRED) { 4589 Log.v(TAG, "setLastChosenActivity intent=" + intent 4590 + " resolvedType=" + resolvedType 4591 + " flags=" + flags 4592 + " filter=" + filter 4593 + " match=" + match 4594 + " activity=" + activity); 4595 filter.dump(new PrintStreamPrinter(System.out), " "); 4596 } 4597 intent.setComponent(null); 4598 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4599 // Find any earlier preferred or last chosen entries and nuke them 4600 findPreferredActivity(intent, resolvedType, 4601 flags, query, 0, false, true, false, userId); 4602 // Add the new activity as the last chosen for this filter 4603 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4604 "Setting last chosen"); 4605 } 4606 4607 @Override 4608 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4609 final int userId = UserHandle.getCallingUserId(); 4610 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4611 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4612 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4613 false, false, false, userId); 4614 } 4615 4616 4617 private boolean isEphemeralAllowed( 4618 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4619 // Short circuit and return early if possible. 4620 if (DISABLE_EPHEMERAL_APPS) { 4621 return false; 4622 } 4623 final int callingUser = UserHandle.getCallingUserId(); 4624 if (callingUser != UserHandle.USER_SYSTEM) { 4625 return false; 4626 } 4627 if (mEphemeralResolverConnection == null) { 4628 return false; 4629 } 4630 if (intent.getComponent() != null) { 4631 return false; 4632 } 4633 if (intent.getPackage() != null) { 4634 return false; 4635 } 4636 final boolean isWebUri = hasWebURI(intent); 4637 if (!isWebUri) { 4638 return false; 4639 } 4640 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4641 synchronized (mPackages) { 4642 final int count = resolvedActivites.size(); 4643 for (int n = 0; n < count; n++) { 4644 ResolveInfo info = resolvedActivites.get(n); 4645 String packageName = info.activityInfo.packageName; 4646 PackageSetting ps = mSettings.mPackages.get(packageName); 4647 if (ps != null) { 4648 // Try to get the status from User settings first 4649 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4650 int status = (int) (packedStatus >> 32); 4651 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4652 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4653 if (DEBUG_EPHEMERAL) { 4654 Slog.v(TAG, "DENY ephemeral apps;" 4655 + " pkg: " + packageName + ", status: " + status); 4656 } 4657 return false; 4658 } 4659 } 4660 } 4661 } 4662 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4663 return true; 4664 } 4665 4666 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4667 int userId) { 4668 MessageDigest digest = null; 4669 try { 4670 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4671 } catch (NoSuchAlgorithmException e) { 4672 // If we can't create a digest, ignore ephemeral apps. 4673 return null; 4674 } 4675 4676 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4677 final byte[] digestBytes = digest.digest(hostBytes); 4678 int shaPrefix = 4679 digestBytes[0] << 24 4680 | digestBytes[1] << 16 4681 | digestBytes[2] << 8 4682 | digestBytes[3] << 0; 4683 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4684 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4685 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4686 // No hash prefix match; there are no ephemeral apps for this domain. 4687 return null; 4688 } 4689 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4690 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4691 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4692 continue; 4693 } 4694 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4695 // No filters; this should never happen. 4696 if (filters.isEmpty()) { 4697 continue; 4698 } 4699 // We have a domain match; resolve the filters to see if anything matches. 4700 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4701 for (int j = filters.size() - 1; j >= 0; --j) { 4702 final EphemeralResolveIntentInfo intentInfo = 4703 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4704 ephemeralResolver.addFilter(intentInfo); 4705 } 4706 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4707 intent, resolvedType, false /*defaultOnly*/, userId); 4708 if (!matchedResolveInfoList.isEmpty()) { 4709 return matchedResolveInfoList.get(0); 4710 } 4711 } 4712 // Hash or filter mis-match; no ephemeral apps for this domain. 4713 return null; 4714 } 4715 4716 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4717 int flags, List<ResolveInfo> query, int userId) { 4718 if (query != null) { 4719 final int N = query.size(); 4720 if (N == 1) { 4721 return query.get(0); 4722 } else if (N > 1) { 4723 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4724 // If there is more than one activity with the same priority, 4725 // then let the user decide between them. 4726 ResolveInfo r0 = query.get(0); 4727 ResolveInfo r1 = query.get(1); 4728 if (DEBUG_INTENT_MATCHING || debug) { 4729 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4730 + r1.activityInfo.name + "=" + r1.priority); 4731 } 4732 // If the first activity has a higher priority, or a different 4733 // default, then it is always desirable to pick it. 4734 if (r0.priority != r1.priority 4735 || r0.preferredOrder != r1.preferredOrder 4736 || r0.isDefault != r1.isDefault) { 4737 return query.get(0); 4738 } 4739 // If we have saved a preference for a preferred activity for 4740 // this Intent, use that. 4741 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4742 flags, query, r0.priority, true, false, debug, userId); 4743 if (ri != null) { 4744 return ri; 4745 } 4746 ri = new ResolveInfo(mResolveInfo); 4747 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4748 ri.activityInfo.applicationInfo = new ApplicationInfo( 4749 ri.activityInfo.applicationInfo); 4750 if (userId != 0) { 4751 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4752 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4753 } 4754 // Make sure that the resolver is displayable in car mode 4755 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4756 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4757 return ri; 4758 } 4759 } 4760 return null; 4761 } 4762 4763 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4764 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4765 final int N = query.size(); 4766 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4767 .get(userId); 4768 // Get the list of persistent preferred activities that handle the intent 4769 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4770 List<PersistentPreferredActivity> pprefs = ppir != null 4771 ? ppir.queryIntent(intent, resolvedType, 4772 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4773 : null; 4774 if (pprefs != null && pprefs.size() > 0) { 4775 final int M = pprefs.size(); 4776 for (int i=0; i<M; i++) { 4777 final PersistentPreferredActivity ppa = pprefs.get(i); 4778 if (DEBUG_PREFERRED || debug) { 4779 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4780 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4781 + "\n component=" + ppa.mComponent); 4782 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4783 } 4784 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4785 flags | MATCH_DISABLED_COMPONENTS, userId); 4786 if (DEBUG_PREFERRED || debug) { 4787 Slog.v(TAG, "Found persistent preferred activity:"); 4788 if (ai != null) { 4789 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4790 } else { 4791 Slog.v(TAG, " null"); 4792 } 4793 } 4794 if (ai == null) { 4795 // This previously registered persistent preferred activity 4796 // component is no longer known. Ignore it and do NOT remove it. 4797 continue; 4798 } 4799 for (int j=0; j<N; j++) { 4800 final ResolveInfo ri = query.get(j); 4801 if (!ri.activityInfo.applicationInfo.packageName 4802 .equals(ai.applicationInfo.packageName)) { 4803 continue; 4804 } 4805 if (!ri.activityInfo.name.equals(ai.name)) { 4806 continue; 4807 } 4808 // Found a persistent preference that can handle the intent. 4809 if (DEBUG_PREFERRED || debug) { 4810 Slog.v(TAG, "Returning persistent preferred activity: " + 4811 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4812 } 4813 return ri; 4814 } 4815 } 4816 } 4817 return null; 4818 } 4819 4820 // TODO: handle preferred activities missing while user has amnesia 4821 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4822 List<ResolveInfo> query, int priority, boolean always, 4823 boolean removeMatches, boolean debug, int userId) { 4824 if (!sUserManager.exists(userId)) return null; 4825 flags = updateFlagsForResolve(flags, userId, intent); 4826 // writer 4827 synchronized (mPackages) { 4828 if (intent.getSelector() != null) { 4829 intent = intent.getSelector(); 4830 } 4831 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4832 4833 // Try to find a matching persistent preferred activity. 4834 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4835 debug, userId); 4836 4837 // If a persistent preferred activity matched, use it. 4838 if (pri != null) { 4839 return pri; 4840 } 4841 4842 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4843 // Get the list of preferred activities that handle the intent 4844 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4845 List<PreferredActivity> prefs = pir != null 4846 ? pir.queryIntent(intent, resolvedType, 4847 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4848 : null; 4849 if (prefs != null && prefs.size() > 0) { 4850 boolean changed = false; 4851 try { 4852 // First figure out how good the original match set is. 4853 // We will only allow preferred activities that came 4854 // from the same match quality. 4855 int match = 0; 4856 4857 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4858 4859 final int N = query.size(); 4860 for (int j=0; j<N; j++) { 4861 final ResolveInfo ri = query.get(j); 4862 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4863 + ": 0x" + Integer.toHexString(match)); 4864 if (ri.match > match) { 4865 match = ri.match; 4866 } 4867 } 4868 4869 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4870 + Integer.toHexString(match)); 4871 4872 match &= IntentFilter.MATCH_CATEGORY_MASK; 4873 final int M = prefs.size(); 4874 for (int i=0; i<M; i++) { 4875 final PreferredActivity pa = prefs.get(i); 4876 if (DEBUG_PREFERRED || debug) { 4877 Slog.v(TAG, "Checking PreferredActivity ds=" 4878 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4879 + "\n component=" + pa.mPref.mComponent); 4880 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4881 } 4882 if (pa.mPref.mMatch != match) { 4883 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4884 + Integer.toHexString(pa.mPref.mMatch)); 4885 continue; 4886 } 4887 // If it's not an "always" type preferred activity and that's what we're 4888 // looking for, skip it. 4889 if (always && !pa.mPref.mAlways) { 4890 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4891 continue; 4892 } 4893 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4894 flags | MATCH_DISABLED_COMPONENTS, userId); 4895 if (DEBUG_PREFERRED || debug) { 4896 Slog.v(TAG, "Found preferred activity:"); 4897 if (ai != null) { 4898 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4899 } else { 4900 Slog.v(TAG, " null"); 4901 } 4902 } 4903 if (ai == null) { 4904 // This previously registered preferred activity 4905 // component is no longer known. Most likely an update 4906 // to the app was installed and in the new version this 4907 // component no longer exists. Clean it up by removing 4908 // it from the preferred activities list, and skip it. 4909 Slog.w(TAG, "Removing dangling preferred activity: " 4910 + pa.mPref.mComponent); 4911 pir.removeFilter(pa); 4912 changed = true; 4913 continue; 4914 } 4915 for (int j=0; j<N; j++) { 4916 final ResolveInfo ri = query.get(j); 4917 if (!ri.activityInfo.applicationInfo.packageName 4918 .equals(ai.applicationInfo.packageName)) { 4919 continue; 4920 } 4921 if (!ri.activityInfo.name.equals(ai.name)) { 4922 continue; 4923 } 4924 4925 if (removeMatches) { 4926 pir.removeFilter(pa); 4927 changed = true; 4928 if (DEBUG_PREFERRED) { 4929 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4930 } 4931 break; 4932 } 4933 4934 // Okay we found a previously set preferred or last chosen app. 4935 // If the result set is different from when this 4936 // was created, we need to clear it and re-ask the 4937 // user their preference, if we're looking for an "always" type entry. 4938 if (always && !pa.mPref.sameSet(query)) { 4939 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4940 + intent + " type " + resolvedType); 4941 if (DEBUG_PREFERRED) { 4942 Slog.v(TAG, "Removing preferred activity since set changed " 4943 + pa.mPref.mComponent); 4944 } 4945 pir.removeFilter(pa); 4946 // Re-add the filter as a "last chosen" entry (!always) 4947 PreferredActivity lastChosen = new PreferredActivity( 4948 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4949 pir.addFilter(lastChosen); 4950 changed = true; 4951 return null; 4952 } 4953 4954 // Yay! Either the set matched or we're looking for the last chosen 4955 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4956 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4957 return ri; 4958 } 4959 } 4960 } finally { 4961 if (changed) { 4962 if (DEBUG_PREFERRED) { 4963 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4964 } 4965 scheduleWritePackageRestrictionsLocked(userId); 4966 } 4967 } 4968 } 4969 } 4970 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4971 return null; 4972 } 4973 4974 /* 4975 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4976 */ 4977 @Override 4978 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4979 int targetUserId) { 4980 mContext.enforceCallingOrSelfPermission( 4981 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4982 List<CrossProfileIntentFilter> matches = 4983 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4984 if (matches != null) { 4985 int size = matches.size(); 4986 for (int i = 0; i < size; i++) { 4987 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4988 } 4989 } 4990 if (hasWebURI(intent)) { 4991 // cross-profile app linking works only towards the parent. 4992 final UserInfo parent = getProfileParent(sourceUserId); 4993 synchronized(mPackages) { 4994 int flags = updateFlagsForResolve(0, parent.id, intent); 4995 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4996 intent, resolvedType, flags, sourceUserId, parent.id); 4997 return xpDomainInfo != null; 4998 } 4999 } 5000 return false; 5001 } 5002 5003 private UserInfo getProfileParent(int userId) { 5004 final long identity = Binder.clearCallingIdentity(); 5005 try { 5006 return sUserManager.getProfileParent(userId); 5007 } finally { 5008 Binder.restoreCallingIdentity(identity); 5009 } 5010 } 5011 5012 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5013 String resolvedType, int userId) { 5014 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5015 if (resolver != null) { 5016 return resolver.queryIntent(intent, resolvedType, false, userId); 5017 } 5018 return null; 5019 } 5020 5021 @Override 5022 public List<ResolveInfo> queryIntentActivities(Intent intent, 5023 String resolvedType, int flags, int userId) { 5024 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5025 flags = updateFlagsForResolve(flags, userId, intent); 5026 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5027 false /* requireFullPermission */, false /* checkShell */, 5028 "query intent activities"); 5029 ComponentName comp = intent.getComponent(); 5030 if (comp == null) { 5031 if (intent.getSelector() != null) { 5032 intent = intent.getSelector(); 5033 comp = intent.getComponent(); 5034 } 5035 } 5036 5037 if (comp != null) { 5038 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5039 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5040 if (ai != null) { 5041 final ResolveInfo ri = new ResolveInfo(); 5042 ri.activityInfo = ai; 5043 list.add(ri); 5044 } 5045 return list; 5046 } 5047 5048 // reader 5049 synchronized (mPackages) { 5050 final String pkgName = intent.getPackage(); 5051 if (pkgName == null) { 5052 List<CrossProfileIntentFilter> matchingFilters = 5053 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5054 // Check for results that need to skip the current profile. 5055 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5056 resolvedType, flags, userId); 5057 if (xpResolveInfo != null) { 5058 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5059 result.add(xpResolveInfo); 5060 return filterIfNotSystemUser(result, userId); 5061 } 5062 5063 // Check for results in the current profile. 5064 List<ResolveInfo> result = mActivities.queryIntent( 5065 intent, resolvedType, flags, userId); 5066 result = filterIfNotSystemUser(result, userId); 5067 5068 // Check for cross profile results. 5069 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5070 xpResolveInfo = queryCrossProfileIntents( 5071 matchingFilters, intent, resolvedType, flags, userId, 5072 hasNonNegativePriorityResult); 5073 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5074 boolean isVisibleToUser = filterIfNotSystemUser( 5075 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5076 if (isVisibleToUser) { 5077 result.add(xpResolveInfo); 5078 Collections.sort(result, mResolvePrioritySorter); 5079 } 5080 } 5081 if (hasWebURI(intent)) { 5082 CrossProfileDomainInfo xpDomainInfo = null; 5083 final UserInfo parent = getProfileParent(userId); 5084 if (parent != null) { 5085 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5086 flags, userId, parent.id); 5087 } 5088 if (xpDomainInfo != null) { 5089 if (xpResolveInfo != null) { 5090 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5091 // in the result. 5092 result.remove(xpResolveInfo); 5093 } 5094 if (result.size() == 0) { 5095 result.add(xpDomainInfo.resolveInfo); 5096 return result; 5097 } 5098 } else if (result.size() <= 1) { 5099 return result; 5100 } 5101 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5102 xpDomainInfo, userId); 5103 Collections.sort(result, mResolvePrioritySorter); 5104 } 5105 return result; 5106 } 5107 final PackageParser.Package pkg = mPackages.get(pkgName); 5108 if (pkg != null) { 5109 return filterIfNotSystemUser( 5110 mActivities.queryIntentForPackage( 5111 intent, resolvedType, flags, pkg.activities, userId), 5112 userId); 5113 } 5114 return new ArrayList<ResolveInfo>(); 5115 } 5116 } 5117 5118 private static class CrossProfileDomainInfo { 5119 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5120 ResolveInfo resolveInfo; 5121 /* Best domain verification status of the activities found in the other profile */ 5122 int bestDomainVerificationStatus; 5123 } 5124 5125 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5126 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5127 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5128 sourceUserId)) { 5129 return null; 5130 } 5131 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5132 resolvedType, flags, parentUserId); 5133 5134 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5135 return null; 5136 } 5137 CrossProfileDomainInfo result = null; 5138 int size = resultTargetUser.size(); 5139 for (int i = 0; i < size; i++) { 5140 ResolveInfo riTargetUser = resultTargetUser.get(i); 5141 // Intent filter verification is only for filters that specify a host. So don't return 5142 // those that handle all web uris. 5143 if (riTargetUser.handleAllWebDataURI) { 5144 continue; 5145 } 5146 String packageName = riTargetUser.activityInfo.packageName; 5147 PackageSetting ps = mSettings.mPackages.get(packageName); 5148 if (ps == null) { 5149 continue; 5150 } 5151 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5152 int status = (int)(verificationState >> 32); 5153 if (result == null) { 5154 result = new CrossProfileDomainInfo(); 5155 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5156 sourceUserId, parentUserId); 5157 result.bestDomainVerificationStatus = status; 5158 } else { 5159 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5160 result.bestDomainVerificationStatus); 5161 } 5162 } 5163 // Don't consider matches with status NEVER across profiles. 5164 if (result != null && result.bestDomainVerificationStatus 5165 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5166 return null; 5167 } 5168 return result; 5169 } 5170 5171 /** 5172 * Verification statuses are ordered from the worse to the best, except for 5173 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5174 */ 5175 private int bestDomainVerificationStatus(int status1, int status2) { 5176 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5177 return status2; 5178 } 5179 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5180 return status1; 5181 } 5182 return (int) MathUtils.max(status1, status2); 5183 } 5184 5185 private boolean isUserEnabled(int userId) { 5186 long callingId = Binder.clearCallingIdentity(); 5187 try { 5188 UserInfo userInfo = sUserManager.getUserInfo(userId); 5189 return userInfo != null && userInfo.isEnabled(); 5190 } finally { 5191 Binder.restoreCallingIdentity(callingId); 5192 } 5193 } 5194 5195 /** 5196 * Filter out activities with systemUserOnly flag set, when current user is not System. 5197 * 5198 * @return filtered list 5199 */ 5200 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5201 if (userId == UserHandle.USER_SYSTEM) { 5202 return resolveInfos; 5203 } 5204 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5205 ResolveInfo info = resolveInfos.get(i); 5206 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5207 resolveInfos.remove(i); 5208 } 5209 } 5210 return resolveInfos; 5211 } 5212 5213 /** 5214 * @param resolveInfos list of resolve infos in descending priority order 5215 * @return if the list contains a resolve info with non-negative priority 5216 */ 5217 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5218 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5219 } 5220 5221 private static boolean hasWebURI(Intent intent) { 5222 if (intent.getData() == null) { 5223 return false; 5224 } 5225 final String scheme = intent.getScheme(); 5226 if (TextUtils.isEmpty(scheme)) { 5227 return false; 5228 } 5229 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5230 } 5231 5232 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5233 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5234 int userId) { 5235 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5236 5237 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5238 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5239 candidates.size()); 5240 } 5241 5242 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5243 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5244 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5245 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5246 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5247 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5248 5249 synchronized (mPackages) { 5250 final int count = candidates.size(); 5251 // First, try to use linked apps. Partition the candidates into four lists: 5252 // one for the final results, one for the "do not use ever", one for "undefined status" 5253 // and finally one for "browser app type". 5254 for (int n=0; n<count; n++) { 5255 ResolveInfo info = candidates.get(n); 5256 String packageName = info.activityInfo.packageName; 5257 PackageSetting ps = mSettings.mPackages.get(packageName); 5258 if (ps != null) { 5259 // Add to the special match all list (Browser use case) 5260 if (info.handleAllWebDataURI) { 5261 matchAllList.add(info); 5262 continue; 5263 } 5264 // Try to get the status from User settings first 5265 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5266 int status = (int)(packedStatus >> 32); 5267 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5268 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5269 if (DEBUG_DOMAIN_VERIFICATION) { 5270 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5271 + " : linkgen=" + linkGeneration); 5272 } 5273 // Use link-enabled generation as preferredOrder, i.e. 5274 // prefer newly-enabled over earlier-enabled. 5275 info.preferredOrder = linkGeneration; 5276 alwaysList.add(info); 5277 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5278 if (DEBUG_DOMAIN_VERIFICATION) { 5279 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5280 } 5281 neverList.add(info); 5282 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5283 if (DEBUG_DOMAIN_VERIFICATION) { 5284 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5285 } 5286 alwaysAskList.add(info); 5287 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5288 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5289 if (DEBUG_DOMAIN_VERIFICATION) { 5290 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5291 } 5292 undefinedList.add(info); 5293 } 5294 } 5295 } 5296 5297 // We'll want to include browser possibilities in a few cases 5298 boolean includeBrowser = false; 5299 5300 // First try to add the "always" resolution(s) for the current user, if any 5301 if (alwaysList.size() > 0) { 5302 result.addAll(alwaysList); 5303 } else { 5304 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5305 result.addAll(undefinedList); 5306 // Maybe add one for the other profile. 5307 if (xpDomainInfo != null && ( 5308 xpDomainInfo.bestDomainVerificationStatus 5309 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5310 result.add(xpDomainInfo.resolveInfo); 5311 } 5312 includeBrowser = true; 5313 } 5314 5315 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5316 // If there were 'always' entries their preferred order has been set, so we also 5317 // back that off to make the alternatives equivalent 5318 if (alwaysAskList.size() > 0) { 5319 for (ResolveInfo i : result) { 5320 i.preferredOrder = 0; 5321 } 5322 result.addAll(alwaysAskList); 5323 includeBrowser = true; 5324 } 5325 5326 if (includeBrowser) { 5327 // Also add browsers (all of them or only the default one) 5328 if (DEBUG_DOMAIN_VERIFICATION) { 5329 Slog.v(TAG, " ...including browsers in candidate set"); 5330 } 5331 if ((matchFlags & MATCH_ALL) != 0) { 5332 result.addAll(matchAllList); 5333 } else { 5334 // Browser/generic handling case. If there's a default browser, go straight 5335 // to that (but only if there is no other higher-priority match). 5336 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5337 int maxMatchPrio = 0; 5338 ResolveInfo defaultBrowserMatch = null; 5339 final int numCandidates = matchAllList.size(); 5340 for (int n = 0; n < numCandidates; n++) { 5341 ResolveInfo info = matchAllList.get(n); 5342 // track the highest overall match priority... 5343 if (info.priority > maxMatchPrio) { 5344 maxMatchPrio = info.priority; 5345 } 5346 // ...and the highest-priority default browser match 5347 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5348 if (defaultBrowserMatch == null 5349 || (defaultBrowserMatch.priority < info.priority)) { 5350 if (debug) { 5351 Slog.v(TAG, "Considering default browser match " + info); 5352 } 5353 defaultBrowserMatch = info; 5354 } 5355 } 5356 } 5357 if (defaultBrowserMatch != null 5358 && defaultBrowserMatch.priority >= maxMatchPrio 5359 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5360 { 5361 if (debug) { 5362 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5363 } 5364 result.add(defaultBrowserMatch); 5365 } else { 5366 result.addAll(matchAllList); 5367 } 5368 } 5369 5370 // If there is nothing selected, add all candidates and remove the ones that the user 5371 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5372 if (result.size() == 0) { 5373 result.addAll(candidates); 5374 result.removeAll(neverList); 5375 } 5376 } 5377 } 5378 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5379 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5380 result.size()); 5381 for (ResolveInfo info : result) { 5382 Slog.v(TAG, " + " + info.activityInfo); 5383 } 5384 } 5385 return result; 5386 } 5387 5388 // Returns a packed value as a long: 5389 // 5390 // high 'int'-sized word: link status: undefined/ask/never/always. 5391 // low 'int'-sized word: relative priority among 'always' results. 5392 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5393 long result = ps.getDomainVerificationStatusForUser(userId); 5394 // if none available, get the master status 5395 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5396 if (ps.getIntentFilterVerificationInfo() != null) { 5397 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5398 } 5399 } 5400 return result; 5401 } 5402 5403 private ResolveInfo querySkipCurrentProfileIntents( 5404 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5405 int flags, int sourceUserId) { 5406 if (matchingFilters != null) { 5407 int size = matchingFilters.size(); 5408 for (int i = 0; i < size; i ++) { 5409 CrossProfileIntentFilter filter = matchingFilters.get(i); 5410 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5411 // Checking if there are activities in the target user that can handle the 5412 // intent. 5413 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5414 resolvedType, flags, sourceUserId); 5415 if (resolveInfo != null) { 5416 return resolveInfo; 5417 } 5418 } 5419 } 5420 } 5421 return null; 5422 } 5423 5424 // Return matching ResolveInfo in target user if any. 5425 private ResolveInfo queryCrossProfileIntents( 5426 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5427 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5428 if (matchingFilters != null) { 5429 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5430 // match the same intent. For performance reasons, it is better not to 5431 // run queryIntent twice for the same userId 5432 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5433 int size = matchingFilters.size(); 5434 for (int i = 0; i < size; i++) { 5435 CrossProfileIntentFilter filter = matchingFilters.get(i); 5436 int targetUserId = filter.getTargetUserId(); 5437 boolean skipCurrentProfile = 5438 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5439 boolean skipCurrentProfileIfNoMatchFound = 5440 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5441 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5442 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5443 // Checking if there are activities in the target user that can handle the 5444 // intent. 5445 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5446 resolvedType, flags, sourceUserId); 5447 if (resolveInfo != null) return resolveInfo; 5448 alreadyTriedUserIds.put(targetUserId, true); 5449 } 5450 } 5451 } 5452 return null; 5453 } 5454 5455 /** 5456 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5457 * will forward the intent to the filter's target user. 5458 * Otherwise, returns null. 5459 */ 5460 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5461 String resolvedType, int flags, int sourceUserId) { 5462 int targetUserId = filter.getTargetUserId(); 5463 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5464 resolvedType, flags, targetUserId); 5465 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5466 // If all the matches in the target profile are suspended, return null. 5467 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5468 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5469 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5470 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5471 targetUserId); 5472 } 5473 } 5474 } 5475 return null; 5476 } 5477 5478 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5479 int sourceUserId, int targetUserId) { 5480 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5481 long ident = Binder.clearCallingIdentity(); 5482 boolean targetIsProfile; 5483 try { 5484 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5485 } finally { 5486 Binder.restoreCallingIdentity(ident); 5487 } 5488 String className; 5489 if (targetIsProfile) { 5490 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5491 } else { 5492 className = FORWARD_INTENT_TO_PARENT; 5493 } 5494 ComponentName forwardingActivityComponentName = new ComponentName( 5495 mAndroidApplication.packageName, className); 5496 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5497 sourceUserId); 5498 if (!targetIsProfile) { 5499 forwardingActivityInfo.showUserIcon = targetUserId; 5500 forwardingResolveInfo.noResourceId = true; 5501 } 5502 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5503 forwardingResolveInfo.priority = 0; 5504 forwardingResolveInfo.preferredOrder = 0; 5505 forwardingResolveInfo.match = 0; 5506 forwardingResolveInfo.isDefault = true; 5507 forwardingResolveInfo.filter = filter; 5508 forwardingResolveInfo.targetUserId = targetUserId; 5509 return forwardingResolveInfo; 5510 } 5511 5512 @Override 5513 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5514 Intent[] specifics, String[] specificTypes, Intent intent, 5515 String resolvedType, int flags, int userId) { 5516 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5517 flags = updateFlagsForResolve(flags, userId, intent); 5518 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5519 false /* requireFullPermission */, false /* checkShell */, 5520 "query intent activity options"); 5521 final String resultsAction = intent.getAction(); 5522 5523 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5524 | PackageManager.GET_RESOLVED_FILTER, userId); 5525 5526 if (DEBUG_INTENT_MATCHING) { 5527 Log.v(TAG, "Query " + intent + ": " + results); 5528 } 5529 5530 int specificsPos = 0; 5531 int N; 5532 5533 // todo: note that the algorithm used here is O(N^2). This 5534 // isn't a problem in our current environment, but if we start running 5535 // into situations where we have more than 5 or 10 matches then this 5536 // should probably be changed to something smarter... 5537 5538 // First we go through and resolve each of the specific items 5539 // that were supplied, taking care of removing any corresponding 5540 // duplicate items in the generic resolve list. 5541 if (specifics != null) { 5542 for (int i=0; i<specifics.length; i++) { 5543 final Intent sintent = specifics[i]; 5544 if (sintent == null) { 5545 continue; 5546 } 5547 5548 if (DEBUG_INTENT_MATCHING) { 5549 Log.v(TAG, "Specific #" + i + ": " + sintent); 5550 } 5551 5552 String action = sintent.getAction(); 5553 if (resultsAction != null && resultsAction.equals(action)) { 5554 // If this action was explicitly requested, then don't 5555 // remove things that have it. 5556 action = null; 5557 } 5558 5559 ResolveInfo ri = null; 5560 ActivityInfo ai = null; 5561 5562 ComponentName comp = sintent.getComponent(); 5563 if (comp == null) { 5564 ri = resolveIntent( 5565 sintent, 5566 specificTypes != null ? specificTypes[i] : null, 5567 flags, userId); 5568 if (ri == null) { 5569 continue; 5570 } 5571 if (ri == mResolveInfo) { 5572 // ACK! Must do something better with this. 5573 } 5574 ai = ri.activityInfo; 5575 comp = new ComponentName(ai.applicationInfo.packageName, 5576 ai.name); 5577 } else { 5578 ai = getActivityInfo(comp, flags, userId); 5579 if (ai == null) { 5580 continue; 5581 } 5582 } 5583 5584 // Look for any generic query activities that are duplicates 5585 // of this specific one, and remove them from the results. 5586 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5587 N = results.size(); 5588 int j; 5589 for (j=specificsPos; j<N; j++) { 5590 ResolveInfo sri = results.get(j); 5591 if ((sri.activityInfo.name.equals(comp.getClassName()) 5592 && sri.activityInfo.applicationInfo.packageName.equals( 5593 comp.getPackageName())) 5594 || (action != null && sri.filter.matchAction(action))) { 5595 results.remove(j); 5596 if (DEBUG_INTENT_MATCHING) Log.v( 5597 TAG, "Removing duplicate item from " + j 5598 + " due to specific " + specificsPos); 5599 if (ri == null) { 5600 ri = sri; 5601 } 5602 j--; 5603 N--; 5604 } 5605 } 5606 5607 // Add this specific item to its proper place. 5608 if (ri == null) { 5609 ri = new ResolveInfo(); 5610 ri.activityInfo = ai; 5611 } 5612 results.add(specificsPos, ri); 5613 ri.specificIndex = i; 5614 specificsPos++; 5615 } 5616 } 5617 5618 // Now we go through the remaining generic results and remove any 5619 // duplicate actions that are found here. 5620 N = results.size(); 5621 for (int i=specificsPos; i<N-1; i++) { 5622 final ResolveInfo rii = results.get(i); 5623 if (rii.filter == null) { 5624 continue; 5625 } 5626 5627 // Iterate over all of the actions of this result's intent 5628 // filter... typically this should be just one. 5629 final Iterator<String> it = rii.filter.actionsIterator(); 5630 if (it == null) { 5631 continue; 5632 } 5633 while (it.hasNext()) { 5634 final String action = it.next(); 5635 if (resultsAction != null && resultsAction.equals(action)) { 5636 // If this action was explicitly requested, then don't 5637 // remove things that have it. 5638 continue; 5639 } 5640 for (int j=i+1; j<N; j++) { 5641 final ResolveInfo rij = results.get(j); 5642 if (rij.filter != null && rij.filter.hasAction(action)) { 5643 results.remove(j); 5644 if (DEBUG_INTENT_MATCHING) Log.v( 5645 TAG, "Removing duplicate item from " + j 5646 + " due to action " + action + " at " + i); 5647 j--; 5648 N--; 5649 } 5650 } 5651 } 5652 5653 // If the caller didn't request filter information, drop it now 5654 // so we don't have to marshall/unmarshall it. 5655 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5656 rii.filter = null; 5657 } 5658 } 5659 5660 // Filter out the caller activity if so requested. 5661 if (caller != null) { 5662 N = results.size(); 5663 for (int i=0; i<N; i++) { 5664 ActivityInfo ainfo = results.get(i).activityInfo; 5665 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5666 && caller.getClassName().equals(ainfo.name)) { 5667 results.remove(i); 5668 break; 5669 } 5670 } 5671 } 5672 5673 // If the caller didn't request filter information, 5674 // drop them now so we don't have to 5675 // marshall/unmarshall it. 5676 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5677 N = results.size(); 5678 for (int i=0; i<N; i++) { 5679 results.get(i).filter = null; 5680 } 5681 } 5682 5683 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5684 return results; 5685 } 5686 5687 @Override 5688 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5689 int userId) { 5690 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5691 flags = updateFlagsForResolve(flags, userId, intent); 5692 ComponentName comp = intent.getComponent(); 5693 if (comp == null) { 5694 if (intent.getSelector() != null) { 5695 intent = intent.getSelector(); 5696 comp = intent.getComponent(); 5697 } 5698 } 5699 if (comp != null) { 5700 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5701 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5702 if (ai != null) { 5703 ResolveInfo ri = new ResolveInfo(); 5704 ri.activityInfo = ai; 5705 list.add(ri); 5706 } 5707 return list; 5708 } 5709 5710 // reader 5711 synchronized (mPackages) { 5712 String pkgName = intent.getPackage(); 5713 if (pkgName == null) { 5714 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5715 } 5716 final PackageParser.Package pkg = mPackages.get(pkgName); 5717 if (pkg != null) { 5718 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5719 userId); 5720 } 5721 return null; 5722 } 5723 } 5724 5725 @Override 5726 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5727 if (!sUserManager.exists(userId)) return null; 5728 flags = updateFlagsForResolve(flags, userId, intent); 5729 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5730 if (query != null) { 5731 if (query.size() >= 1) { 5732 // If there is more than one service with the same priority, 5733 // just arbitrarily pick the first one. 5734 return query.get(0); 5735 } 5736 } 5737 return null; 5738 } 5739 5740 @Override 5741 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5742 int userId) { 5743 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5744 flags = updateFlagsForResolve(flags, userId, intent); 5745 ComponentName comp = intent.getComponent(); 5746 if (comp == null) { 5747 if (intent.getSelector() != null) { 5748 intent = intent.getSelector(); 5749 comp = intent.getComponent(); 5750 } 5751 } 5752 if (comp != null) { 5753 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5754 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5755 if (si != null) { 5756 final ResolveInfo ri = new ResolveInfo(); 5757 ri.serviceInfo = si; 5758 list.add(ri); 5759 } 5760 return list; 5761 } 5762 5763 // reader 5764 synchronized (mPackages) { 5765 String pkgName = intent.getPackage(); 5766 if (pkgName == null) { 5767 return mServices.queryIntent(intent, resolvedType, flags, userId); 5768 } 5769 final PackageParser.Package pkg = mPackages.get(pkgName); 5770 if (pkg != null) { 5771 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5772 userId); 5773 } 5774 return null; 5775 } 5776 } 5777 5778 @Override 5779 public List<ResolveInfo> queryIntentContentProviders( 5780 Intent intent, String resolvedType, int flags, int userId) { 5781 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5782 flags = updateFlagsForResolve(flags, userId, intent); 5783 ComponentName comp = intent.getComponent(); 5784 if (comp == null) { 5785 if (intent.getSelector() != null) { 5786 intent = intent.getSelector(); 5787 comp = intent.getComponent(); 5788 } 5789 } 5790 if (comp != null) { 5791 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5792 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5793 if (pi != null) { 5794 final ResolveInfo ri = new ResolveInfo(); 5795 ri.providerInfo = pi; 5796 list.add(ri); 5797 } 5798 return list; 5799 } 5800 5801 // reader 5802 synchronized (mPackages) { 5803 String pkgName = intent.getPackage(); 5804 if (pkgName == null) { 5805 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5806 } 5807 final PackageParser.Package pkg = mPackages.get(pkgName); 5808 if (pkg != null) { 5809 return mProviders.queryIntentForPackage( 5810 intent, resolvedType, flags, pkg.providers, userId); 5811 } 5812 return null; 5813 } 5814 } 5815 5816 @Override 5817 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5818 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5819 flags = updateFlagsForPackage(flags, userId, null); 5820 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5821 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5822 true /* requireFullPermission */, false /* checkShell */, 5823 "get installed packages"); 5824 5825 // writer 5826 synchronized (mPackages) { 5827 ArrayList<PackageInfo> list; 5828 if (listUninstalled) { 5829 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5830 for (PackageSetting ps : mSettings.mPackages.values()) { 5831 PackageInfo pi; 5832 if (ps.pkg != null) { 5833 pi = generatePackageInfo(ps.pkg, flags, userId); 5834 } else { 5835 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5836 } 5837 if (pi != null) { 5838 list.add(pi); 5839 } 5840 } 5841 } else { 5842 list = new ArrayList<PackageInfo>(mPackages.size()); 5843 for (PackageParser.Package p : mPackages.values()) { 5844 PackageInfo pi = generatePackageInfo(p, flags, userId); 5845 if (pi != null) { 5846 list.add(pi); 5847 } 5848 } 5849 } 5850 5851 return new ParceledListSlice<PackageInfo>(list); 5852 } 5853 } 5854 5855 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5856 String[] permissions, boolean[] tmp, int flags, int userId) { 5857 int numMatch = 0; 5858 final PermissionsState permissionsState = ps.getPermissionsState(); 5859 for (int i=0; i<permissions.length; i++) { 5860 final String permission = permissions[i]; 5861 if (permissionsState.hasPermission(permission, userId)) { 5862 tmp[i] = true; 5863 numMatch++; 5864 } else { 5865 tmp[i] = false; 5866 } 5867 } 5868 if (numMatch == 0) { 5869 return; 5870 } 5871 PackageInfo pi; 5872 if (ps.pkg != null) { 5873 pi = generatePackageInfo(ps.pkg, flags, userId); 5874 } else { 5875 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5876 } 5877 // The above might return null in cases of uninstalled apps or install-state 5878 // skew across users/profiles. 5879 if (pi != null) { 5880 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5881 if (numMatch == permissions.length) { 5882 pi.requestedPermissions = permissions; 5883 } else { 5884 pi.requestedPermissions = new String[numMatch]; 5885 numMatch = 0; 5886 for (int i=0; i<permissions.length; i++) { 5887 if (tmp[i]) { 5888 pi.requestedPermissions[numMatch] = permissions[i]; 5889 numMatch++; 5890 } 5891 } 5892 } 5893 } 5894 list.add(pi); 5895 } 5896 } 5897 5898 @Override 5899 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5900 String[] permissions, int flags, int userId) { 5901 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5902 flags = updateFlagsForPackage(flags, userId, permissions); 5903 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5904 5905 // writer 5906 synchronized (mPackages) { 5907 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5908 boolean[] tmpBools = new boolean[permissions.length]; 5909 if (listUninstalled) { 5910 for (PackageSetting ps : mSettings.mPackages.values()) { 5911 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5912 } 5913 } else { 5914 for (PackageParser.Package pkg : mPackages.values()) { 5915 PackageSetting ps = (PackageSetting)pkg.mExtras; 5916 if (ps != null) { 5917 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5918 userId); 5919 } 5920 } 5921 } 5922 5923 return new ParceledListSlice<PackageInfo>(list); 5924 } 5925 } 5926 5927 @Override 5928 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5929 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5930 flags = updateFlagsForApplication(flags, userId, null); 5931 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5932 5933 // writer 5934 synchronized (mPackages) { 5935 ArrayList<ApplicationInfo> list; 5936 if (listUninstalled) { 5937 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5938 for (PackageSetting ps : mSettings.mPackages.values()) { 5939 ApplicationInfo ai; 5940 if (ps.pkg != null) { 5941 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5942 ps.readUserState(userId), userId); 5943 } else { 5944 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5945 } 5946 if (ai != null) { 5947 list.add(ai); 5948 } 5949 } 5950 } else { 5951 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5952 for (PackageParser.Package p : mPackages.values()) { 5953 if (p.mExtras != null) { 5954 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5955 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5956 if (ai != null) { 5957 list.add(ai); 5958 } 5959 } 5960 } 5961 } 5962 5963 return new ParceledListSlice<ApplicationInfo>(list); 5964 } 5965 } 5966 5967 @Override 5968 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5969 if (DISABLE_EPHEMERAL_APPS) { 5970 return null; 5971 } 5972 5973 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5974 "getEphemeralApplications"); 5975 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5976 true /* requireFullPermission */, false /* checkShell */, 5977 "getEphemeralApplications"); 5978 synchronized (mPackages) { 5979 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5980 .getEphemeralApplicationsLPw(userId); 5981 if (ephemeralApps != null) { 5982 return new ParceledListSlice<>(ephemeralApps); 5983 } 5984 } 5985 return null; 5986 } 5987 5988 @Override 5989 public boolean isEphemeralApplication(String packageName, int userId) { 5990 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5991 true /* requireFullPermission */, false /* checkShell */, 5992 "isEphemeral"); 5993 if (DISABLE_EPHEMERAL_APPS) { 5994 return false; 5995 } 5996 5997 if (!isCallerSameApp(packageName)) { 5998 return false; 5999 } 6000 synchronized (mPackages) { 6001 PackageParser.Package pkg = mPackages.get(packageName); 6002 if (pkg != null) { 6003 return pkg.applicationInfo.isEphemeralApp(); 6004 } 6005 } 6006 return false; 6007 } 6008 6009 @Override 6010 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6011 if (DISABLE_EPHEMERAL_APPS) { 6012 return null; 6013 } 6014 6015 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6016 true /* requireFullPermission */, false /* checkShell */, 6017 "getCookie"); 6018 if (!isCallerSameApp(packageName)) { 6019 return null; 6020 } 6021 synchronized (mPackages) { 6022 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6023 packageName, userId); 6024 } 6025 } 6026 6027 @Override 6028 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6029 if (DISABLE_EPHEMERAL_APPS) { 6030 return true; 6031 } 6032 6033 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6034 true /* requireFullPermission */, true /* checkShell */, 6035 "setCookie"); 6036 if (!isCallerSameApp(packageName)) { 6037 return false; 6038 } 6039 synchronized (mPackages) { 6040 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6041 packageName, cookie, userId); 6042 } 6043 } 6044 6045 @Override 6046 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6047 if (DISABLE_EPHEMERAL_APPS) { 6048 return null; 6049 } 6050 6051 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6052 "getEphemeralApplicationIcon"); 6053 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6054 true /* requireFullPermission */, false /* checkShell */, 6055 "getEphemeralApplicationIcon"); 6056 synchronized (mPackages) { 6057 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6058 packageName, userId); 6059 } 6060 } 6061 6062 private boolean isCallerSameApp(String packageName) { 6063 PackageParser.Package pkg = mPackages.get(packageName); 6064 return pkg != null 6065 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6066 } 6067 6068 public List<ApplicationInfo> getPersistentApplications(int flags) { 6069 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6070 6071 // reader 6072 synchronized (mPackages) { 6073 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6074 final int userId = UserHandle.getCallingUserId(); 6075 while (i.hasNext()) { 6076 final PackageParser.Package p = i.next(); 6077 if (p.applicationInfo == null) continue; 6078 6079 final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0) 6080 && !p.applicationInfo.isEncryptionAware(); 6081 final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0) 6082 && p.applicationInfo.isEncryptionAware(); 6083 6084 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6085 && (!mSafeMode || isSystemApp(p)) 6086 && (matchesUnaware || matchesAware)) { 6087 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6088 if (ps != null) { 6089 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6090 ps.readUserState(userId), userId); 6091 if (ai != null) { 6092 finalList.add(ai); 6093 } 6094 } 6095 } 6096 } 6097 } 6098 6099 return finalList; 6100 } 6101 6102 @Override 6103 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6104 if (!sUserManager.exists(userId)) return null; 6105 flags = updateFlagsForComponent(flags, userId, name); 6106 // reader 6107 synchronized (mPackages) { 6108 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6109 PackageSetting ps = provider != null 6110 ? mSettings.mPackages.get(provider.owner.packageName) 6111 : null; 6112 return ps != null 6113 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6114 ? PackageParser.generateProviderInfo(provider, flags, 6115 ps.readUserState(userId), userId) 6116 : null; 6117 } 6118 } 6119 6120 /** 6121 * @deprecated 6122 */ 6123 @Deprecated 6124 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6125 // reader 6126 synchronized (mPackages) { 6127 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6128 .entrySet().iterator(); 6129 final int userId = UserHandle.getCallingUserId(); 6130 while (i.hasNext()) { 6131 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6132 PackageParser.Provider p = entry.getValue(); 6133 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6134 6135 if (ps != null && p.syncable 6136 && (!mSafeMode || (p.info.applicationInfo.flags 6137 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6138 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6139 ps.readUserState(userId), userId); 6140 if (info != null) { 6141 outNames.add(entry.getKey()); 6142 outInfo.add(info); 6143 } 6144 } 6145 } 6146 } 6147 } 6148 6149 @Override 6150 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6151 int uid, int flags) { 6152 final int userId = processName != null ? UserHandle.getUserId(uid) 6153 : UserHandle.getCallingUserId(); 6154 if (!sUserManager.exists(userId)) return null; 6155 flags = updateFlagsForComponent(flags, userId, processName); 6156 6157 ArrayList<ProviderInfo> finalList = null; 6158 // reader 6159 synchronized (mPackages) { 6160 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6161 while (i.hasNext()) { 6162 final PackageParser.Provider p = i.next(); 6163 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6164 if (ps != null && p.info.authority != null 6165 && (processName == null 6166 || (p.info.processName.equals(processName) 6167 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6168 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6169 if (finalList == null) { 6170 finalList = new ArrayList<ProviderInfo>(3); 6171 } 6172 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6173 ps.readUserState(userId), userId); 6174 if (info != null) { 6175 finalList.add(info); 6176 } 6177 } 6178 } 6179 } 6180 6181 if (finalList != null) { 6182 Collections.sort(finalList, mProviderInitOrderSorter); 6183 return new ParceledListSlice<ProviderInfo>(finalList); 6184 } 6185 6186 return null; 6187 } 6188 6189 @Override 6190 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6191 // reader 6192 synchronized (mPackages) { 6193 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6194 return PackageParser.generateInstrumentationInfo(i, flags); 6195 } 6196 } 6197 6198 @Override 6199 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6200 int flags) { 6201 ArrayList<InstrumentationInfo> finalList = 6202 new ArrayList<InstrumentationInfo>(); 6203 6204 // reader 6205 synchronized (mPackages) { 6206 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6207 while (i.hasNext()) { 6208 final PackageParser.Instrumentation p = i.next(); 6209 if (targetPackage == null 6210 || targetPackage.equals(p.info.targetPackage)) { 6211 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6212 flags); 6213 if (ii != null) { 6214 finalList.add(ii); 6215 } 6216 } 6217 } 6218 } 6219 6220 return finalList; 6221 } 6222 6223 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6224 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6225 if (overlays == null) { 6226 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6227 return; 6228 } 6229 for (PackageParser.Package opkg : overlays.values()) { 6230 // Not much to do if idmap fails: we already logged the error 6231 // and we certainly don't want to abort installation of pkg simply 6232 // because an overlay didn't fit properly. For these reasons, 6233 // ignore the return value of createIdmapForPackagePairLI. 6234 createIdmapForPackagePairLI(pkg, opkg); 6235 } 6236 } 6237 6238 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6239 PackageParser.Package opkg) { 6240 if (!opkg.mTrustedOverlay) { 6241 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6242 opkg.baseCodePath + ": overlay not trusted"); 6243 return false; 6244 } 6245 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6246 if (overlaySet == null) { 6247 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6248 opkg.baseCodePath + " but target package has no known overlays"); 6249 return false; 6250 } 6251 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6252 // TODO: generate idmap for split APKs 6253 try { 6254 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6255 } catch (InstallerException e) { 6256 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6257 + opkg.baseCodePath); 6258 return false; 6259 } 6260 PackageParser.Package[] overlayArray = 6261 overlaySet.values().toArray(new PackageParser.Package[0]); 6262 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6263 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6264 return p1.mOverlayPriority - p2.mOverlayPriority; 6265 } 6266 }; 6267 Arrays.sort(overlayArray, cmp); 6268 6269 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6270 int i = 0; 6271 for (PackageParser.Package p : overlayArray) { 6272 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6273 } 6274 return true; 6275 } 6276 6277 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6279 try { 6280 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6281 } finally { 6282 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6283 } 6284 } 6285 6286 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6287 final File[] files = dir.listFiles(); 6288 if (ArrayUtils.isEmpty(files)) { 6289 Log.d(TAG, "No files in app dir " + dir); 6290 return; 6291 } 6292 6293 if (DEBUG_PACKAGE_SCANNING) { 6294 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6295 + " flags=0x" + Integer.toHexString(parseFlags)); 6296 } 6297 6298 for (File file : files) { 6299 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6300 && !PackageInstallerService.isStageName(file.getName()); 6301 if (!isPackage) { 6302 // Ignore entries which are not packages 6303 continue; 6304 } 6305 try { 6306 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6307 scanFlags, currentTime, null); 6308 } catch (PackageManagerException e) { 6309 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6310 6311 // Delete invalid userdata apps 6312 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6313 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6314 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6315 removeCodePathLI(file); 6316 } 6317 } 6318 } 6319 } 6320 6321 private static File getSettingsProblemFile() { 6322 File dataDir = Environment.getDataDirectory(); 6323 File systemDir = new File(dataDir, "system"); 6324 File fname = new File(systemDir, "uiderrors.txt"); 6325 return fname; 6326 } 6327 6328 static void reportSettingsProblem(int priority, String msg) { 6329 logCriticalInfo(priority, msg); 6330 } 6331 6332 static void logCriticalInfo(int priority, String msg) { 6333 Slog.println(priority, TAG, msg); 6334 EventLogTags.writePmCriticalInfo(msg); 6335 try { 6336 File fname = getSettingsProblemFile(); 6337 FileOutputStream out = new FileOutputStream(fname, true); 6338 PrintWriter pw = new FastPrintWriter(out); 6339 SimpleDateFormat formatter = new SimpleDateFormat(); 6340 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6341 pw.println(dateString + ": " + msg); 6342 pw.close(); 6343 FileUtils.setPermissions( 6344 fname.toString(), 6345 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6346 -1, -1); 6347 } catch (java.io.IOException e) { 6348 } 6349 } 6350 6351 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6352 int parseFlags) throws PackageManagerException { 6353 if (ps != null 6354 && ps.codePath.equals(srcFile) 6355 && ps.timeStamp == srcFile.lastModified() 6356 && !isCompatSignatureUpdateNeeded(pkg) 6357 && !isRecoverSignatureUpdateNeeded(pkg)) { 6358 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6359 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6360 ArraySet<PublicKey> signingKs; 6361 synchronized (mPackages) { 6362 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6363 } 6364 if (ps.signatures.mSignatures != null 6365 && ps.signatures.mSignatures.length != 0 6366 && signingKs != null) { 6367 // Optimization: reuse the existing cached certificates 6368 // if the package appears to be unchanged. 6369 pkg.mSignatures = ps.signatures.mSignatures; 6370 pkg.mSigningKeys = signingKs; 6371 return; 6372 } 6373 6374 Slog.w(TAG, "PackageSetting for " + ps.name 6375 + " is missing signatures. Collecting certs again to recover them."); 6376 } else { 6377 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6378 } 6379 6380 try { 6381 PackageParser.collectCertificates(pkg, parseFlags); 6382 } catch (PackageParserException e) { 6383 throw PackageManagerException.from(e); 6384 } 6385 } 6386 6387 /** 6388 * Traces a package scan. 6389 * @see #scanPackageLI(File, int, int, long, UserHandle) 6390 */ 6391 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6392 long currentTime, UserHandle user) throws PackageManagerException { 6393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6394 try { 6395 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6396 } finally { 6397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6398 } 6399 } 6400 6401 /** 6402 * Scans a package and returns the newly parsed package. 6403 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6404 */ 6405 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6406 long currentTime, UserHandle user) throws PackageManagerException { 6407 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6408 parseFlags |= mDefParseFlags; 6409 PackageParser pp = new PackageParser(); 6410 pp.setSeparateProcesses(mSeparateProcesses); 6411 pp.setOnlyCoreApps(mOnlyCore); 6412 pp.setDisplayMetrics(mMetrics); 6413 6414 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6415 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6416 } 6417 6418 final PackageParser.Package pkg; 6419 try { 6420 pkg = pp.parsePackage(scanFile, parseFlags); 6421 } catch (PackageParserException e) { 6422 throw PackageManagerException.from(e); 6423 } 6424 6425 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6426 } 6427 6428 /** 6429 * Scans a package and returns the newly parsed package. 6430 * @throws PackageManagerException on a parse error. 6431 */ 6432 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6433 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6434 throws PackageManagerException { 6435 // If the package has children and this is the first dive in the function 6436 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6437 // packages (parent and children) would be successfully scanned before the 6438 // actual scan since scanning mutates internal state and we want to atomically 6439 // install the package and its children. 6440 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6441 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6442 scanFlags |= SCAN_CHECK_ONLY; 6443 } 6444 } else { 6445 scanFlags &= ~SCAN_CHECK_ONLY; 6446 } 6447 6448 // Scan the parent 6449 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6450 scanFlags, currentTime, user); 6451 6452 // Scan the children 6453 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6454 for (int i = 0; i < childCount; i++) { 6455 PackageParser.Package childPackage = pkg.childPackages.get(i); 6456 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6457 currentTime, user); 6458 } 6459 6460 6461 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6462 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6463 } 6464 6465 return scannedPkg; 6466 } 6467 6468 /** 6469 * Scans a package and returns the newly parsed package. 6470 * @throws PackageManagerException on a parse error. 6471 */ 6472 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6473 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6474 throws PackageManagerException { 6475 PackageSetting ps = null; 6476 PackageSetting updatedPkg; 6477 // reader 6478 synchronized (mPackages) { 6479 // Look to see if we already know about this package. 6480 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6481 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6482 // This package has been renamed to its original name. Let's 6483 // use that. 6484 ps = mSettings.peekPackageLPr(oldName); 6485 } 6486 // If there was no original package, see one for the real package name. 6487 if (ps == null) { 6488 ps = mSettings.peekPackageLPr(pkg.packageName); 6489 } 6490 // Check to see if this package could be hiding/updating a system 6491 // package. Must look for it either under the original or real 6492 // package name depending on our state. 6493 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6494 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6495 6496 // If this is a package we don't know about on the system partition, we 6497 // may need to remove disabled child packages on the system partition 6498 // or may need to not add child packages if the parent apk is updated 6499 // on the data partition and no longer defines this child package. 6500 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6501 // If this is a parent package for an updated system app and this system 6502 // app got an OTA update which no longer defines some of the child packages 6503 // we have to prune them from the disabled system packages. 6504 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6505 if (disabledPs != null) { 6506 final int scannedChildCount = (pkg.childPackages != null) 6507 ? pkg.childPackages.size() : 0; 6508 final int disabledChildCount = disabledPs.childPackageNames != null 6509 ? disabledPs.childPackageNames.size() : 0; 6510 for (int i = 0; i < disabledChildCount; i++) { 6511 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6512 boolean disabledPackageAvailable = false; 6513 for (int j = 0; j < scannedChildCount; j++) { 6514 PackageParser.Package childPkg = pkg.childPackages.get(j); 6515 if (childPkg.packageName.equals(disabledChildPackageName)) { 6516 disabledPackageAvailable = true; 6517 break; 6518 } 6519 } 6520 if (!disabledPackageAvailable) { 6521 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6522 } 6523 } 6524 } 6525 } 6526 } 6527 6528 boolean updatedPkgBetter = false; 6529 // First check if this is a system package that may involve an update 6530 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6531 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6532 // it needs to drop FLAG_PRIVILEGED. 6533 if (locationIsPrivileged(scanFile)) { 6534 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6535 } else { 6536 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6537 } 6538 6539 if (ps != null && !ps.codePath.equals(scanFile)) { 6540 // The path has changed from what was last scanned... check the 6541 // version of the new path against what we have stored to determine 6542 // what to do. 6543 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6544 if (pkg.mVersionCode <= ps.versionCode) { 6545 // The system package has been updated and the code path does not match 6546 // Ignore entry. Skip it. 6547 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6548 + " ignored: updated version " + ps.versionCode 6549 + " better than this " + pkg.mVersionCode); 6550 if (!updatedPkg.codePath.equals(scanFile)) { 6551 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6552 + ps.name + " changing from " + updatedPkg.codePathString 6553 + " to " + scanFile); 6554 updatedPkg.codePath = scanFile; 6555 updatedPkg.codePathString = scanFile.toString(); 6556 updatedPkg.resourcePath = scanFile; 6557 updatedPkg.resourcePathString = scanFile.toString(); 6558 } 6559 updatedPkg.pkg = pkg; 6560 updatedPkg.versionCode = pkg.mVersionCode; 6561 6562 // Update the disabled system child packages to point to the package too. 6563 final int childCount = updatedPkg.childPackageNames != null 6564 ? updatedPkg.childPackageNames.size() : 0; 6565 for (int i = 0; i < childCount; i++) { 6566 String childPackageName = updatedPkg.childPackageNames.get(i); 6567 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6568 childPackageName); 6569 if (updatedChildPkg != null) { 6570 updatedChildPkg.pkg = pkg; 6571 updatedChildPkg.versionCode = pkg.mVersionCode; 6572 } 6573 } 6574 6575 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6576 + scanFile + " ignored: updated version " + ps.versionCode 6577 + " better than this " + pkg.mVersionCode); 6578 } else { 6579 // The current app on the system partition is better than 6580 // what we have updated to on the data partition; switch 6581 // back to the system partition version. 6582 // At this point, its safely assumed that package installation for 6583 // apps in system partition will go through. If not there won't be a working 6584 // version of the app 6585 // writer 6586 synchronized (mPackages) { 6587 // Just remove the loaded entries from package lists. 6588 mPackages.remove(ps.name); 6589 } 6590 6591 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6592 + " reverting from " + ps.codePathString 6593 + ": new version " + pkg.mVersionCode 6594 + " better than installed " + ps.versionCode); 6595 6596 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6597 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6598 synchronized (mInstallLock) { 6599 args.cleanUpResourcesLI(); 6600 } 6601 synchronized (mPackages) { 6602 mSettings.enableSystemPackageLPw(ps.name); 6603 } 6604 updatedPkgBetter = true; 6605 } 6606 } 6607 } 6608 6609 if (updatedPkg != null) { 6610 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6611 // initially 6612 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6613 6614 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6615 // flag set initially 6616 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6617 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6618 } 6619 } 6620 6621 // Verify certificates against what was last scanned 6622 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6623 6624 /* 6625 * A new system app appeared, but we already had a non-system one of the 6626 * same name installed earlier. 6627 */ 6628 boolean shouldHideSystemApp = false; 6629 if (updatedPkg == null && ps != null 6630 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6631 /* 6632 * Check to make sure the signatures match first. If they don't, 6633 * wipe the installed application and its data. 6634 */ 6635 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6636 != PackageManager.SIGNATURE_MATCH) { 6637 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6638 + " signatures don't match existing userdata copy; removing"); 6639 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6640 ps = null; 6641 } else { 6642 /* 6643 * If the newly-added system app is an older version than the 6644 * already installed version, hide it. It will be scanned later 6645 * and re-added like an update. 6646 */ 6647 if (pkg.mVersionCode <= ps.versionCode) { 6648 shouldHideSystemApp = true; 6649 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6650 + " but new version " + pkg.mVersionCode + " better than installed " 6651 + ps.versionCode + "; hiding system"); 6652 } else { 6653 /* 6654 * The newly found system app is a newer version that the 6655 * one previously installed. Simply remove the 6656 * already-installed application and replace it with our own 6657 * while keeping the application data. 6658 */ 6659 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6660 + " reverting from " + ps.codePathString + ": new version " 6661 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6662 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6663 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6664 synchronized (mInstallLock) { 6665 args.cleanUpResourcesLI(); 6666 } 6667 } 6668 } 6669 } 6670 6671 // The apk is forward locked (not public) if its code and resources 6672 // are kept in different files. (except for app in either system or 6673 // vendor path). 6674 // TODO grab this value from PackageSettings 6675 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6676 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6677 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6678 } 6679 } 6680 6681 // TODO: extend to support forward-locked splits 6682 String resourcePath = null; 6683 String baseResourcePath = null; 6684 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6685 if (ps != null && ps.resourcePathString != null) { 6686 resourcePath = ps.resourcePathString; 6687 baseResourcePath = ps.resourcePathString; 6688 } else { 6689 // Should not happen at all. Just log an error. 6690 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6691 } 6692 } else { 6693 resourcePath = pkg.codePath; 6694 baseResourcePath = pkg.baseCodePath; 6695 } 6696 6697 // Set application objects path explicitly. 6698 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6699 pkg.setApplicationInfoCodePath(pkg.codePath); 6700 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6701 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6702 pkg.setApplicationInfoResourcePath(resourcePath); 6703 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6704 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6705 6706 // Note that we invoke the following method only if we are about to unpack an application 6707 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6708 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6709 6710 /* 6711 * If the system app should be overridden by a previously installed 6712 * data, hide the system app now and let the /data/app scan pick it up 6713 * again. 6714 */ 6715 if (shouldHideSystemApp) { 6716 synchronized (mPackages) { 6717 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6718 } 6719 } 6720 6721 return scannedPkg; 6722 } 6723 6724 private static String fixProcessName(String defProcessName, 6725 String processName, int uid) { 6726 if (processName == null) { 6727 return defProcessName; 6728 } 6729 return processName; 6730 } 6731 6732 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6733 throws PackageManagerException { 6734 if (pkgSetting.signatures.mSignatures != null) { 6735 // Already existing package. Make sure signatures match 6736 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6737 == PackageManager.SIGNATURE_MATCH; 6738 if (!match) { 6739 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6740 == PackageManager.SIGNATURE_MATCH; 6741 } 6742 if (!match) { 6743 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6744 == PackageManager.SIGNATURE_MATCH; 6745 } 6746 if (!match) { 6747 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6748 + pkg.packageName + " signatures do not match the " 6749 + "previously installed version; ignoring!"); 6750 } 6751 } 6752 6753 // Check for shared user signatures 6754 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6755 // Already existing package. Make sure signatures match 6756 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6757 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6758 if (!match) { 6759 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6760 == PackageManager.SIGNATURE_MATCH; 6761 } 6762 if (!match) { 6763 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6764 == PackageManager.SIGNATURE_MATCH; 6765 } 6766 if (!match) { 6767 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6768 "Package " + pkg.packageName 6769 + " has no signatures that match those in shared user " 6770 + pkgSetting.sharedUser.name + "; ignoring!"); 6771 } 6772 } 6773 } 6774 6775 /** 6776 * Enforces that only the system UID or root's UID can call a method exposed 6777 * via Binder. 6778 * 6779 * @param message used as message if SecurityException is thrown 6780 * @throws SecurityException if the caller is not system or root 6781 */ 6782 private static final void enforceSystemOrRoot(String message) { 6783 final int uid = Binder.getCallingUid(); 6784 if (uid != Process.SYSTEM_UID && uid != 0) { 6785 throw new SecurityException(message); 6786 } 6787 } 6788 6789 @Override 6790 public void performFstrimIfNeeded() { 6791 enforceSystemOrRoot("Only the system can request fstrim"); 6792 6793 // Before everything else, see whether we need to fstrim. 6794 try { 6795 IMountService ms = PackageHelper.getMountService(); 6796 if (ms != null) { 6797 final boolean isUpgrade = isUpgrade(); 6798 boolean doTrim = isUpgrade; 6799 if (doTrim) { 6800 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6801 } else { 6802 final long interval = android.provider.Settings.Global.getLong( 6803 mContext.getContentResolver(), 6804 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6805 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6806 if (interval > 0) { 6807 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6808 if (timeSinceLast > interval) { 6809 doTrim = true; 6810 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6811 + "; running immediately"); 6812 } 6813 } 6814 } 6815 if (doTrim) { 6816 if (!isFirstBoot()) { 6817 try { 6818 ActivityManagerNative.getDefault().showBootMessage( 6819 mContext.getResources().getString( 6820 R.string.android_upgrading_fstrim), true); 6821 } catch (RemoteException e) { 6822 } 6823 } 6824 ms.runMaintenance(); 6825 } 6826 } else { 6827 Slog.e(TAG, "Mount service unavailable!"); 6828 } 6829 } catch (RemoteException e) { 6830 // Can't happen; MountService is local 6831 } 6832 } 6833 6834 @Override 6835 public void extractPackagesIfNeeded() { 6836 enforceSystemOrRoot("Only the system can request package extraction"); 6837 6838 // Extract pacakges only if profile-guided compilation is enabled because 6839 // otherwise BackgroundDexOptService will not dexopt them later. 6840 if (!mUseJitProfiles || !isUpgrade()) { 6841 return; 6842 } 6843 6844 List<PackageParser.Package> pkgs; 6845 synchronized (mPackages) { 6846 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6847 } 6848 6849 int curr = 0; 6850 int total = pkgs.size(); 6851 for (PackageParser.Package pkg : pkgs) { 6852 curr++; 6853 6854 if (DEBUG_DEXOPT) { 6855 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6856 } 6857 6858 if (!isFirstBoot()) { 6859 try { 6860 ActivityManagerNative.getDefault().showBootMessage( 6861 mContext.getResources().getString(R.string.android_upgrading_apk, 6862 curr, total), true); 6863 } catch (RemoteException e) { 6864 } 6865 } 6866 6867 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6868 performDexOpt(pkg.packageName, null /* instructionSet */, 6869 false /* useProfiles */, true /* extractOnly */, false /* force */); 6870 } 6871 } 6872 } 6873 6874 @Override 6875 public void notifyPackageUse(String packageName) { 6876 synchronized (mPackages) { 6877 PackageParser.Package p = mPackages.get(packageName); 6878 if (p == null) { 6879 return; 6880 } 6881 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6882 } 6883 } 6884 6885 // TODO: this is not used nor needed. Delete it. 6886 @Override 6887 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6888 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6889 false /* extractOnly */, false /* force */); 6890 } 6891 6892 @Override 6893 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6894 boolean extractOnly, boolean force) { 6895 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6896 } 6897 6898 private boolean performDexOptTraced(String packageName, String instructionSet, 6899 boolean useProfiles, boolean extractOnly, boolean force) { 6900 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6901 try { 6902 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6903 force); 6904 } finally { 6905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6906 } 6907 } 6908 6909 private boolean performDexOptInternal(String packageName, String instructionSet, 6910 boolean useProfiles, boolean extractOnly, boolean force) { 6911 PackageParser.Package p; 6912 final String targetInstructionSet; 6913 synchronized (mPackages) { 6914 p = mPackages.get(packageName); 6915 if (p == null) { 6916 return false; 6917 } 6918 mPackageUsage.write(false); 6919 6920 targetInstructionSet = instructionSet != null ? instructionSet : 6921 getPrimaryInstructionSet(p.applicationInfo); 6922 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6923 // Skip only if we do not use profiles since they might trigger a recompilation. 6924 return false; 6925 } 6926 } 6927 long callingId = Binder.clearCallingIdentity(); 6928 try { 6929 synchronized (mInstallLock) { 6930 final String[] instructionSets = new String[] { targetInstructionSet }; 6931 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6932 useProfiles, extractOnly, force); 6933 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6934 } 6935 } finally { 6936 Binder.restoreCallingIdentity(callingId); 6937 } 6938 } 6939 6940 public ArraySet<String> getOptimizablePackages() { 6941 ArraySet<String> pkgs = new ArraySet<String>(); 6942 synchronized (mPackages) { 6943 for (PackageParser.Package p : mPackages.values()) { 6944 if (PackageDexOptimizer.canOptimizePackage(p)) { 6945 pkgs.add(p.packageName); 6946 } 6947 } 6948 } 6949 return pkgs; 6950 } 6951 6952 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6953 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6954 // Select the dex optimizer based on the force parameter. 6955 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6956 // allocate an object here. 6957 PackageDexOptimizer pdo = force 6958 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6959 : mPackageDexOptimizer; 6960 6961 // Optimize all dependencies first. Note: we ignore the return value and march on 6962 // on errors. 6963 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6964 if (!deps.isEmpty()) { 6965 for (PackageParser.Package depPackage : deps) { 6966 // TODO: Analyze and investigate if we (should) profile libraries. 6967 // Currently this will do a full compilation of the library. 6968 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6969 false /* extractOnly */); 6970 } 6971 } 6972 6973 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6974 } 6975 6976 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6977 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6978 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6979 Set<String> collectedNames = new HashSet<>(); 6980 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6981 6982 retValue.remove(p); 6983 6984 return retValue; 6985 } else { 6986 return Collections.emptyList(); 6987 } 6988 } 6989 6990 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6991 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6992 if (!collectedNames.contains(p.packageName)) { 6993 collectedNames.add(p.packageName); 6994 collected.add(p); 6995 6996 if (p.usesLibraries != null) { 6997 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6998 } 6999 if (p.usesOptionalLibraries != null) { 7000 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7001 collectedNames); 7002 } 7003 } 7004 } 7005 7006 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7007 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7008 for (String libName : libs) { 7009 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7010 if (libPkg != null) { 7011 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7012 } 7013 } 7014 } 7015 7016 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7017 synchronized (mPackages) { 7018 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7019 if (lib != null && lib.apk != null) { 7020 return mPackages.get(lib.apk); 7021 } 7022 } 7023 return null; 7024 } 7025 7026 public void shutdown() { 7027 mPackageUsage.write(true); 7028 } 7029 7030 @Override 7031 public void forceDexOpt(String packageName) { 7032 enforceSystemOrRoot("forceDexOpt"); 7033 7034 PackageParser.Package pkg; 7035 synchronized (mPackages) { 7036 pkg = mPackages.get(packageName); 7037 if (pkg == null) { 7038 throw new IllegalArgumentException("Unknown package: " + packageName); 7039 } 7040 } 7041 7042 synchronized (mInstallLock) { 7043 final String[] instructionSets = new String[] { 7044 getPrimaryInstructionSet(pkg.applicationInfo) }; 7045 7046 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7047 7048 // Whoever is calling forceDexOpt wants a fully compiled package. 7049 // Don't use profiles since that may cause compilation to be skipped. 7050 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7051 false /* useProfiles */, false /* extractOnly */, true /* force */); 7052 7053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7054 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7055 throw new IllegalStateException("Failed to dexopt: " + res); 7056 } 7057 } 7058 } 7059 7060 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7061 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7062 Slog.w(TAG, "Unable to update from " + oldPkg.name 7063 + " to " + newPkg.packageName 7064 + ": old package not in system partition"); 7065 return false; 7066 } else if (mPackages.get(oldPkg.name) != null) { 7067 Slog.w(TAG, "Unable to update from " + oldPkg.name 7068 + " to " + newPkg.packageName 7069 + ": old package still exists"); 7070 return false; 7071 } 7072 return true; 7073 } 7074 7075 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7076 // TODO: triage flags as part of 26466827 7077 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7078 7079 boolean res = true; 7080 final int[] users = sUserManager.getUserIds(); 7081 for (int user : users) { 7082 try { 7083 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7084 } catch (InstallerException e) { 7085 Slog.w(TAG, "Failed to delete data directory", e); 7086 res = false; 7087 } 7088 } 7089 return res; 7090 } 7091 7092 void removeCodePathLI(File codePath) { 7093 if (codePath.isDirectory()) { 7094 try { 7095 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7096 } catch (InstallerException e) { 7097 Slog.w(TAG, "Failed to remove code path", e); 7098 } 7099 } else { 7100 codePath.delete(); 7101 } 7102 } 7103 7104 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7105 try { 7106 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7107 } catch (InstallerException e) { 7108 Slog.w(TAG, "Failed to destroy app data", e); 7109 } 7110 } 7111 7112 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7113 int appId, String seinfo) { 7114 try { 7115 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7116 } catch (InstallerException e) { 7117 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7118 } 7119 } 7120 7121 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7122 final PackageParser.Package pkg; 7123 synchronized (mPackages) { 7124 pkg = mPackages.get(packageName); 7125 } 7126 if (pkg == null) { 7127 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7128 return; 7129 } 7130 deleteCodeCacheDirsLI(pkg); 7131 } 7132 7133 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7134 // TODO: triage flags as part of 26466827 7135 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7136 7137 int[] users = sUserManager.getUserIds(); 7138 int res = 0; 7139 for (int user : users) { 7140 // Remove the parent code cache 7141 try { 7142 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7143 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7144 } catch (InstallerException e) { 7145 Slog.w(TAG, "Failed to delete code cache directory", e); 7146 } 7147 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7148 for (int i = 0; i < childCount; i++) { 7149 PackageParser.Package childPkg = pkg.childPackages.get(i); 7150 // Remove the child code cache 7151 try { 7152 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7153 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7154 } catch (InstallerException e) { 7155 Slog.w(TAG, "Failed to delete code cache directory", e); 7156 } 7157 } 7158 } 7159 } 7160 7161 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7162 long lastUpdateTime) { 7163 // Set parent install/update time 7164 PackageSetting ps = (PackageSetting) pkg.mExtras; 7165 if (ps != null) { 7166 ps.firstInstallTime = firstInstallTime; 7167 ps.lastUpdateTime = lastUpdateTime; 7168 } 7169 // Set children install/update time 7170 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7171 for (int i = 0; i < childCount; i++) { 7172 PackageParser.Package childPkg = pkg.childPackages.get(i); 7173 ps = (PackageSetting) childPkg.mExtras; 7174 if (ps != null) { 7175 ps.firstInstallTime = firstInstallTime; 7176 ps.lastUpdateTime = lastUpdateTime; 7177 } 7178 } 7179 } 7180 7181 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7182 PackageParser.Package changingLib) { 7183 if (file.path != null) { 7184 usesLibraryFiles.add(file.path); 7185 return; 7186 } 7187 PackageParser.Package p = mPackages.get(file.apk); 7188 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7189 // If we are doing this while in the middle of updating a library apk, 7190 // then we need to make sure to use that new apk for determining the 7191 // dependencies here. (We haven't yet finished committing the new apk 7192 // to the package manager state.) 7193 if (p == null || p.packageName.equals(changingLib.packageName)) { 7194 p = changingLib; 7195 } 7196 } 7197 if (p != null) { 7198 usesLibraryFiles.addAll(p.getAllCodePaths()); 7199 } 7200 } 7201 7202 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7203 PackageParser.Package changingLib) throws PackageManagerException { 7204 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7205 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7206 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7207 for (int i=0; i<N; i++) { 7208 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7209 if (file == null) { 7210 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7211 "Package " + pkg.packageName + " requires unavailable shared library " 7212 + pkg.usesLibraries.get(i) + "; failing!"); 7213 } 7214 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7215 } 7216 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7217 for (int i=0; i<N; i++) { 7218 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7219 if (file == null) { 7220 Slog.w(TAG, "Package " + pkg.packageName 7221 + " desires unavailable shared library " 7222 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7223 } else { 7224 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7225 } 7226 } 7227 N = usesLibraryFiles.size(); 7228 if (N > 0) { 7229 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7230 } else { 7231 pkg.usesLibraryFiles = null; 7232 } 7233 } 7234 } 7235 7236 private static boolean hasString(List<String> list, List<String> which) { 7237 if (list == null) { 7238 return false; 7239 } 7240 for (int i=list.size()-1; i>=0; i--) { 7241 for (int j=which.size()-1; j>=0; j--) { 7242 if (which.get(j).equals(list.get(i))) { 7243 return true; 7244 } 7245 } 7246 } 7247 return false; 7248 } 7249 7250 private void updateAllSharedLibrariesLPw() { 7251 for (PackageParser.Package pkg : mPackages.values()) { 7252 try { 7253 updateSharedLibrariesLPw(pkg, null); 7254 } catch (PackageManagerException e) { 7255 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7256 } 7257 } 7258 } 7259 7260 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7261 PackageParser.Package changingPkg) { 7262 ArrayList<PackageParser.Package> res = null; 7263 for (PackageParser.Package pkg : mPackages.values()) { 7264 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7265 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7266 if (res == null) { 7267 res = new ArrayList<PackageParser.Package>(); 7268 } 7269 res.add(pkg); 7270 try { 7271 updateSharedLibrariesLPw(pkg, changingPkg); 7272 } catch (PackageManagerException e) { 7273 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7274 } 7275 } 7276 } 7277 return res; 7278 } 7279 7280 /** 7281 * Derive the value of the {@code cpuAbiOverride} based on the provided 7282 * value and an optional stored value from the package settings. 7283 */ 7284 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7285 String cpuAbiOverride = null; 7286 7287 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7288 cpuAbiOverride = null; 7289 } else if (abiOverride != null) { 7290 cpuAbiOverride = abiOverride; 7291 } else if (settings != null) { 7292 cpuAbiOverride = settings.cpuAbiOverrideString; 7293 } 7294 7295 return cpuAbiOverride; 7296 } 7297 7298 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7299 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7301 // If the package has children and this is the first dive in the function 7302 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7303 // whether all packages (parent and children) would be successfully scanned 7304 // before the actual scan since scanning mutates internal state and we want 7305 // to atomically install the package and its children. 7306 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7307 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7308 scanFlags |= SCAN_CHECK_ONLY; 7309 } 7310 } else { 7311 scanFlags &= ~SCAN_CHECK_ONLY; 7312 } 7313 7314 final PackageParser.Package scannedPkg; 7315 try { 7316 // Scan the parent 7317 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7318 // Scan the children 7319 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7320 for (int i = 0; i < childCount; i++) { 7321 PackageParser.Package childPkg = pkg.childPackages.get(i); 7322 scanPackageLI(childPkg, parseFlags, 7323 scanFlags, currentTime, user); 7324 } 7325 } finally { 7326 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7327 } 7328 7329 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7330 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7331 } 7332 7333 return scannedPkg; 7334 } 7335 7336 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7337 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7338 boolean success = false; 7339 try { 7340 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7341 currentTime, user); 7342 success = true; 7343 return res; 7344 } finally { 7345 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7346 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7347 } 7348 } 7349 } 7350 7351 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7352 int scanFlags, long currentTime, UserHandle user) 7353 throws PackageManagerException { 7354 final File scanFile = new File(pkg.codePath); 7355 if (pkg.applicationInfo.getCodePath() == null || 7356 pkg.applicationInfo.getResourcePath() == null) { 7357 // Bail out. The resource and code paths haven't been set. 7358 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7359 "Code and resource paths haven't been set correctly"); 7360 } 7361 7362 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7363 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7364 } else { 7365 // Only allow system apps to be flagged as core apps. 7366 pkg.coreApp = false; 7367 } 7368 7369 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7370 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7371 } 7372 7373 if (mCustomResolverComponentName != null && 7374 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7375 setUpCustomResolverActivity(pkg); 7376 } 7377 7378 if (pkg.packageName.equals("android")) { 7379 synchronized (mPackages) { 7380 if (mAndroidApplication != null) { 7381 Slog.w(TAG, "*************************************************"); 7382 Slog.w(TAG, "Core android package being redefined. Skipping."); 7383 Slog.w(TAG, " file=" + scanFile); 7384 Slog.w(TAG, "*************************************************"); 7385 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7386 "Core android package being redefined. Skipping."); 7387 } 7388 7389 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7390 // Set up information for our fall-back user intent resolution activity. 7391 mPlatformPackage = pkg; 7392 pkg.mVersionCode = mSdkVersion; 7393 mAndroidApplication = pkg.applicationInfo; 7394 7395 if (!mResolverReplaced) { 7396 mResolveActivity.applicationInfo = mAndroidApplication; 7397 mResolveActivity.name = ResolverActivity.class.getName(); 7398 mResolveActivity.packageName = mAndroidApplication.packageName; 7399 mResolveActivity.processName = "system:ui"; 7400 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7401 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7402 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7403 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7404 mResolveActivity.exported = true; 7405 mResolveActivity.enabled = true; 7406 mResolveInfo.activityInfo = mResolveActivity; 7407 mResolveInfo.priority = 0; 7408 mResolveInfo.preferredOrder = 0; 7409 mResolveInfo.match = 0; 7410 mResolveComponentName = new ComponentName( 7411 mAndroidApplication.packageName, mResolveActivity.name); 7412 } 7413 } 7414 } 7415 } 7416 7417 if (DEBUG_PACKAGE_SCANNING) { 7418 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7419 Log.d(TAG, "Scanning package " + pkg.packageName); 7420 } 7421 7422 synchronized (mPackages) { 7423 if (mPackages.containsKey(pkg.packageName) 7424 || mSharedLibraries.containsKey(pkg.packageName)) { 7425 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7426 "Application package " + pkg.packageName 7427 + " already installed. Skipping duplicate."); 7428 } 7429 7430 // If we're only installing presumed-existing packages, require that the 7431 // scanned APK is both already known and at the path previously established 7432 // for it. Previously unknown packages we pick up normally, but if we have an 7433 // a priori expectation about this package's install presence, enforce it. 7434 // With a singular exception for new system packages. When an OTA contains 7435 // a new system package, we allow the codepath to change from a system location 7436 // to the user-installed location. If we don't allow this change, any newer, 7437 // user-installed version of the application will be ignored. 7438 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7439 if (mExpectingBetter.containsKey(pkg.packageName)) { 7440 logCriticalInfo(Log.WARN, 7441 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7442 } else { 7443 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7444 if (known != null) { 7445 if (DEBUG_PACKAGE_SCANNING) { 7446 Log.d(TAG, "Examining " + pkg.codePath 7447 + " and requiring known paths " + known.codePathString 7448 + " & " + known.resourcePathString); 7449 } 7450 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7451 || !pkg.applicationInfo.getResourcePath().equals( 7452 known.resourcePathString)) { 7453 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7454 "Application package " + pkg.packageName 7455 + " found at " + pkg.applicationInfo.getCodePath() 7456 + " but expected at " + known.codePathString 7457 + "; ignoring."); 7458 } 7459 } 7460 } 7461 } 7462 } 7463 7464 // Initialize package source and resource directories 7465 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7466 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7467 7468 SharedUserSetting suid = null; 7469 PackageSetting pkgSetting = null; 7470 7471 if (!isSystemApp(pkg)) { 7472 // Only system apps can use these features. 7473 pkg.mOriginalPackages = null; 7474 pkg.mRealPackage = null; 7475 pkg.mAdoptPermissions = null; 7476 } 7477 7478 // Getting the package setting may have a side-effect, so if we 7479 // are only checking if scan would succeed, stash a copy of the 7480 // old setting to restore at the end. 7481 PackageSetting nonMutatedPs = null; 7482 7483 // writer 7484 synchronized (mPackages) { 7485 if (pkg.mSharedUserId != null) { 7486 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7487 if (suid == null) { 7488 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7489 "Creating application package " + pkg.packageName 7490 + " for shared user failed"); 7491 } 7492 if (DEBUG_PACKAGE_SCANNING) { 7493 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7494 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7495 + "): packages=" + suid.packages); 7496 } 7497 } 7498 7499 // Check if we are renaming from an original package name. 7500 PackageSetting origPackage = null; 7501 String realName = null; 7502 if (pkg.mOriginalPackages != null) { 7503 // This package may need to be renamed to a previously 7504 // installed name. Let's check on that... 7505 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7506 if (pkg.mOriginalPackages.contains(renamed)) { 7507 // This package had originally been installed as the 7508 // original name, and we have already taken care of 7509 // transitioning to the new one. Just update the new 7510 // one to continue using the old name. 7511 realName = pkg.mRealPackage; 7512 if (!pkg.packageName.equals(renamed)) { 7513 // Callers into this function may have already taken 7514 // care of renaming the package; only do it here if 7515 // it is not already done. 7516 pkg.setPackageName(renamed); 7517 } 7518 7519 } else { 7520 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7521 if ((origPackage = mSettings.peekPackageLPr( 7522 pkg.mOriginalPackages.get(i))) != null) { 7523 // We do have the package already installed under its 7524 // original name... should we use it? 7525 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7526 // New package is not compatible with original. 7527 origPackage = null; 7528 continue; 7529 } else if (origPackage.sharedUser != null) { 7530 // Make sure uid is compatible between packages. 7531 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7532 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7533 + " to " + pkg.packageName + ": old uid " 7534 + origPackage.sharedUser.name 7535 + " differs from " + pkg.mSharedUserId); 7536 origPackage = null; 7537 continue; 7538 } 7539 } else { 7540 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7541 + pkg.packageName + " to old name " + origPackage.name); 7542 } 7543 break; 7544 } 7545 } 7546 } 7547 } 7548 7549 if (mTransferedPackages.contains(pkg.packageName)) { 7550 Slog.w(TAG, "Package " + pkg.packageName 7551 + " was transferred to another, but its .apk remains"); 7552 } 7553 7554 // See comments in nonMutatedPs declaration 7555 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7556 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7557 if (foundPs != null) { 7558 nonMutatedPs = new PackageSetting(foundPs); 7559 } 7560 } 7561 7562 // Just create the setting, don't add it yet. For already existing packages 7563 // the PkgSetting exists already and doesn't have to be created. 7564 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7565 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7566 pkg.applicationInfo.primaryCpuAbi, 7567 pkg.applicationInfo.secondaryCpuAbi, 7568 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7569 user, false); 7570 if (pkgSetting == null) { 7571 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7572 "Creating application package " + pkg.packageName + " failed"); 7573 } 7574 7575 if (pkgSetting.origPackage != null) { 7576 // If we are first transitioning from an original package, 7577 // fix up the new package's name now. We need to do this after 7578 // looking up the package under its new name, so getPackageLP 7579 // can take care of fiddling things correctly. 7580 pkg.setPackageName(origPackage.name); 7581 7582 // File a report about this. 7583 String msg = "New package " + pkgSetting.realName 7584 + " renamed to replace old package " + pkgSetting.name; 7585 reportSettingsProblem(Log.WARN, msg); 7586 7587 // Make a note of it. 7588 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7589 mTransferedPackages.add(origPackage.name); 7590 } 7591 7592 // No longer need to retain this. 7593 pkgSetting.origPackage = null; 7594 } 7595 7596 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7597 // Make a note of it. 7598 mTransferedPackages.add(pkg.packageName); 7599 } 7600 7601 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7602 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7603 } 7604 7605 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7606 // Check all shared libraries and map to their actual file path. 7607 // We only do this here for apps not on a system dir, because those 7608 // are the only ones that can fail an install due to this. We 7609 // will take care of the system apps by updating all of their 7610 // library paths after the scan is done. 7611 updateSharedLibrariesLPw(pkg, null); 7612 } 7613 7614 if (mFoundPolicyFile) { 7615 SELinuxMMAC.assignSeinfoValue(pkg); 7616 } 7617 7618 pkg.applicationInfo.uid = pkgSetting.appId; 7619 pkg.mExtras = pkgSetting; 7620 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7621 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7622 // We just determined the app is signed correctly, so bring 7623 // over the latest parsed certs. 7624 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7625 } else { 7626 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7627 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7628 "Package " + pkg.packageName + " upgrade keys do not match the " 7629 + "previously installed version"); 7630 } else { 7631 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7632 String msg = "System package " + pkg.packageName 7633 + " signature changed; retaining data."; 7634 reportSettingsProblem(Log.WARN, msg); 7635 } 7636 } 7637 } else { 7638 try { 7639 verifySignaturesLP(pkgSetting, pkg); 7640 // We just determined the app is signed correctly, so bring 7641 // over the latest parsed certs. 7642 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7643 } catch (PackageManagerException e) { 7644 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7645 throw e; 7646 } 7647 // The signature has changed, but this package is in the system 7648 // image... let's recover! 7649 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7650 // However... if this package is part of a shared user, but it 7651 // doesn't match the signature of the shared user, let's fail. 7652 // What this means is that you can't change the signatures 7653 // associated with an overall shared user, which doesn't seem all 7654 // that unreasonable. 7655 if (pkgSetting.sharedUser != null) { 7656 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7657 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7658 throw new PackageManagerException( 7659 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7660 "Signature mismatch for shared user: " 7661 + pkgSetting.sharedUser); 7662 } 7663 } 7664 // File a report about this. 7665 String msg = "System package " + pkg.packageName 7666 + " signature changed; retaining data."; 7667 reportSettingsProblem(Log.WARN, msg); 7668 } 7669 } 7670 // Verify that this new package doesn't have any content providers 7671 // that conflict with existing packages. Only do this if the 7672 // package isn't already installed, since we don't want to break 7673 // things that are installed. 7674 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7675 final int N = pkg.providers.size(); 7676 int i; 7677 for (i=0; i<N; i++) { 7678 PackageParser.Provider p = pkg.providers.get(i); 7679 if (p.info.authority != null) { 7680 String names[] = p.info.authority.split(";"); 7681 for (int j = 0; j < names.length; j++) { 7682 if (mProvidersByAuthority.containsKey(names[j])) { 7683 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7684 final String otherPackageName = 7685 ((other != null && other.getComponentName() != null) ? 7686 other.getComponentName().getPackageName() : "?"); 7687 throw new PackageManagerException( 7688 INSTALL_FAILED_CONFLICTING_PROVIDER, 7689 "Can't install because provider name " + names[j] 7690 + " (in package " + pkg.applicationInfo.packageName 7691 + ") is already used by " + otherPackageName); 7692 } 7693 } 7694 } 7695 } 7696 } 7697 7698 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7699 // This package wants to adopt ownership of permissions from 7700 // another package. 7701 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7702 final String origName = pkg.mAdoptPermissions.get(i); 7703 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7704 if (orig != null) { 7705 if (verifyPackageUpdateLPr(orig, pkg)) { 7706 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7707 + pkg.packageName); 7708 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7709 } 7710 } 7711 } 7712 } 7713 } 7714 7715 final String pkgName = pkg.packageName; 7716 7717 final long scanFileTime = scanFile.lastModified(); 7718 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7719 pkg.applicationInfo.processName = fixProcessName( 7720 pkg.applicationInfo.packageName, 7721 pkg.applicationInfo.processName, 7722 pkg.applicationInfo.uid); 7723 7724 if (pkg != mPlatformPackage) { 7725 // Get all of our default paths setup 7726 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7727 } 7728 7729 final String path = scanFile.getPath(); 7730 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7731 7732 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7733 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7734 7735 // Some system apps still use directory structure for native libraries 7736 // in which case we might end up not detecting abi solely based on apk 7737 // structure. Try to detect abi based on directory structure. 7738 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7739 pkg.applicationInfo.primaryCpuAbi == null) { 7740 setBundledAppAbisAndRoots(pkg, pkgSetting); 7741 setNativeLibraryPaths(pkg); 7742 } 7743 7744 } else { 7745 if ((scanFlags & SCAN_MOVE) != 0) { 7746 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7747 // but we already have this packages package info in the PackageSetting. We just 7748 // use that and derive the native library path based on the new codepath. 7749 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7750 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7751 } 7752 7753 // Set native library paths again. For moves, the path will be updated based on the 7754 // ABIs we've determined above. For non-moves, the path will be updated based on the 7755 // ABIs we determined during compilation, but the path will depend on the final 7756 // package path (after the rename away from the stage path). 7757 setNativeLibraryPaths(pkg); 7758 } 7759 7760 // This is a special case for the "system" package, where the ABI is 7761 // dictated by the zygote configuration (and init.rc). We should keep track 7762 // of this ABI so that we can deal with "normal" applications that run under 7763 // the same UID correctly. 7764 if (mPlatformPackage == pkg) { 7765 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7766 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7767 } 7768 7769 // If there's a mismatch between the abi-override in the package setting 7770 // and the abiOverride specified for the install. Warn about this because we 7771 // would've already compiled the app without taking the package setting into 7772 // account. 7773 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7774 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7775 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7776 " for package " + pkg.packageName); 7777 } 7778 } 7779 7780 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7781 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7782 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7783 7784 // Copy the derived override back to the parsed package, so that we can 7785 // update the package settings accordingly. 7786 pkg.cpuAbiOverride = cpuAbiOverride; 7787 7788 if (DEBUG_ABI_SELECTION) { 7789 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7790 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7791 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7792 } 7793 7794 // Push the derived path down into PackageSettings so we know what to 7795 // clean up at uninstall time. 7796 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7797 7798 if (DEBUG_ABI_SELECTION) { 7799 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7800 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7801 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7802 } 7803 7804 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7805 // We don't do this here during boot because we can do it all 7806 // at once after scanning all existing packages. 7807 // 7808 // We also do this *before* we perform dexopt on this package, so that 7809 // we can avoid redundant dexopts, and also to make sure we've got the 7810 // code and package path correct. 7811 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7812 pkg, true /* boot complete */); 7813 } 7814 7815 if (mFactoryTest && pkg.requestedPermissions.contains( 7816 android.Manifest.permission.FACTORY_TEST)) { 7817 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7818 } 7819 7820 ArrayList<PackageParser.Package> clientLibPkgs = null; 7821 7822 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7823 if (nonMutatedPs != null) { 7824 synchronized (mPackages) { 7825 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7826 } 7827 } 7828 return pkg; 7829 } 7830 7831 // Only privileged apps and updated privileged apps can add child packages. 7832 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7833 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7834 throw new PackageManagerException("Only privileged apps and updated " 7835 + "privileged apps can add child packages. Ignoring package " 7836 + pkg.packageName); 7837 } 7838 final int childCount = pkg.childPackages.size(); 7839 for (int i = 0; i < childCount; i++) { 7840 PackageParser.Package childPkg = pkg.childPackages.get(i); 7841 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7842 childPkg.packageName)) { 7843 throw new PackageManagerException("Cannot override a child package of " 7844 + "another disabled system app. Ignoring package " + pkg.packageName); 7845 } 7846 } 7847 } 7848 7849 // writer 7850 synchronized (mPackages) { 7851 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7852 // Only system apps can add new shared libraries. 7853 if (pkg.libraryNames != null) { 7854 for (int i=0; i<pkg.libraryNames.size(); i++) { 7855 String name = pkg.libraryNames.get(i); 7856 boolean allowed = false; 7857 if (pkg.isUpdatedSystemApp()) { 7858 // New library entries can only be added through the 7859 // system image. This is important to get rid of a lot 7860 // of nasty edge cases: for example if we allowed a non- 7861 // system update of the app to add a library, then uninstalling 7862 // the update would make the library go away, and assumptions 7863 // we made such as through app install filtering would now 7864 // have allowed apps on the device which aren't compatible 7865 // with it. Better to just have the restriction here, be 7866 // conservative, and create many fewer cases that can negatively 7867 // impact the user experience. 7868 final PackageSetting sysPs = mSettings 7869 .getDisabledSystemPkgLPr(pkg.packageName); 7870 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7871 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7872 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7873 allowed = true; 7874 break; 7875 } 7876 } 7877 } 7878 } else { 7879 allowed = true; 7880 } 7881 if (allowed) { 7882 if (!mSharedLibraries.containsKey(name)) { 7883 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7884 } else if (!name.equals(pkg.packageName)) { 7885 Slog.w(TAG, "Package " + pkg.packageName + " library " 7886 + name + " already exists; skipping"); 7887 } 7888 } else { 7889 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7890 + name + " that is not declared on system image; skipping"); 7891 } 7892 } 7893 if ((scanFlags & SCAN_BOOTING) == 0) { 7894 // If we are not booting, we need to update any applications 7895 // that are clients of our shared library. If we are booting, 7896 // this will all be done once the scan is complete. 7897 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7898 } 7899 } 7900 } 7901 } 7902 7903 // Request the ActivityManager to kill the process(only for existing packages) 7904 // so that we do not end up in a confused state while the user is still using the older 7905 // version of the application while the new one gets installed. 7906 if ((scanFlags & SCAN_REPLACING) != 0) { 7907 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7908 7909 killApplication(pkg.applicationInfo.packageName, 7910 pkg.applicationInfo.uid, "replace pkg"); 7911 7912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7913 } 7914 7915 // Also need to kill any apps that are dependent on the library. 7916 if (clientLibPkgs != null) { 7917 for (int i=0; i<clientLibPkgs.size(); i++) { 7918 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7919 killApplication(clientPkg.applicationInfo.packageName, 7920 clientPkg.applicationInfo.uid, "update lib"); 7921 } 7922 } 7923 7924 // Make sure we're not adding any bogus keyset info 7925 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7926 ksms.assertScannedPackageValid(pkg); 7927 7928 // writer 7929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7930 7931 boolean createIdmapFailed = false; 7932 synchronized (mPackages) { 7933 // We don't expect installation to fail beyond this point 7934 7935 // Add the new setting to mSettings 7936 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7937 // Add the new setting to mPackages 7938 mPackages.put(pkg.applicationInfo.packageName, pkg); 7939 // Make sure we don't accidentally delete its data. 7940 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7941 while (iter.hasNext()) { 7942 PackageCleanItem item = iter.next(); 7943 if (pkgName.equals(item.packageName)) { 7944 iter.remove(); 7945 } 7946 } 7947 7948 // Take care of first install / last update times. 7949 if (currentTime != 0) { 7950 if (pkgSetting.firstInstallTime == 0) { 7951 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7952 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7953 pkgSetting.lastUpdateTime = currentTime; 7954 } 7955 } else if (pkgSetting.firstInstallTime == 0) { 7956 // We need *something*. Take time time stamp of the file. 7957 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7958 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7959 if (scanFileTime != pkgSetting.timeStamp) { 7960 // A package on the system image has changed; consider this 7961 // to be an update. 7962 pkgSetting.lastUpdateTime = scanFileTime; 7963 } 7964 } 7965 7966 // Add the package's KeySets to the global KeySetManagerService 7967 ksms.addScannedPackageLPw(pkg); 7968 7969 int N = pkg.providers.size(); 7970 StringBuilder r = null; 7971 int i; 7972 for (i=0; i<N; i++) { 7973 PackageParser.Provider p = pkg.providers.get(i); 7974 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7975 p.info.processName, pkg.applicationInfo.uid); 7976 mProviders.addProvider(p); 7977 p.syncable = p.info.isSyncable; 7978 if (p.info.authority != null) { 7979 String names[] = p.info.authority.split(";"); 7980 p.info.authority = null; 7981 for (int j = 0; j < names.length; j++) { 7982 if (j == 1 && p.syncable) { 7983 // We only want the first authority for a provider to possibly be 7984 // syncable, so if we already added this provider using a different 7985 // authority clear the syncable flag. We copy the provider before 7986 // changing it because the mProviders object contains a reference 7987 // to a provider that we don't want to change. 7988 // Only do this for the second authority since the resulting provider 7989 // object can be the same for all future authorities for this provider. 7990 p = new PackageParser.Provider(p); 7991 p.syncable = false; 7992 } 7993 if (!mProvidersByAuthority.containsKey(names[j])) { 7994 mProvidersByAuthority.put(names[j], p); 7995 if (p.info.authority == null) { 7996 p.info.authority = names[j]; 7997 } else { 7998 p.info.authority = p.info.authority + ";" + names[j]; 7999 } 8000 if (DEBUG_PACKAGE_SCANNING) { 8001 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8002 Log.d(TAG, "Registered content provider: " + names[j] 8003 + ", className = " + p.info.name + ", isSyncable = " 8004 + p.info.isSyncable); 8005 } 8006 } else { 8007 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8008 Slog.w(TAG, "Skipping provider name " + names[j] + 8009 " (in package " + pkg.applicationInfo.packageName + 8010 "): name already used by " 8011 + ((other != null && other.getComponentName() != null) 8012 ? other.getComponentName().getPackageName() : "?")); 8013 } 8014 } 8015 } 8016 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8017 if (r == null) { 8018 r = new StringBuilder(256); 8019 } else { 8020 r.append(' '); 8021 } 8022 r.append(p.info.name); 8023 } 8024 } 8025 if (r != null) { 8026 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8027 } 8028 8029 N = pkg.services.size(); 8030 r = null; 8031 for (i=0; i<N; i++) { 8032 PackageParser.Service s = pkg.services.get(i); 8033 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8034 s.info.processName, pkg.applicationInfo.uid); 8035 mServices.addService(s); 8036 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8037 if (r == null) { 8038 r = new StringBuilder(256); 8039 } else { 8040 r.append(' '); 8041 } 8042 r.append(s.info.name); 8043 } 8044 } 8045 if (r != null) { 8046 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8047 } 8048 8049 N = pkg.receivers.size(); 8050 r = null; 8051 for (i=0; i<N; i++) { 8052 PackageParser.Activity a = pkg.receivers.get(i); 8053 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8054 a.info.processName, pkg.applicationInfo.uid); 8055 mReceivers.addActivity(a, "receiver"); 8056 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8057 if (r == null) { 8058 r = new StringBuilder(256); 8059 } else { 8060 r.append(' '); 8061 } 8062 r.append(a.info.name); 8063 } 8064 } 8065 if (r != null) { 8066 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8067 } 8068 8069 N = pkg.activities.size(); 8070 r = null; 8071 for (i=0; i<N; i++) { 8072 PackageParser.Activity a = pkg.activities.get(i); 8073 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8074 a.info.processName, pkg.applicationInfo.uid); 8075 mActivities.addActivity(a, "activity"); 8076 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8077 if (r == null) { 8078 r = new StringBuilder(256); 8079 } else { 8080 r.append(' '); 8081 } 8082 r.append(a.info.name); 8083 } 8084 } 8085 if (r != null) { 8086 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8087 } 8088 8089 N = pkg.permissionGroups.size(); 8090 r = null; 8091 for (i=0; i<N; i++) { 8092 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8093 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8094 if (cur == null) { 8095 mPermissionGroups.put(pg.info.name, pg); 8096 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8097 if (r == null) { 8098 r = new StringBuilder(256); 8099 } else { 8100 r.append(' '); 8101 } 8102 r.append(pg.info.name); 8103 } 8104 } else { 8105 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8106 + pg.info.packageName + " ignored: original from " 8107 + cur.info.packageName); 8108 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8109 if (r == null) { 8110 r = new StringBuilder(256); 8111 } else { 8112 r.append(' '); 8113 } 8114 r.append("DUP:"); 8115 r.append(pg.info.name); 8116 } 8117 } 8118 } 8119 if (r != null) { 8120 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8121 } 8122 8123 N = pkg.permissions.size(); 8124 r = null; 8125 for (i=0; i<N; i++) { 8126 PackageParser.Permission p = pkg.permissions.get(i); 8127 8128 // Assume by default that we did not install this permission into the system. 8129 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8130 8131 // Now that permission groups have a special meaning, we ignore permission 8132 // groups for legacy apps to prevent unexpected behavior. In particular, 8133 // permissions for one app being granted to someone just becase they happen 8134 // to be in a group defined by another app (before this had no implications). 8135 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8136 p.group = mPermissionGroups.get(p.info.group); 8137 // Warn for a permission in an unknown group. 8138 if (p.info.group != null && p.group == null) { 8139 Slog.w(TAG, "Permission " + p.info.name + " from package " 8140 + p.info.packageName + " in an unknown group " + p.info.group); 8141 } 8142 } 8143 8144 ArrayMap<String, BasePermission> permissionMap = 8145 p.tree ? mSettings.mPermissionTrees 8146 : mSettings.mPermissions; 8147 BasePermission bp = permissionMap.get(p.info.name); 8148 8149 // Allow system apps to redefine non-system permissions 8150 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8151 final boolean currentOwnerIsSystem = (bp.perm != null 8152 && isSystemApp(bp.perm.owner)); 8153 if (isSystemApp(p.owner)) { 8154 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8155 // It's a built-in permission and no owner, take ownership now 8156 bp.packageSetting = pkgSetting; 8157 bp.perm = p; 8158 bp.uid = pkg.applicationInfo.uid; 8159 bp.sourcePackage = p.info.packageName; 8160 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8161 } else if (!currentOwnerIsSystem) { 8162 String msg = "New decl " + p.owner + " of permission " 8163 + p.info.name + " is system; overriding " + bp.sourcePackage; 8164 reportSettingsProblem(Log.WARN, msg); 8165 bp = null; 8166 } 8167 } 8168 } 8169 8170 if (bp == null) { 8171 bp = new BasePermission(p.info.name, p.info.packageName, 8172 BasePermission.TYPE_NORMAL); 8173 permissionMap.put(p.info.name, bp); 8174 } 8175 8176 if (bp.perm == null) { 8177 if (bp.sourcePackage == null 8178 || bp.sourcePackage.equals(p.info.packageName)) { 8179 BasePermission tree = findPermissionTreeLP(p.info.name); 8180 if (tree == null 8181 || tree.sourcePackage.equals(p.info.packageName)) { 8182 bp.packageSetting = pkgSetting; 8183 bp.perm = p; 8184 bp.uid = pkg.applicationInfo.uid; 8185 bp.sourcePackage = p.info.packageName; 8186 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8188 if (r == null) { 8189 r = new StringBuilder(256); 8190 } else { 8191 r.append(' '); 8192 } 8193 r.append(p.info.name); 8194 } 8195 } else { 8196 Slog.w(TAG, "Permission " + p.info.name + " from package " 8197 + p.info.packageName + " ignored: base tree " 8198 + tree.name + " is from package " 8199 + tree.sourcePackage); 8200 } 8201 } else { 8202 Slog.w(TAG, "Permission " + p.info.name + " from package " 8203 + p.info.packageName + " ignored: original from " 8204 + bp.sourcePackage); 8205 } 8206 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8207 if (r == null) { 8208 r = new StringBuilder(256); 8209 } else { 8210 r.append(' '); 8211 } 8212 r.append("DUP:"); 8213 r.append(p.info.name); 8214 } 8215 if (bp.perm == p) { 8216 bp.protectionLevel = p.info.protectionLevel; 8217 } 8218 } 8219 8220 if (r != null) { 8221 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8222 } 8223 8224 N = pkg.instrumentation.size(); 8225 r = null; 8226 for (i=0; i<N; i++) { 8227 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8228 a.info.packageName = pkg.applicationInfo.packageName; 8229 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8230 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8231 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8232 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8233 a.info.dataDir = pkg.applicationInfo.dataDir; 8234 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8235 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8236 8237 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8238 // need other information about the application, like the ABI and what not ? 8239 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8240 mInstrumentation.put(a.getComponentName(), a); 8241 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8242 if (r == null) { 8243 r = new StringBuilder(256); 8244 } else { 8245 r.append(' '); 8246 } 8247 r.append(a.info.name); 8248 } 8249 } 8250 if (r != null) { 8251 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8252 } 8253 8254 if (pkg.protectedBroadcasts != null) { 8255 N = pkg.protectedBroadcasts.size(); 8256 for (i=0; i<N; i++) { 8257 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8258 } 8259 } 8260 8261 pkgSetting.setTimeStamp(scanFileTime); 8262 8263 // Create idmap files for pairs of (packages, overlay packages). 8264 // Note: "android", ie framework-res.apk, is handled by native layers. 8265 if (pkg.mOverlayTarget != null) { 8266 // This is an overlay package. 8267 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8268 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8269 mOverlays.put(pkg.mOverlayTarget, 8270 new ArrayMap<String, PackageParser.Package>()); 8271 } 8272 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8273 map.put(pkg.packageName, pkg); 8274 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8275 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8276 createIdmapFailed = true; 8277 } 8278 } 8279 } else if (mOverlays.containsKey(pkg.packageName) && 8280 !pkg.packageName.equals("android")) { 8281 // This is a regular package, with one or more known overlay packages. 8282 createIdmapsForPackageLI(pkg); 8283 } 8284 } 8285 8286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8287 8288 if (createIdmapFailed) { 8289 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8290 "scanPackageLI failed to createIdmap"); 8291 } 8292 return pkg; 8293 } 8294 8295 /** 8296 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8297 * is derived purely on the basis of the contents of {@code scanFile} and 8298 * {@code cpuAbiOverride}. 8299 * 8300 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8301 */ 8302 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8303 String cpuAbiOverride, boolean extractLibs) 8304 throws PackageManagerException { 8305 // TODO: We can probably be smarter about this stuff. For installed apps, 8306 // we can calculate this information at install time once and for all. For 8307 // system apps, we can probably assume that this information doesn't change 8308 // after the first boot scan. As things stand, we do lots of unnecessary work. 8309 8310 // Give ourselves some initial paths; we'll come back for another 8311 // pass once we've determined ABI below. 8312 setNativeLibraryPaths(pkg); 8313 8314 // We would never need to extract libs for forward-locked and external packages, 8315 // since the container service will do it for us. We shouldn't attempt to 8316 // extract libs from system app when it was not updated. 8317 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8318 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8319 extractLibs = false; 8320 } 8321 8322 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8323 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8324 8325 NativeLibraryHelper.Handle handle = null; 8326 try { 8327 handle = NativeLibraryHelper.Handle.create(pkg); 8328 // TODO(multiArch): This can be null for apps that didn't go through the 8329 // usual installation process. We can calculate it again, like we 8330 // do during install time. 8331 // 8332 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8333 // unnecessary. 8334 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8335 8336 // Null out the abis so that they can be recalculated. 8337 pkg.applicationInfo.primaryCpuAbi = null; 8338 pkg.applicationInfo.secondaryCpuAbi = null; 8339 if (isMultiArch(pkg.applicationInfo)) { 8340 // Warn if we've set an abiOverride for multi-lib packages.. 8341 // By definition, we need to copy both 32 and 64 bit libraries for 8342 // such packages. 8343 if (pkg.cpuAbiOverride != null 8344 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8345 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8346 } 8347 8348 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8349 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8350 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8351 if (extractLibs) { 8352 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8353 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8354 useIsaSpecificSubdirs); 8355 } else { 8356 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8357 } 8358 } 8359 8360 maybeThrowExceptionForMultiArchCopy( 8361 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8362 8363 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8364 if (extractLibs) { 8365 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8366 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8367 useIsaSpecificSubdirs); 8368 } else { 8369 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8370 } 8371 } 8372 8373 maybeThrowExceptionForMultiArchCopy( 8374 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8375 8376 if (abi64 >= 0) { 8377 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8378 } 8379 8380 if (abi32 >= 0) { 8381 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8382 if (abi64 >= 0) { 8383 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8384 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8385 pkg.applicationInfo.primaryCpuAbi = abi; 8386 } else { 8387 pkg.applicationInfo.secondaryCpuAbi = abi; 8388 } 8389 } else { 8390 pkg.applicationInfo.primaryCpuAbi = abi; 8391 } 8392 } 8393 8394 } else { 8395 String[] abiList = (cpuAbiOverride != null) ? 8396 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8397 8398 // Enable gross and lame hacks for apps that are built with old 8399 // SDK tools. We must scan their APKs for renderscript bitcode and 8400 // not launch them if it's present. Don't bother checking on devices 8401 // that don't have 64 bit support. 8402 boolean needsRenderScriptOverride = false; 8403 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8404 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8405 abiList = Build.SUPPORTED_32_BIT_ABIS; 8406 needsRenderScriptOverride = true; 8407 } 8408 8409 final int copyRet; 8410 if (extractLibs) { 8411 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8412 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8413 } else { 8414 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8415 } 8416 8417 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8418 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8419 "Error unpackaging native libs for app, errorCode=" + copyRet); 8420 } 8421 8422 if (copyRet >= 0) { 8423 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8424 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8425 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8426 } else if (needsRenderScriptOverride) { 8427 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8428 } 8429 } 8430 } catch (IOException ioe) { 8431 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8432 } finally { 8433 IoUtils.closeQuietly(handle); 8434 } 8435 8436 // Now that we've calculated the ABIs and determined if it's an internal app, 8437 // we will go ahead and populate the nativeLibraryPath. 8438 setNativeLibraryPaths(pkg); 8439 } 8440 8441 /** 8442 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8443 * i.e, so that all packages can be run inside a single process if required. 8444 * 8445 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8446 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8447 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8448 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8449 * updating a package that belongs to a shared user. 8450 * 8451 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8452 * adds unnecessary complexity. 8453 */ 8454 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8455 PackageParser.Package scannedPackage, boolean bootComplete) { 8456 String requiredInstructionSet = null; 8457 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8458 requiredInstructionSet = VMRuntime.getInstructionSet( 8459 scannedPackage.applicationInfo.primaryCpuAbi); 8460 } 8461 8462 PackageSetting requirer = null; 8463 for (PackageSetting ps : packagesForUser) { 8464 // If packagesForUser contains scannedPackage, we skip it. This will happen 8465 // when scannedPackage is an update of an existing package. Without this check, 8466 // we will never be able to change the ABI of any package belonging to a shared 8467 // user, even if it's compatible with other packages. 8468 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8469 if (ps.primaryCpuAbiString == null) { 8470 continue; 8471 } 8472 8473 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8474 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8475 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8476 // this but there's not much we can do. 8477 String errorMessage = "Instruction set mismatch, " 8478 + ((requirer == null) ? "[caller]" : requirer) 8479 + " requires " + requiredInstructionSet + " whereas " + ps 8480 + " requires " + instructionSet; 8481 Slog.w(TAG, errorMessage); 8482 } 8483 8484 if (requiredInstructionSet == null) { 8485 requiredInstructionSet = instructionSet; 8486 requirer = ps; 8487 } 8488 } 8489 } 8490 8491 if (requiredInstructionSet != null) { 8492 String adjustedAbi; 8493 if (requirer != null) { 8494 // requirer != null implies that either scannedPackage was null or that scannedPackage 8495 // did not require an ABI, in which case we have to adjust scannedPackage to match 8496 // the ABI of the set (which is the same as requirer's ABI) 8497 adjustedAbi = requirer.primaryCpuAbiString; 8498 if (scannedPackage != null) { 8499 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8500 } 8501 } else { 8502 // requirer == null implies that we're updating all ABIs in the set to 8503 // match scannedPackage. 8504 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8505 } 8506 8507 for (PackageSetting ps : packagesForUser) { 8508 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8509 if (ps.primaryCpuAbiString != null) { 8510 continue; 8511 } 8512 8513 ps.primaryCpuAbiString = adjustedAbi; 8514 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8515 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8516 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8517 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8518 + " (requirer=" 8519 + (requirer == null ? "null" : requirer.pkg.packageName) 8520 + ", scannedPackage=" 8521 + (scannedPackage != null ? scannedPackage.packageName : "null") 8522 + ")"); 8523 try { 8524 mInstaller.rmdex(ps.codePathString, 8525 getDexCodeInstructionSet(getPreferredInstructionSet())); 8526 } catch (InstallerException ignored) { 8527 } 8528 } 8529 } 8530 } 8531 } 8532 } 8533 8534 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8535 synchronized (mPackages) { 8536 mResolverReplaced = true; 8537 // Set up information for custom user intent resolution activity. 8538 mResolveActivity.applicationInfo = pkg.applicationInfo; 8539 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8540 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8541 mResolveActivity.processName = pkg.applicationInfo.packageName; 8542 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8543 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8544 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8545 mResolveActivity.theme = 0; 8546 mResolveActivity.exported = true; 8547 mResolveActivity.enabled = true; 8548 mResolveInfo.activityInfo = mResolveActivity; 8549 mResolveInfo.priority = 0; 8550 mResolveInfo.preferredOrder = 0; 8551 mResolveInfo.match = 0; 8552 mResolveComponentName = mCustomResolverComponentName; 8553 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8554 mResolveComponentName); 8555 } 8556 } 8557 8558 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8559 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8560 8561 // Set up information for ephemeral installer activity 8562 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8563 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8564 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8565 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8566 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8567 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8568 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8569 mEphemeralInstallerActivity.theme = 0; 8570 mEphemeralInstallerActivity.exported = true; 8571 mEphemeralInstallerActivity.enabled = true; 8572 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8573 mEphemeralInstallerInfo.priority = 0; 8574 mEphemeralInstallerInfo.preferredOrder = 0; 8575 mEphemeralInstallerInfo.match = 0; 8576 8577 if (DEBUG_EPHEMERAL) { 8578 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8579 } 8580 } 8581 8582 private static String calculateBundledApkRoot(final String codePathString) { 8583 final File codePath = new File(codePathString); 8584 final File codeRoot; 8585 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8586 codeRoot = Environment.getRootDirectory(); 8587 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8588 codeRoot = Environment.getOemDirectory(); 8589 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8590 codeRoot = Environment.getVendorDirectory(); 8591 } else { 8592 // Unrecognized code path; take its top real segment as the apk root: 8593 // e.g. /something/app/blah.apk => /something 8594 try { 8595 File f = codePath.getCanonicalFile(); 8596 File parent = f.getParentFile(); // non-null because codePath is a file 8597 File tmp; 8598 while ((tmp = parent.getParentFile()) != null) { 8599 f = parent; 8600 parent = tmp; 8601 } 8602 codeRoot = f; 8603 Slog.w(TAG, "Unrecognized code path " 8604 + codePath + " - using " + codeRoot); 8605 } catch (IOException e) { 8606 // Can't canonicalize the code path -- shenanigans? 8607 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8608 return Environment.getRootDirectory().getPath(); 8609 } 8610 } 8611 return codeRoot.getPath(); 8612 } 8613 8614 /** 8615 * Derive and set the location of native libraries for the given package, 8616 * which varies depending on where and how the package was installed. 8617 */ 8618 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8619 final ApplicationInfo info = pkg.applicationInfo; 8620 final String codePath = pkg.codePath; 8621 final File codeFile = new File(codePath); 8622 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8623 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8624 8625 info.nativeLibraryRootDir = null; 8626 info.nativeLibraryRootRequiresIsa = false; 8627 info.nativeLibraryDir = null; 8628 info.secondaryNativeLibraryDir = null; 8629 8630 if (isApkFile(codeFile)) { 8631 // Monolithic install 8632 if (bundledApp) { 8633 // If "/system/lib64/apkname" exists, assume that is the per-package 8634 // native library directory to use; otherwise use "/system/lib/apkname". 8635 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8636 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8637 getPrimaryInstructionSet(info)); 8638 8639 // This is a bundled system app so choose the path based on the ABI. 8640 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8641 // is just the default path. 8642 final String apkName = deriveCodePathName(codePath); 8643 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8644 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8645 apkName).getAbsolutePath(); 8646 8647 if (info.secondaryCpuAbi != null) { 8648 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8649 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8650 secondaryLibDir, apkName).getAbsolutePath(); 8651 } 8652 } else if (asecApp) { 8653 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8654 .getAbsolutePath(); 8655 } else { 8656 final String apkName = deriveCodePathName(codePath); 8657 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8658 .getAbsolutePath(); 8659 } 8660 8661 info.nativeLibraryRootRequiresIsa = false; 8662 info.nativeLibraryDir = info.nativeLibraryRootDir; 8663 } else { 8664 // Cluster install 8665 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8666 info.nativeLibraryRootRequiresIsa = true; 8667 8668 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8669 getPrimaryInstructionSet(info)).getAbsolutePath(); 8670 8671 if (info.secondaryCpuAbi != null) { 8672 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8673 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8674 } 8675 } 8676 } 8677 8678 /** 8679 * Calculate the abis and roots for a bundled app. These can uniquely 8680 * be determined from the contents of the system partition, i.e whether 8681 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8682 * of this information, and instead assume that the system was built 8683 * sensibly. 8684 */ 8685 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8686 PackageSetting pkgSetting) { 8687 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8688 8689 // If "/system/lib64/apkname" exists, assume that is the per-package 8690 // native library directory to use; otherwise use "/system/lib/apkname". 8691 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8692 setBundledAppAbi(pkg, apkRoot, apkName); 8693 // pkgSetting might be null during rescan following uninstall of updates 8694 // to a bundled app, so accommodate that possibility. The settings in 8695 // that case will be established later from the parsed package. 8696 // 8697 // If the settings aren't null, sync them up with what we've just derived. 8698 // note that apkRoot isn't stored in the package settings. 8699 if (pkgSetting != null) { 8700 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8701 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8702 } 8703 } 8704 8705 /** 8706 * Deduces the ABI of a bundled app and sets the relevant fields on the 8707 * parsed pkg object. 8708 * 8709 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8710 * under which system libraries are installed. 8711 * @param apkName the name of the installed package. 8712 */ 8713 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8714 final File codeFile = new File(pkg.codePath); 8715 8716 final boolean has64BitLibs; 8717 final boolean has32BitLibs; 8718 if (isApkFile(codeFile)) { 8719 // Monolithic install 8720 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8721 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8722 } else { 8723 // Cluster install 8724 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8725 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8726 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8727 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8728 has64BitLibs = (new File(rootDir, isa)).exists(); 8729 } else { 8730 has64BitLibs = false; 8731 } 8732 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8733 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8734 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8735 has32BitLibs = (new File(rootDir, isa)).exists(); 8736 } else { 8737 has32BitLibs = false; 8738 } 8739 } 8740 8741 if (has64BitLibs && !has32BitLibs) { 8742 // The package has 64 bit libs, but not 32 bit libs. Its primary 8743 // ABI should be 64 bit. We can safely assume here that the bundled 8744 // native libraries correspond to the most preferred ABI in the list. 8745 8746 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8747 pkg.applicationInfo.secondaryCpuAbi = null; 8748 } else if (has32BitLibs && !has64BitLibs) { 8749 // The package has 32 bit libs but not 64 bit libs. Its primary 8750 // ABI should be 32 bit. 8751 8752 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8753 pkg.applicationInfo.secondaryCpuAbi = null; 8754 } else if (has32BitLibs && has64BitLibs) { 8755 // The application has both 64 and 32 bit bundled libraries. We check 8756 // here that the app declares multiArch support, and warn if it doesn't. 8757 // 8758 // We will be lenient here and record both ABIs. The primary will be the 8759 // ABI that's higher on the list, i.e, a device that's configured to prefer 8760 // 64 bit apps will see a 64 bit primary ABI, 8761 8762 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8763 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8764 } 8765 8766 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8767 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8768 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8769 } else { 8770 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8771 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8772 } 8773 } else { 8774 pkg.applicationInfo.primaryCpuAbi = null; 8775 pkg.applicationInfo.secondaryCpuAbi = null; 8776 } 8777 } 8778 8779 private void killPackage(PackageParser.Package pkg, String reason) { 8780 // Kill the parent package 8781 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8782 // Kill the child packages 8783 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8784 for (int i = 0; i < childCount; i++) { 8785 PackageParser.Package childPkg = pkg.childPackages.get(i); 8786 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8787 } 8788 } 8789 8790 private void killApplication(String pkgName, int appId, String reason) { 8791 // Request the ActivityManager to kill the process(only for existing packages) 8792 // so that we do not end up in a confused state while the user is still using the older 8793 // version of the application while the new one gets installed. 8794 IActivityManager am = ActivityManagerNative.getDefault(); 8795 if (am != null) { 8796 try { 8797 am.killApplicationWithAppId(pkgName, appId, reason); 8798 } catch (RemoteException e) { 8799 } 8800 } 8801 } 8802 8803 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8804 // Remove the parent package setting 8805 PackageSetting ps = (PackageSetting) pkg.mExtras; 8806 if (ps != null) { 8807 removePackageLI(ps, chatty); 8808 } 8809 // Remove the child package setting 8810 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8811 for (int i = 0; i < childCount; i++) { 8812 PackageParser.Package childPkg = pkg.childPackages.get(i); 8813 ps = (PackageSetting) childPkg.mExtras; 8814 if (ps != null) { 8815 removePackageLI(ps, chatty); 8816 } 8817 } 8818 } 8819 8820 void removePackageLI(PackageSetting ps, boolean chatty) { 8821 if (DEBUG_INSTALL) { 8822 if (chatty) 8823 Log.d(TAG, "Removing package " + ps.name); 8824 } 8825 8826 // writer 8827 synchronized (mPackages) { 8828 mPackages.remove(ps.name); 8829 final PackageParser.Package pkg = ps.pkg; 8830 if (pkg != null) { 8831 cleanPackageDataStructuresLILPw(pkg, chatty); 8832 } 8833 } 8834 } 8835 8836 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8837 if (DEBUG_INSTALL) { 8838 if (chatty) 8839 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8840 } 8841 8842 // writer 8843 synchronized (mPackages) { 8844 // Remove the parent package 8845 mPackages.remove(pkg.applicationInfo.packageName); 8846 cleanPackageDataStructuresLILPw(pkg, chatty); 8847 8848 // Remove the child packages 8849 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8850 for (int i = 0; i < childCount; i++) { 8851 PackageParser.Package childPkg = pkg.childPackages.get(i); 8852 mPackages.remove(childPkg.applicationInfo.packageName); 8853 cleanPackageDataStructuresLILPw(childPkg, chatty); 8854 } 8855 } 8856 } 8857 8858 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8859 int N = pkg.providers.size(); 8860 StringBuilder r = null; 8861 int i; 8862 for (i=0; i<N; i++) { 8863 PackageParser.Provider p = pkg.providers.get(i); 8864 mProviders.removeProvider(p); 8865 if (p.info.authority == null) { 8866 8867 /* There was another ContentProvider with this authority when 8868 * this app was installed so this authority is null, 8869 * Ignore it as we don't have to unregister the provider. 8870 */ 8871 continue; 8872 } 8873 String names[] = p.info.authority.split(";"); 8874 for (int j = 0; j < names.length; j++) { 8875 if (mProvidersByAuthority.get(names[j]) == p) { 8876 mProvidersByAuthority.remove(names[j]); 8877 if (DEBUG_REMOVE) { 8878 if (chatty) 8879 Log.d(TAG, "Unregistered content provider: " + names[j] 8880 + ", className = " + p.info.name + ", isSyncable = " 8881 + p.info.isSyncable); 8882 } 8883 } 8884 } 8885 if (DEBUG_REMOVE && chatty) { 8886 if (r == null) { 8887 r = new StringBuilder(256); 8888 } else { 8889 r.append(' '); 8890 } 8891 r.append(p.info.name); 8892 } 8893 } 8894 if (r != null) { 8895 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8896 } 8897 8898 N = pkg.services.size(); 8899 r = null; 8900 for (i=0; i<N; i++) { 8901 PackageParser.Service s = pkg.services.get(i); 8902 mServices.removeService(s); 8903 if (chatty) { 8904 if (r == null) { 8905 r = new StringBuilder(256); 8906 } else { 8907 r.append(' '); 8908 } 8909 r.append(s.info.name); 8910 } 8911 } 8912 if (r != null) { 8913 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8914 } 8915 8916 N = pkg.receivers.size(); 8917 r = null; 8918 for (i=0; i<N; i++) { 8919 PackageParser.Activity a = pkg.receivers.get(i); 8920 mReceivers.removeActivity(a, "receiver"); 8921 if (DEBUG_REMOVE && chatty) { 8922 if (r == null) { 8923 r = new StringBuilder(256); 8924 } else { 8925 r.append(' '); 8926 } 8927 r.append(a.info.name); 8928 } 8929 } 8930 if (r != null) { 8931 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8932 } 8933 8934 N = pkg.activities.size(); 8935 r = null; 8936 for (i=0; i<N; i++) { 8937 PackageParser.Activity a = pkg.activities.get(i); 8938 mActivities.removeActivity(a, "activity"); 8939 if (DEBUG_REMOVE && chatty) { 8940 if (r == null) { 8941 r = new StringBuilder(256); 8942 } else { 8943 r.append(' '); 8944 } 8945 r.append(a.info.name); 8946 } 8947 } 8948 if (r != null) { 8949 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8950 } 8951 8952 N = pkg.permissions.size(); 8953 r = null; 8954 for (i=0; i<N; i++) { 8955 PackageParser.Permission p = pkg.permissions.get(i); 8956 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8957 if (bp == null) { 8958 bp = mSettings.mPermissionTrees.get(p.info.name); 8959 } 8960 if (bp != null && bp.perm == p) { 8961 bp.perm = null; 8962 if (DEBUG_REMOVE && chatty) { 8963 if (r == null) { 8964 r = new StringBuilder(256); 8965 } else { 8966 r.append(' '); 8967 } 8968 r.append(p.info.name); 8969 } 8970 } 8971 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8972 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8973 if (appOpPkgs != null) { 8974 appOpPkgs.remove(pkg.packageName); 8975 } 8976 } 8977 } 8978 if (r != null) { 8979 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8980 } 8981 8982 N = pkg.requestedPermissions.size(); 8983 r = null; 8984 for (i=0; i<N; i++) { 8985 String perm = pkg.requestedPermissions.get(i); 8986 BasePermission bp = mSettings.mPermissions.get(perm); 8987 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8988 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8989 if (appOpPkgs != null) { 8990 appOpPkgs.remove(pkg.packageName); 8991 if (appOpPkgs.isEmpty()) { 8992 mAppOpPermissionPackages.remove(perm); 8993 } 8994 } 8995 } 8996 } 8997 if (r != null) { 8998 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8999 } 9000 9001 N = pkg.instrumentation.size(); 9002 r = null; 9003 for (i=0; i<N; i++) { 9004 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9005 mInstrumentation.remove(a.getComponentName()); 9006 if (DEBUG_REMOVE && chatty) { 9007 if (r == null) { 9008 r = new StringBuilder(256); 9009 } else { 9010 r.append(' '); 9011 } 9012 r.append(a.info.name); 9013 } 9014 } 9015 if (r != null) { 9016 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9017 } 9018 9019 r = null; 9020 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9021 // Only system apps can hold shared libraries. 9022 if (pkg.libraryNames != null) { 9023 for (i=0; i<pkg.libraryNames.size(); i++) { 9024 String name = pkg.libraryNames.get(i); 9025 SharedLibraryEntry cur = mSharedLibraries.get(name); 9026 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9027 mSharedLibraries.remove(name); 9028 if (DEBUG_REMOVE && chatty) { 9029 if (r == null) { 9030 r = new StringBuilder(256); 9031 } else { 9032 r.append(' '); 9033 } 9034 r.append(name); 9035 } 9036 } 9037 } 9038 } 9039 } 9040 if (r != null) { 9041 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9042 } 9043 } 9044 9045 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9046 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9047 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9048 return true; 9049 } 9050 } 9051 return false; 9052 } 9053 9054 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9055 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9056 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9057 9058 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9059 // Update the parent permissions 9060 updatePermissionsLPw(pkg.packageName, pkg, flags); 9061 // Update the child permissions 9062 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9063 for (int i = 0; i < childCount; i++) { 9064 PackageParser.Package childPkg = pkg.childPackages.get(i); 9065 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9066 } 9067 } 9068 9069 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9070 int flags) { 9071 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9072 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9073 } 9074 9075 private void updatePermissionsLPw(String changingPkg, 9076 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9077 // Make sure there are no dangling permission trees. 9078 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9079 while (it.hasNext()) { 9080 final BasePermission bp = it.next(); 9081 if (bp.packageSetting == null) { 9082 // We may not yet have parsed the package, so just see if 9083 // we still know about its settings. 9084 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9085 } 9086 if (bp.packageSetting == null) { 9087 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9088 + " from package " + bp.sourcePackage); 9089 it.remove(); 9090 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9091 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9092 Slog.i(TAG, "Removing old permission tree: " + bp.name 9093 + " from package " + bp.sourcePackage); 9094 flags |= UPDATE_PERMISSIONS_ALL; 9095 it.remove(); 9096 } 9097 } 9098 } 9099 9100 // Make sure all dynamic permissions have been assigned to a package, 9101 // and make sure there are no dangling permissions. 9102 it = mSettings.mPermissions.values().iterator(); 9103 while (it.hasNext()) { 9104 final BasePermission bp = it.next(); 9105 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9106 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9107 + bp.name + " pkg=" + bp.sourcePackage 9108 + " info=" + bp.pendingInfo); 9109 if (bp.packageSetting == null && bp.pendingInfo != null) { 9110 final BasePermission tree = findPermissionTreeLP(bp.name); 9111 if (tree != null && tree.perm != null) { 9112 bp.packageSetting = tree.packageSetting; 9113 bp.perm = new PackageParser.Permission(tree.perm.owner, 9114 new PermissionInfo(bp.pendingInfo)); 9115 bp.perm.info.packageName = tree.perm.info.packageName; 9116 bp.perm.info.name = bp.name; 9117 bp.uid = tree.uid; 9118 } 9119 } 9120 } 9121 if (bp.packageSetting == null) { 9122 // We may not yet have parsed the package, so just see if 9123 // we still know about its settings. 9124 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9125 } 9126 if (bp.packageSetting == null) { 9127 Slog.w(TAG, "Removing dangling permission: " + bp.name 9128 + " from package " + bp.sourcePackage); 9129 it.remove(); 9130 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9131 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9132 Slog.i(TAG, "Removing old permission: " + bp.name 9133 + " from package " + bp.sourcePackage); 9134 flags |= UPDATE_PERMISSIONS_ALL; 9135 it.remove(); 9136 } 9137 } 9138 } 9139 9140 // Now update the permissions for all packages, in particular 9141 // replace the granted permissions of the system packages. 9142 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9143 for (PackageParser.Package pkg : mPackages.values()) { 9144 if (pkg != pkgInfo) { 9145 // Only replace for packages on requested volume 9146 final String volumeUuid = getVolumeUuidForPackage(pkg); 9147 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9148 && Objects.equals(replaceVolumeUuid, volumeUuid); 9149 grantPermissionsLPw(pkg, replace, changingPkg); 9150 } 9151 } 9152 } 9153 9154 if (pkgInfo != null) { 9155 // Only replace for packages on requested volume 9156 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9157 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9158 && Objects.equals(replaceVolumeUuid, volumeUuid); 9159 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9160 } 9161 } 9162 9163 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9164 String packageOfInterest) { 9165 // IMPORTANT: There are two types of permissions: install and runtime. 9166 // Install time permissions are granted when the app is installed to 9167 // all device users and users added in the future. Runtime permissions 9168 // are granted at runtime explicitly to specific users. Normal and signature 9169 // protected permissions are install time permissions. Dangerous permissions 9170 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9171 // otherwise they are runtime permissions. This function does not manage 9172 // runtime permissions except for the case an app targeting Lollipop MR1 9173 // being upgraded to target a newer SDK, in which case dangerous permissions 9174 // are transformed from install time to runtime ones. 9175 9176 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9177 if (ps == null) { 9178 return; 9179 } 9180 9181 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9182 9183 PermissionsState permissionsState = ps.getPermissionsState(); 9184 PermissionsState origPermissions = permissionsState; 9185 9186 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9187 9188 boolean runtimePermissionsRevoked = false; 9189 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9190 9191 boolean changedInstallPermission = false; 9192 9193 if (replace) { 9194 ps.installPermissionsFixed = false; 9195 if (!ps.isSharedUser()) { 9196 origPermissions = new PermissionsState(permissionsState); 9197 permissionsState.reset(); 9198 } else { 9199 // We need to know only about runtime permission changes since the 9200 // calling code always writes the install permissions state but 9201 // the runtime ones are written only if changed. The only cases of 9202 // changed runtime permissions here are promotion of an install to 9203 // runtime and revocation of a runtime from a shared user. 9204 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9205 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9206 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9207 runtimePermissionsRevoked = true; 9208 } 9209 } 9210 } 9211 9212 permissionsState.setGlobalGids(mGlobalGids); 9213 9214 final int N = pkg.requestedPermissions.size(); 9215 for (int i=0; i<N; i++) { 9216 final String name = pkg.requestedPermissions.get(i); 9217 final BasePermission bp = mSettings.mPermissions.get(name); 9218 9219 if (DEBUG_INSTALL) { 9220 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9221 } 9222 9223 if (bp == null || bp.packageSetting == null) { 9224 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9225 Slog.w(TAG, "Unknown permission " + name 9226 + " in package " + pkg.packageName); 9227 } 9228 continue; 9229 } 9230 9231 final String perm = bp.name; 9232 boolean allowedSig = false; 9233 int grant = GRANT_DENIED; 9234 9235 // Keep track of app op permissions. 9236 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9237 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9238 if (pkgs == null) { 9239 pkgs = new ArraySet<>(); 9240 mAppOpPermissionPackages.put(bp.name, pkgs); 9241 } 9242 pkgs.add(pkg.packageName); 9243 } 9244 9245 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9246 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9247 >= Build.VERSION_CODES.M; 9248 switch (level) { 9249 case PermissionInfo.PROTECTION_NORMAL: { 9250 // For all apps normal permissions are install time ones. 9251 grant = GRANT_INSTALL; 9252 } break; 9253 9254 case PermissionInfo.PROTECTION_DANGEROUS: { 9255 // If a permission review is required for legacy apps we represent 9256 // their permissions as always granted runtime ones since we need 9257 // to keep the review required permission flag per user while an 9258 // install permission's state is shared across all users. 9259 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9260 // For legacy apps dangerous permissions are install time ones. 9261 grant = GRANT_INSTALL; 9262 } else if (origPermissions.hasInstallPermission(bp.name)) { 9263 // For legacy apps that became modern, install becomes runtime. 9264 grant = GRANT_UPGRADE; 9265 } else if (mPromoteSystemApps 9266 && isSystemApp(ps) 9267 && mExistingSystemPackages.contains(ps.name)) { 9268 // For legacy system apps, install becomes runtime. 9269 // We cannot check hasInstallPermission() for system apps since those 9270 // permissions were granted implicitly and not persisted pre-M. 9271 grant = GRANT_UPGRADE; 9272 } else { 9273 // For modern apps keep runtime permissions unchanged. 9274 grant = GRANT_RUNTIME; 9275 } 9276 } break; 9277 9278 case PermissionInfo.PROTECTION_SIGNATURE: { 9279 // For all apps signature permissions are install time ones. 9280 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9281 if (allowedSig) { 9282 grant = GRANT_INSTALL; 9283 } 9284 } break; 9285 } 9286 9287 if (DEBUG_INSTALL) { 9288 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9289 } 9290 9291 if (grant != GRANT_DENIED) { 9292 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9293 // If this is an existing, non-system package, then 9294 // we can't add any new permissions to it. 9295 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9296 // Except... if this is a permission that was added 9297 // to the platform (note: need to only do this when 9298 // updating the platform). 9299 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9300 grant = GRANT_DENIED; 9301 } 9302 } 9303 } 9304 9305 switch (grant) { 9306 case GRANT_INSTALL: { 9307 // Revoke this as runtime permission to handle the case of 9308 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9309 for (int userId : UserManagerService.getInstance().getUserIds()) { 9310 if (origPermissions.getRuntimePermissionState( 9311 bp.name, userId) != null) { 9312 // Revoke the runtime permission and clear the flags. 9313 origPermissions.revokeRuntimePermission(bp, userId); 9314 origPermissions.updatePermissionFlags(bp, userId, 9315 PackageManager.MASK_PERMISSION_FLAGS, 0); 9316 // If we revoked a permission permission, we have to write. 9317 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9318 changedRuntimePermissionUserIds, userId); 9319 } 9320 } 9321 // Grant an install permission. 9322 if (permissionsState.grantInstallPermission(bp) != 9323 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9324 changedInstallPermission = true; 9325 } 9326 } break; 9327 9328 case GRANT_RUNTIME: { 9329 // Grant previously granted runtime permissions. 9330 for (int userId : UserManagerService.getInstance().getUserIds()) { 9331 PermissionState permissionState = origPermissions 9332 .getRuntimePermissionState(bp.name, userId); 9333 int flags = permissionState != null 9334 ? permissionState.getFlags() : 0; 9335 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9336 if (permissionsState.grantRuntimePermission(bp, userId) == 9337 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9338 // If we cannot put the permission as it was, we have to write. 9339 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9340 changedRuntimePermissionUserIds, userId); 9341 } 9342 // If the app supports runtime permissions no need for a review. 9343 if (Build.PERMISSIONS_REVIEW_REQUIRED 9344 && appSupportsRuntimePermissions 9345 && (flags & PackageManager 9346 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9347 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9348 // Since we changed the flags, we have to write. 9349 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9350 changedRuntimePermissionUserIds, userId); 9351 } 9352 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9353 && !appSupportsRuntimePermissions) { 9354 // For legacy apps that need a permission review, every new 9355 // runtime permission is granted but it is pending a review. 9356 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9357 permissionsState.grantRuntimePermission(bp, userId); 9358 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9359 // We changed the permission and flags, hence have to write. 9360 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9361 changedRuntimePermissionUserIds, userId); 9362 } 9363 } 9364 // Propagate the permission flags. 9365 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9366 } 9367 } break; 9368 9369 case GRANT_UPGRADE: { 9370 // Grant runtime permissions for a previously held install permission. 9371 PermissionState permissionState = origPermissions 9372 .getInstallPermissionState(bp.name); 9373 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9374 9375 if (origPermissions.revokeInstallPermission(bp) 9376 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9377 // We will be transferring the permission flags, so clear them. 9378 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9379 PackageManager.MASK_PERMISSION_FLAGS, 0); 9380 changedInstallPermission = true; 9381 } 9382 9383 // If the permission is not to be promoted to runtime we ignore it and 9384 // also its other flags as they are not applicable to install permissions. 9385 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9386 for (int userId : currentUserIds) { 9387 if (permissionsState.grantRuntimePermission(bp, userId) != 9388 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9389 // Transfer the permission flags. 9390 permissionsState.updatePermissionFlags(bp, userId, 9391 flags, flags); 9392 // If we granted the permission, we have to write. 9393 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9394 changedRuntimePermissionUserIds, userId); 9395 } 9396 } 9397 } 9398 } break; 9399 9400 default: { 9401 if (packageOfInterest == null 9402 || packageOfInterest.equals(pkg.packageName)) { 9403 Slog.w(TAG, "Not granting permission " + perm 9404 + " to package " + pkg.packageName 9405 + " because it was previously installed without"); 9406 } 9407 } break; 9408 } 9409 } else { 9410 if (permissionsState.revokeInstallPermission(bp) != 9411 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9412 // Also drop the permission flags. 9413 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9414 PackageManager.MASK_PERMISSION_FLAGS, 0); 9415 changedInstallPermission = true; 9416 Slog.i(TAG, "Un-granting permission " + perm 9417 + " from package " + pkg.packageName 9418 + " (protectionLevel=" + bp.protectionLevel 9419 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9420 + ")"); 9421 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9422 // Don't print warning for app op permissions, since it is fine for them 9423 // not to be granted, there is a UI for the user to decide. 9424 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9425 Slog.w(TAG, "Not granting permission " + perm 9426 + " to package " + pkg.packageName 9427 + " (protectionLevel=" + bp.protectionLevel 9428 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9429 + ")"); 9430 } 9431 } 9432 } 9433 } 9434 9435 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9436 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9437 // This is the first that we have heard about this package, so the 9438 // permissions we have now selected are fixed until explicitly 9439 // changed. 9440 ps.installPermissionsFixed = true; 9441 } 9442 9443 // Persist the runtime permissions state for users with changes. If permissions 9444 // were revoked because no app in the shared user declares them we have to 9445 // write synchronously to avoid losing runtime permissions state. 9446 for (int userId : changedRuntimePermissionUserIds) { 9447 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9448 } 9449 9450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9451 } 9452 9453 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9454 boolean allowed = false; 9455 final int NP = PackageParser.NEW_PERMISSIONS.length; 9456 for (int ip=0; ip<NP; ip++) { 9457 final PackageParser.NewPermissionInfo npi 9458 = PackageParser.NEW_PERMISSIONS[ip]; 9459 if (npi.name.equals(perm) 9460 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9461 allowed = true; 9462 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9463 + pkg.packageName); 9464 break; 9465 } 9466 } 9467 return allowed; 9468 } 9469 9470 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9471 BasePermission bp, PermissionsState origPermissions) { 9472 boolean allowed; 9473 allowed = (compareSignatures( 9474 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9475 == PackageManager.SIGNATURE_MATCH) 9476 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9477 == PackageManager.SIGNATURE_MATCH); 9478 if (!allowed && (bp.protectionLevel 9479 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9480 if (isSystemApp(pkg)) { 9481 // For updated system applications, a system permission 9482 // is granted only if it had been defined by the original application. 9483 if (pkg.isUpdatedSystemApp()) { 9484 final PackageSetting sysPs = mSettings 9485 .getDisabledSystemPkgLPr(pkg.packageName); 9486 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9487 // If the original was granted this permission, we take 9488 // that grant decision as read and propagate it to the 9489 // update. 9490 if (sysPs.isPrivileged()) { 9491 allowed = true; 9492 } 9493 } else { 9494 // The system apk may have been updated with an older 9495 // version of the one on the data partition, but which 9496 // granted a new system permission that it didn't have 9497 // before. In this case we do want to allow the app to 9498 // now get the new permission if the ancestral apk is 9499 // privileged to get it. 9500 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9501 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9502 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9503 allowed = true; 9504 break; 9505 } 9506 } 9507 } 9508 // Also if a privileged parent package on the system image or any of 9509 // its children requested a privileged permission, the updated child 9510 // packages can also get the permission. 9511 if (pkg.parentPackage != null) { 9512 final PackageSetting disabledSysParentPs = mSettings 9513 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9514 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9515 && disabledSysParentPs.isPrivileged()) { 9516 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9517 allowed = true; 9518 } else if (disabledSysParentPs.pkg.childPackages != null) { 9519 final int count = disabledSysParentPs.pkg.childPackages.size(); 9520 for (int i = 0; i < count; i++) { 9521 PackageParser.Package disabledSysChildPkg = 9522 disabledSysParentPs.pkg.childPackages.get(i); 9523 if (isPackageRequestingPermission(disabledSysChildPkg, 9524 perm)) { 9525 allowed = true; 9526 break; 9527 } 9528 } 9529 } 9530 } 9531 } 9532 } 9533 } else { 9534 allowed = isPrivilegedApp(pkg); 9535 } 9536 } 9537 } 9538 if (!allowed) { 9539 if (!allowed && (bp.protectionLevel 9540 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9541 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9542 // If this was a previously normal/dangerous permission that got moved 9543 // to a system permission as part of the runtime permission redesign, then 9544 // we still want to blindly grant it to old apps. 9545 allowed = true; 9546 } 9547 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9548 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9549 // If this permission is to be granted to the system installer and 9550 // this app is an installer, then it gets the permission. 9551 allowed = true; 9552 } 9553 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9554 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9555 // If this permission is to be granted to the system verifier and 9556 // this app is a verifier, then it gets the permission. 9557 allowed = true; 9558 } 9559 if (!allowed && (bp.protectionLevel 9560 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9561 && isSystemApp(pkg)) { 9562 // Any pre-installed system app is allowed to get this permission. 9563 allowed = true; 9564 } 9565 if (!allowed && (bp.protectionLevel 9566 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9567 // For development permissions, a development permission 9568 // is granted only if it was already granted. 9569 allowed = origPermissions.hasInstallPermission(perm); 9570 } 9571 } 9572 return allowed; 9573 } 9574 9575 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9576 final int permCount = pkg.requestedPermissions.size(); 9577 for (int j = 0; j < permCount; j++) { 9578 String requestedPermission = pkg.requestedPermissions.get(j); 9579 if (permission.equals(requestedPermission)) { 9580 return true; 9581 } 9582 } 9583 return false; 9584 } 9585 9586 final class ActivityIntentResolver 9587 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9588 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9589 boolean defaultOnly, int userId) { 9590 if (!sUserManager.exists(userId)) return null; 9591 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9592 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9593 } 9594 9595 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9596 int userId) { 9597 if (!sUserManager.exists(userId)) return null; 9598 mFlags = flags; 9599 return super.queryIntent(intent, resolvedType, 9600 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9601 } 9602 9603 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9604 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9605 if (!sUserManager.exists(userId)) return null; 9606 if (packageActivities == null) { 9607 return null; 9608 } 9609 mFlags = flags; 9610 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9611 final int N = packageActivities.size(); 9612 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9613 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9614 9615 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9616 for (int i = 0; i < N; ++i) { 9617 intentFilters = packageActivities.get(i).intents; 9618 if (intentFilters != null && intentFilters.size() > 0) { 9619 PackageParser.ActivityIntentInfo[] array = 9620 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9621 intentFilters.toArray(array); 9622 listCut.add(array); 9623 } 9624 } 9625 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9626 } 9627 9628 public final void addActivity(PackageParser.Activity a, String type) { 9629 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9630 mActivities.put(a.getComponentName(), a); 9631 if (DEBUG_SHOW_INFO) 9632 Log.v( 9633 TAG, " " + type + " " + 9634 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9635 if (DEBUG_SHOW_INFO) 9636 Log.v(TAG, " Class=" + a.info.name); 9637 final int NI = a.intents.size(); 9638 for (int j=0; j<NI; j++) { 9639 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9640 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9641 intent.setPriority(0); 9642 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9643 + a.className + " with priority > 0, forcing to 0"); 9644 } 9645 if (DEBUG_SHOW_INFO) { 9646 Log.v(TAG, " IntentFilter:"); 9647 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9648 } 9649 if (!intent.debugCheck()) { 9650 Log.w(TAG, "==> For Activity " + a.info.name); 9651 } 9652 addFilter(intent); 9653 } 9654 } 9655 9656 public final void removeActivity(PackageParser.Activity a, String type) { 9657 mActivities.remove(a.getComponentName()); 9658 if (DEBUG_SHOW_INFO) { 9659 Log.v(TAG, " " + type + " " 9660 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9661 : a.info.name) + ":"); 9662 Log.v(TAG, " Class=" + a.info.name); 9663 } 9664 final int NI = a.intents.size(); 9665 for (int j=0; j<NI; j++) { 9666 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9667 if (DEBUG_SHOW_INFO) { 9668 Log.v(TAG, " IntentFilter:"); 9669 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9670 } 9671 removeFilter(intent); 9672 } 9673 } 9674 9675 @Override 9676 protected boolean allowFilterResult( 9677 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9678 ActivityInfo filterAi = filter.activity.info; 9679 for (int i=dest.size()-1; i>=0; i--) { 9680 ActivityInfo destAi = dest.get(i).activityInfo; 9681 if (destAi.name == filterAi.name 9682 && destAi.packageName == filterAi.packageName) { 9683 return false; 9684 } 9685 } 9686 return true; 9687 } 9688 9689 @Override 9690 protected ActivityIntentInfo[] newArray(int size) { 9691 return new ActivityIntentInfo[size]; 9692 } 9693 9694 @Override 9695 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9696 if (!sUserManager.exists(userId)) return true; 9697 PackageParser.Package p = filter.activity.owner; 9698 if (p != null) { 9699 PackageSetting ps = (PackageSetting)p.mExtras; 9700 if (ps != null) { 9701 // System apps are never considered stopped for purposes of 9702 // filtering, because there may be no way for the user to 9703 // actually re-launch them. 9704 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9705 && ps.getStopped(userId); 9706 } 9707 } 9708 return false; 9709 } 9710 9711 @Override 9712 protected boolean isPackageForFilter(String packageName, 9713 PackageParser.ActivityIntentInfo info) { 9714 return packageName.equals(info.activity.owner.packageName); 9715 } 9716 9717 @Override 9718 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9719 int match, int userId) { 9720 if (!sUserManager.exists(userId)) return null; 9721 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9722 return null; 9723 } 9724 final PackageParser.Activity activity = info.activity; 9725 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9726 if (ps == null) { 9727 return null; 9728 } 9729 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9730 ps.readUserState(userId), userId); 9731 if (ai == null) { 9732 return null; 9733 } 9734 final ResolveInfo res = new ResolveInfo(); 9735 res.activityInfo = ai; 9736 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9737 res.filter = info; 9738 } 9739 if (info != null) { 9740 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9741 } 9742 res.priority = info.getPriority(); 9743 res.preferredOrder = activity.owner.mPreferredOrder; 9744 //System.out.println("Result: " + res.activityInfo.className + 9745 // " = " + res.priority); 9746 res.match = match; 9747 res.isDefault = info.hasDefault; 9748 res.labelRes = info.labelRes; 9749 res.nonLocalizedLabel = info.nonLocalizedLabel; 9750 if (userNeedsBadging(userId)) { 9751 res.noResourceId = true; 9752 } else { 9753 res.icon = info.icon; 9754 } 9755 res.iconResourceId = info.icon; 9756 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9757 return res; 9758 } 9759 9760 @Override 9761 protected void sortResults(List<ResolveInfo> results) { 9762 Collections.sort(results, mResolvePrioritySorter); 9763 } 9764 9765 @Override 9766 protected void dumpFilter(PrintWriter out, String prefix, 9767 PackageParser.ActivityIntentInfo filter) { 9768 out.print(prefix); out.print( 9769 Integer.toHexString(System.identityHashCode(filter.activity))); 9770 out.print(' '); 9771 filter.activity.printComponentShortName(out); 9772 out.print(" filter "); 9773 out.println(Integer.toHexString(System.identityHashCode(filter))); 9774 } 9775 9776 @Override 9777 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9778 return filter.activity; 9779 } 9780 9781 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9782 PackageParser.Activity activity = (PackageParser.Activity)label; 9783 out.print(prefix); out.print( 9784 Integer.toHexString(System.identityHashCode(activity))); 9785 out.print(' '); 9786 activity.printComponentShortName(out); 9787 if (count > 1) { 9788 out.print(" ("); out.print(count); out.print(" filters)"); 9789 } 9790 out.println(); 9791 } 9792 9793// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9794// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9795// final List<ResolveInfo> retList = Lists.newArrayList(); 9796// while (i.hasNext()) { 9797// final ResolveInfo resolveInfo = i.next(); 9798// if (isEnabledLP(resolveInfo.activityInfo)) { 9799// retList.add(resolveInfo); 9800// } 9801// } 9802// return retList; 9803// } 9804 9805 // Keys are String (activity class name), values are Activity. 9806 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9807 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9808 private int mFlags; 9809 } 9810 9811 private final class ServiceIntentResolver 9812 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9813 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9814 boolean defaultOnly, int userId) { 9815 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9816 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9817 } 9818 9819 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9820 int userId) { 9821 if (!sUserManager.exists(userId)) return null; 9822 mFlags = flags; 9823 return super.queryIntent(intent, resolvedType, 9824 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9825 } 9826 9827 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9828 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9829 if (!sUserManager.exists(userId)) return null; 9830 if (packageServices == null) { 9831 return null; 9832 } 9833 mFlags = flags; 9834 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9835 final int N = packageServices.size(); 9836 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9837 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9838 9839 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9840 for (int i = 0; i < N; ++i) { 9841 intentFilters = packageServices.get(i).intents; 9842 if (intentFilters != null && intentFilters.size() > 0) { 9843 PackageParser.ServiceIntentInfo[] array = 9844 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9845 intentFilters.toArray(array); 9846 listCut.add(array); 9847 } 9848 } 9849 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9850 } 9851 9852 public final void addService(PackageParser.Service s) { 9853 mServices.put(s.getComponentName(), s); 9854 if (DEBUG_SHOW_INFO) { 9855 Log.v(TAG, " " 9856 + (s.info.nonLocalizedLabel != null 9857 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9858 Log.v(TAG, " Class=" + s.info.name); 9859 } 9860 final int NI = s.intents.size(); 9861 int j; 9862 for (j=0; j<NI; j++) { 9863 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9864 if (DEBUG_SHOW_INFO) { 9865 Log.v(TAG, " IntentFilter:"); 9866 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9867 } 9868 if (!intent.debugCheck()) { 9869 Log.w(TAG, "==> For Service " + s.info.name); 9870 } 9871 addFilter(intent); 9872 } 9873 } 9874 9875 public final void removeService(PackageParser.Service s) { 9876 mServices.remove(s.getComponentName()); 9877 if (DEBUG_SHOW_INFO) { 9878 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9879 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9880 Log.v(TAG, " Class=" + s.info.name); 9881 } 9882 final int NI = s.intents.size(); 9883 int j; 9884 for (j=0; j<NI; j++) { 9885 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9886 if (DEBUG_SHOW_INFO) { 9887 Log.v(TAG, " IntentFilter:"); 9888 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9889 } 9890 removeFilter(intent); 9891 } 9892 } 9893 9894 @Override 9895 protected boolean allowFilterResult( 9896 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9897 ServiceInfo filterSi = filter.service.info; 9898 for (int i=dest.size()-1; i>=0; i--) { 9899 ServiceInfo destAi = dest.get(i).serviceInfo; 9900 if (destAi.name == filterSi.name 9901 && destAi.packageName == filterSi.packageName) { 9902 return false; 9903 } 9904 } 9905 return true; 9906 } 9907 9908 @Override 9909 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9910 return new PackageParser.ServiceIntentInfo[size]; 9911 } 9912 9913 @Override 9914 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9915 if (!sUserManager.exists(userId)) return true; 9916 PackageParser.Package p = filter.service.owner; 9917 if (p != null) { 9918 PackageSetting ps = (PackageSetting)p.mExtras; 9919 if (ps != null) { 9920 // System apps are never considered stopped for purposes of 9921 // filtering, because there may be no way for the user to 9922 // actually re-launch them. 9923 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9924 && ps.getStopped(userId); 9925 } 9926 } 9927 return false; 9928 } 9929 9930 @Override 9931 protected boolean isPackageForFilter(String packageName, 9932 PackageParser.ServiceIntentInfo info) { 9933 return packageName.equals(info.service.owner.packageName); 9934 } 9935 9936 @Override 9937 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9938 int match, int userId) { 9939 if (!sUserManager.exists(userId)) return null; 9940 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9941 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9942 return null; 9943 } 9944 final PackageParser.Service service = info.service; 9945 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9946 if (ps == null) { 9947 return null; 9948 } 9949 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9950 ps.readUserState(userId), userId); 9951 if (si == null) { 9952 return null; 9953 } 9954 final ResolveInfo res = new ResolveInfo(); 9955 res.serviceInfo = si; 9956 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9957 res.filter = filter; 9958 } 9959 res.priority = info.getPriority(); 9960 res.preferredOrder = service.owner.mPreferredOrder; 9961 res.match = match; 9962 res.isDefault = info.hasDefault; 9963 res.labelRes = info.labelRes; 9964 res.nonLocalizedLabel = info.nonLocalizedLabel; 9965 res.icon = info.icon; 9966 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9967 return res; 9968 } 9969 9970 @Override 9971 protected void sortResults(List<ResolveInfo> results) { 9972 Collections.sort(results, mResolvePrioritySorter); 9973 } 9974 9975 @Override 9976 protected void dumpFilter(PrintWriter out, String prefix, 9977 PackageParser.ServiceIntentInfo filter) { 9978 out.print(prefix); out.print( 9979 Integer.toHexString(System.identityHashCode(filter.service))); 9980 out.print(' '); 9981 filter.service.printComponentShortName(out); 9982 out.print(" filter "); 9983 out.println(Integer.toHexString(System.identityHashCode(filter))); 9984 } 9985 9986 @Override 9987 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9988 return filter.service; 9989 } 9990 9991 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9992 PackageParser.Service service = (PackageParser.Service)label; 9993 out.print(prefix); out.print( 9994 Integer.toHexString(System.identityHashCode(service))); 9995 out.print(' '); 9996 service.printComponentShortName(out); 9997 if (count > 1) { 9998 out.print(" ("); out.print(count); out.print(" filters)"); 9999 } 10000 out.println(); 10001 } 10002 10003// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10004// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10005// final List<ResolveInfo> retList = Lists.newArrayList(); 10006// while (i.hasNext()) { 10007// final ResolveInfo resolveInfo = (ResolveInfo) i; 10008// if (isEnabledLP(resolveInfo.serviceInfo)) { 10009// retList.add(resolveInfo); 10010// } 10011// } 10012// return retList; 10013// } 10014 10015 // Keys are String (activity class name), values are Activity. 10016 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10017 = new ArrayMap<ComponentName, PackageParser.Service>(); 10018 private int mFlags; 10019 }; 10020 10021 private final class ProviderIntentResolver 10022 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10023 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10024 boolean defaultOnly, int userId) { 10025 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10026 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10027 } 10028 10029 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10030 int userId) { 10031 if (!sUserManager.exists(userId)) 10032 return null; 10033 mFlags = flags; 10034 return super.queryIntent(intent, resolvedType, 10035 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10036 } 10037 10038 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10039 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10040 if (!sUserManager.exists(userId)) 10041 return null; 10042 if (packageProviders == null) { 10043 return null; 10044 } 10045 mFlags = flags; 10046 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10047 final int N = packageProviders.size(); 10048 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10049 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10050 10051 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10052 for (int i = 0; i < N; ++i) { 10053 intentFilters = packageProviders.get(i).intents; 10054 if (intentFilters != null && intentFilters.size() > 0) { 10055 PackageParser.ProviderIntentInfo[] array = 10056 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10057 intentFilters.toArray(array); 10058 listCut.add(array); 10059 } 10060 } 10061 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10062 } 10063 10064 public final void addProvider(PackageParser.Provider p) { 10065 if (mProviders.containsKey(p.getComponentName())) { 10066 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10067 return; 10068 } 10069 10070 mProviders.put(p.getComponentName(), p); 10071 if (DEBUG_SHOW_INFO) { 10072 Log.v(TAG, " " 10073 + (p.info.nonLocalizedLabel != null 10074 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10075 Log.v(TAG, " Class=" + p.info.name); 10076 } 10077 final int NI = p.intents.size(); 10078 int j; 10079 for (j = 0; j < NI; j++) { 10080 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10081 if (DEBUG_SHOW_INFO) { 10082 Log.v(TAG, " IntentFilter:"); 10083 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10084 } 10085 if (!intent.debugCheck()) { 10086 Log.w(TAG, "==> For Provider " + p.info.name); 10087 } 10088 addFilter(intent); 10089 } 10090 } 10091 10092 public final void removeProvider(PackageParser.Provider p) { 10093 mProviders.remove(p.getComponentName()); 10094 if (DEBUG_SHOW_INFO) { 10095 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10096 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10097 Log.v(TAG, " Class=" + p.info.name); 10098 } 10099 final int NI = p.intents.size(); 10100 int j; 10101 for (j = 0; j < NI; j++) { 10102 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10103 if (DEBUG_SHOW_INFO) { 10104 Log.v(TAG, " IntentFilter:"); 10105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10106 } 10107 removeFilter(intent); 10108 } 10109 } 10110 10111 @Override 10112 protected boolean allowFilterResult( 10113 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10114 ProviderInfo filterPi = filter.provider.info; 10115 for (int i = dest.size() - 1; i >= 0; i--) { 10116 ProviderInfo destPi = dest.get(i).providerInfo; 10117 if (destPi.name == filterPi.name 10118 && destPi.packageName == filterPi.packageName) { 10119 return false; 10120 } 10121 } 10122 return true; 10123 } 10124 10125 @Override 10126 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10127 return new PackageParser.ProviderIntentInfo[size]; 10128 } 10129 10130 @Override 10131 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10132 if (!sUserManager.exists(userId)) 10133 return true; 10134 PackageParser.Package p = filter.provider.owner; 10135 if (p != null) { 10136 PackageSetting ps = (PackageSetting) p.mExtras; 10137 if (ps != null) { 10138 // System apps are never considered stopped for purposes of 10139 // filtering, because there may be no way for the user to 10140 // actually re-launch them. 10141 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10142 && ps.getStopped(userId); 10143 } 10144 } 10145 return false; 10146 } 10147 10148 @Override 10149 protected boolean isPackageForFilter(String packageName, 10150 PackageParser.ProviderIntentInfo info) { 10151 return packageName.equals(info.provider.owner.packageName); 10152 } 10153 10154 @Override 10155 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10156 int match, int userId) { 10157 if (!sUserManager.exists(userId)) 10158 return null; 10159 final PackageParser.ProviderIntentInfo info = filter; 10160 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10161 return null; 10162 } 10163 final PackageParser.Provider provider = info.provider; 10164 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10165 if (ps == null) { 10166 return null; 10167 } 10168 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10169 ps.readUserState(userId), userId); 10170 if (pi == null) { 10171 return null; 10172 } 10173 final ResolveInfo res = new ResolveInfo(); 10174 res.providerInfo = pi; 10175 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10176 res.filter = filter; 10177 } 10178 res.priority = info.getPriority(); 10179 res.preferredOrder = provider.owner.mPreferredOrder; 10180 res.match = match; 10181 res.isDefault = info.hasDefault; 10182 res.labelRes = info.labelRes; 10183 res.nonLocalizedLabel = info.nonLocalizedLabel; 10184 res.icon = info.icon; 10185 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10186 return res; 10187 } 10188 10189 @Override 10190 protected void sortResults(List<ResolveInfo> results) { 10191 Collections.sort(results, mResolvePrioritySorter); 10192 } 10193 10194 @Override 10195 protected void dumpFilter(PrintWriter out, String prefix, 10196 PackageParser.ProviderIntentInfo filter) { 10197 out.print(prefix); 10198 out.print( 10199 Integer.toHexString(System.identityHashCode(filter.provider))); 10200 out.print(' '); 10201 filter.provider.printComponentShortName(out); 10202 out.print(" filter "); 10203 out.println(Integer.toHexString(System.identityHashCode(filter))); 10204 } 10205 10206 @Override 10207 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10208 return filter.provider; 10209 } 10210 10211 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10212 PackageParser.Provider provider = (PackageParser.Provider)label; 10213 out.print(prefix); out.print( 10214 Integer.toHexString(System.identityHashCode(provider))); 10215 out.print(' '); 10216 provider.printComponentShortName(out); 10217 if (count > 1) { 10218 out.print(" ("); out.print(count); out.print(" filters)"); 10219 } 10220 out.println(); 10221 } 10222 10223 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10224 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10225 private int mFlags; 10226 } 10227 10228 private static final class EphemeralIntentResolver 10229 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10230 @Override 10231 protected EphemeralResolveIntentInfo[] newArray(int size) { 10232 return new EphemeralResolveIntentInfo[size]; 10233 } 10234 10235 @Override 10236 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10237 return true; 10238 } 10239 10240 @Override 10241 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10242 int userId) { 10243 if (!sUserManager.exists(userId)) { 10244 return null; 10245 } 10246 return info.getEphemeralResolveInfo(); 10247 } 10248 } 10249 10250 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10251 new Comparator<ResolveInfo>() { 10252 public int compare(ResolveInfo r1, ResolveInfo r2) { 10253 int v1 = r1.priority; 10254 int v2 = r2.priority; 10255 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10256 if (v1 != v2) { 10257 return (v1 > v2) ? -1 : 1; 10258 } 10259 v1 = r1.preferredOrder; 10260 v2 = r2.preferredOrder; 10261 if (v1 != v2) { 10262 return (v1 > v2) ? -1 : 1; 10263 } 10264 if (r1.isDefault != r2.isDefault) { 10265 return r1.isDefault ? -1 : 1; 10266 } 10267 v1 = r1.match; 10268 v2 = r2.match; 10269 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10270 if (v1 != v2) { 10271 return (v1 > v2) ? -1 : 1; 10272 } 10273 if (r1.system != r2.system) { 10274 return r1.system ? -1 : 1; 10275 } 10276 if (r1.activityInfo != null) { 10277 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10278 } 10279 if (r1.serviceInfo != null) { 10280 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10281 } 10282 if (r1.providerInfo != null) { 10283 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10284 } 10285 return 0; 10286 } 10287 }; 10288 10289 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10290 new Comparator<ProviderInfo>() { 10291 public int compare(ProviderInfo p1, ProviderInfo p2) { 10292 final int v1 = p1.initOrder; 10293 final int v2 = p2.initOrder; 10294 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10295 } 10296 }; 10297 10298 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10299 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10300 final int[] userIds) { 10301 mHandler.post(new Runnable() { 10302 @Override 10303 public void run() { 10304 try { 10305 final IActivityManager am = ActivityManagerNative.getDefault(); 10306 if (am == null) return; 10307 final int[] resolvedUserIds; 10308 if (userIds == null) { 10309 resolvedUserIds = am.getRunningUserIds(); 10310 } else { 10311 resolvedUserIds = userIds; 10312 } 10313 for (int id : resolvedUserIds) { 10314 final Intent intent = new Intent(action, 10315 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10316 if (extras != null) { 10317 intent.putExtras(extras); 10318 } 10319 if (targetPkg != null) { 10320 intent.setPackage(targetPkg); 10321 } 10322 // Modify the UID when posting to other users 10323 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10324 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10325 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10326 intent.putExtra(Intent.EXTRA_UID, uid); 10327 } 10328 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10329 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10330 if (DEBUG_BROADCASTS) { 10331 RuntimeException here = new RuntimeException("here"); 10332 here.fillInStackTrace(); 10333 Slog.d(TAG, "Sending to user " + id + ": " 10334 + intent.toShortString(false, true, false, false) 10335 + " " + intent.getExtras(), here); 10336 } 10337 am.broadcastIntent(null, intent, null, finishedReceiver, 10338 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10339 null, finishedReceiver != null, false, id); 10340 } 10341 } catch (RemoteException ex) { 10342 } 10343 } 10344 }); 10345 } 10346 10347 /** 10348 * Check if the external storage media is available. This is true if there 10349 * is a mounted external storage medium or if the external storage is 10350 * emulated. 10351 */ 10352 private boolean isExternalMediaAvailable() { 10353 return mMediaMounted || Environment.isExternalStorageEmulated(); 10354 } 10355 10356 @Override 10357 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10358 // writer 10359 synchronized (mPackages) { 10360 if (!isExternalMediaAvailable()) { 10361 // If the external storage is no longer mounted at this point, 10362 // the caller may not have been able to delete all of this 10363 // packages files and can not delete any more. Bail. 10364 return null; 10365 } 10366 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10367 if (lastPackage != null) { 10368 pkgs.remove(lastPackage); 10369 } 10370 if (pkgs.size() > 0) { 10371 return pkgs.get(0); 10372 } 10373 } 10374 return null; 10375 } 10376 10377 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10378 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10379 userId, andCode ? 1 : 0, packageName); 10380 if (mSystemReady) { 10381 msg.sendToTarget(); 10382 } else { 10383 if (mPostSystemReadyMessages == null) { 10384 mPostSystemReadyMessages = new ArrayList<>(); 10385 } 10386 mPostSystemReadyMessages.add(msg); 10387 } 10388 } 10389 10390 void startCleaningPackages() { 10391 // reader 10392 synchronized (mPackages) { 10393 if (!isExternalMediaAvailable()) { 10394 return; 10395 } 10396 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10397 return; 10398 } 10399 } 10400 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10401 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10402 IActivityManager am = ActivityManagerNative.getDefault(); 10403 if (am != null) { 10404 try { 10405 am.startService(null, intent, null, mContext.getOpPackageName(), 10406 UserHandle.USER_SYSTEM); 10407 } catch (RemoteException e) { 10408 } 10409 } 10410 } 10411 10412 @Override 10413 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10414 int installFlags, String installerPackageName, int userId) { 10415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10416 10417 final int callingUid = Binder.getCallingUid(); 10418 enforceCrossUserPermission(callingUid, userId, 10419 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10420 10421 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10422 try { 10423 if (observer != null) { 10424 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10425 } 10426 } catch (RemoteException re) { 10427 } 10428 return; 10429 } 10430 10431 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10432 installFlags |= PackageManager.INSTALL_FROM_ADB; 10433 10434 } else { 10435 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10436 // about installerPackageName. 10437 10438 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10439 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10440 } 10441 10442 UserHandle user; 10443 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10444 user = UserHandle.ALL; 10445 } else { 10446 user = new UserHandle(userId); 10447 } 10448 10449 // Only system components can circumvent runtime permissions when installing. 10450 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10451 && mContext.checkCallingOrSelfPermission(Manifest.permission 10452 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10453 throw new SecurityException("You need the " 10454 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10455 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10456 } 10457 10458 final File originFile = new File(originPath); 10459 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10460 10461 final Message msg = mHandler.obtainMessage(INIT_COPY); 10462 final VerificationInfo verificationInfo = new VerificationInfo( 10463 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10464 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10465 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10466 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10467 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10468 msg.obj = params; 10469 10470 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10471 System.identityHashCode(msg.obj)); 10472 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10473 System.identityHashCode(msg.obj)); 10474 10475 mHandler.sendMessage(msg); 10476 } 10477 10478 void installStage(String packageName, File stagedDir, String stagedCid, 10479 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10480 String installerPackageName, int installerUid, UserHandle user) { 10481 if (DEBUG_EPHEMERAL) { 10482 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10483 Slog.d(TAG, "Ephemeral install of " + packageName); 10484 } 10485 } 10486 final VerificationInfo verificationInfo = new VerificationInfo( 10487 sessionParams.originatingUri, sessionParams.referrerUri, 10488 sessionParams.originatingUid, installerUid); 10489 10490 final OriginInfo origin; 10491 if (stagedDir != null) { 10492 origin = OriginInfo.fromStagedFile(stagedDir); 10493 } else { 10494 origin = OriginInfo.fromStagedContainer(stagedCid); 10495 } 10496 10497 final Message msg = mHandler.obtainMessage(INIT_COPY); 10498 final InstallParams params = new InstallParams(origin, null, observer, 10499 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10500 verificationInfo, user, sessionParams.abiOverride, 10501 sessionParams.grantedRuntimePermissions); 10502 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10503 msg.obj = params; 10504 10505 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10506 System.identityHashCode(msg.obj)); 10507 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10508 System.identityHashCode(msg.obj)); 10509 10510 mHandler.sendMessage(msg); 10511 } 10512 10513 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10514 int userId) { 10515 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10516 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10517 } 10518 10519 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10520 int appId, int userId) { 10521 Bundle extras = new Bundle(1); 10522 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10523 10524 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10525 packageName, extras, 0, null, null, new int[] {userId}); 10526 try { 10527 IActivityManager am = ActivityManagerNative.getDefault(); 10528 if (isSystem && am.isUserRunning(userId, 0)) { 10529 // The just-installed/enabled app is bundled on the system, so presumed 10530 // to be able to run automatically without needing an explicit launch. 10531 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10532 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10533 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10534 .setPackage(packageName); 10535 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10536 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10537 } 10538 } catch (RemoteException e) { 10539 // shouldn't happen 10540 Slog.w(TAG, "Unable to bootstrap installed package", e); 10541 } 10542 } 10543 10544 @Override 10545 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10546 int userId) { 10547 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10548 PackageSetting pkgSetting; 10549 final int uid = Binder.getCallingUid(); 10550 enforceCrossUserPermission(uid, userId, 10551 true /* requireFullPermission */, true /* checkShell */, 10552 "setApplicationHiddenSetting for user " + userId); 10553 10554 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10555 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10556 return false; 10557 } 10558 10559 long callingId = Binder.clearCallingIdentity(); 10560 try { 10561 boolean sendAdded = false; 10562 boolean sendRemoved = false; 10563 // writer 10564 synchronized (mPackages) { 10565 pkgSetting = mSettings.mPackages.get(packageName); 10566 if (pkgSetting == null) { 10567 return false; 10568 } 10569 if (pkgSetting.getHidden(userId) != hidden) { 10570 pkgSetting.setHidden(hidden, userId); 10571 mSettings.writePackageRestrictionsLPr(userId); 10572 if (hidden) { 10573 sendRemoved = true; 10574 } else { 10575 sendAdded = true; 10576 } 10577 } 10578 } 10579 if (sendAdded) { 10580 sendPackageAddedForUser(packageName, pkgSetting, userId); 10581 return true; 10582 } 10583 if (sendRemoved) { 10584 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10585 "hiding pkg"); 10586 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10587 return true; 10588 } 10589 } finally { 10590 Binder.restoreCallingIdentity(callingId); 10591 } 10592 return false; 10593 } 10594 10595 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10596 int userId) { 10597 final PackageRemovedInfo info = new PackageRemovedInfo(); 10598 info.removedPackage = packageName; 10599 info.removedUsers = new int[] {userId}; 10600 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10601 info.sendPackageRemovedBroadcasts(); 10602 } 10603 10604 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10605 if (pkgList.length > 0) { 10606 Bundle extras = new Bundle(1); 10607 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10608 10609 sendPackageBroadcast( 10610 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10611 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10612 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10613 new int[] {userId}); 10614 } 10615 } 10616 10617 /** 10618 * Returns true if application is not found or there was an error. Otherwise it returns 10619 * the hidden state of the package for the given user. 10620 */ 10621 @Override 10622 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10623 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10625 true /* requireFullPermission */, false /* checkShell */, 10626 "getApplicationHidden for user " + userId); 10627 PackageSetting pkgSetting; 10628 long callingId = Binder.clearCallingIdentity(); 10629 try { 10630 // writer 10631 synchronized (mPackages) { 10632 pkgSetting = mSettings.mPackages.get(packageName); 10633 if (pkgSetting == null) { 10634 return true; 10635 } 10636 return pkgSetting.getHidden(userId); 10637 } 10638 } finally { 10639 Binder.restoreCallingIdentity(callingId); 10640 } 10641 } 10642 10643 /** 10644 * @hide 10645 */ 10646 @Override 10647 public int installExistingPackageAsUser(String packageName, int userId) { 10648 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10649 null); 10650 PackageSetting pkgSetting; 10651 final int uid = Binder.getCallingUid(); 10652 enforceCrossUserPermission(uid, userId, 10653 true /* requireFullPermission */, true /* checkShell */, 10654 "installExistingPackage for user " + userId); 10655 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10656 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10657 } 10658 10659 long callingId = Binder.clearCallingIdentity(); 10660 try { 10661 boolean installed = false; 10662 10663 // writer 10664 synchronized (mPackages) { 10665 pkgSetting = mSettings.mPackages.get(packageName); 10666 if (pkgSetting == null) { 10667 return PackageManager.INSTALL_FAILED_INVALID_URI; 10668 } 10669 if (!pkgSetting.getInstalled(userId)) { 10670 pkgSetting.setInstalled(true, userId); 10671 pkgSetting.setHidden(false, userId); 10672 mSettings.writePackageRestrictionsLPr(userId); 10673 installed = true; 10674 } 10675 } 10676 10677 if (installed) { 10678 if (pkgSetting.pkg != null) { 10679 prepareAppDataAfterInstall(pkgSetting.pkg); 10680 } 10681 sendPackageAddedForUser(packageName, pkgSetting, userId); 10682 } 10683 } finally { 10684 Binder.restoreCallingIdentity(callingId); 10685 } 10686 10687 return PackageManager.INSTALL_SUCCEEDED; 10688 } 10689 10690 boolean isUserRestricted(int userId, String restrictionKey) { 10691 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10692 if (restrictions.getBoolean(restrictionKey, false)) { 10693 Log.w(TAG, "User is restricted: " + restrictionKey); 10694 return true; 10695 } 10696 return false; 10697 } 10698 10699 @Override 10700 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10701 int userId) { 10702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10703 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10704 true /* requireFullPermission */, true /* checkShell */, 10705 "setPackagesSuspended for user " + userId); 10706 10707 if (ArrayUtils.isEmpty(packageNames)) { 10708 return packageNames; 10709 } 10710 10711 // List of package names for whom the suspended state has changed. 10712 List<String> changedPackages = new ArrayList<>(packageNames.length); 10713 // List of package names for whom the suspended state is not set as requested in this 10714 // method. 10715 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10716 for (int i = 0; i < packageNames.length; i++) { 10717 String packageName = packageNames[i]; 10718 long callingId = Binder.clearCallingIdentity(); 10719 try { 10720 boolean changed = false; 10721 final int appId; 10722 synchronized (mPackages) { 10723 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10724 if (pkgSetting == null) { 10725 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10726 + "\". Skipping suspending/un-suspending."); 10727 unactionedPackages.add(packageName); 10728 continue; 10729 } 10730 appId = pkgSetting.appId; 10731 if (pkgSetting.getSuspended(userId) != suspended) { 10732 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10733 unactionedPackages.add(packageName); 10734 continue; 10735 } 10736 pkgSetting.setSuspended(suspended, userId); 10737 mSettings.writePackageRestrictionsLPr(userId); 10738 changed = true; 10739 changedPackages.add(packageName); 10740 } 10741 } 10742 10743 if (changed && suspended) { 10744 killApplication(packageName, UserHandle.getUid(userId, appId), 10745 "suspending package"); 10746 } 10747 } finally { 10748 Binder.restoreCallingIdentity(callingId); 10749 } 10750 } 10751 10752 if (!changedPackages.isEmpty()) { 10753 sendPackagesSuspendedForUser(changedPackages.toArray( 10754 new String[changedPackages.size()]), userId, suspended); 10755 } 10756 10757 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10758 } 10759 10760 @Override 10761 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10762 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10763 true /* requireFullPermission */, false /* checkShell */, 10764 "isPackageSuspendedForUser for user " + userId); 10765 synchronized (mPackages) { 10766 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10767 return pkgSetting != null && pkgSetting.getSuspended(userId); 10768 } 10769 } 10770 10771 // TODO: investigate and add more restrictions for suspending crucial packages. 10772 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10773 if (isPackageDeviceAdmin(packageName, userId)) { 10774 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10775 + "\": has active device admin"); 10776 return false; 10777 } 10778 10779 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10780 if (packageName.equals(activeLauncherPackageName)) { 10781 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10782 + "\" because it is set as the active launcher"); 10783 return false; 10784 } 10785 10786 final PackageParser.Package pkg = mPackages.get(packageName); 10787 if (pkg != null && isPrivilegedApp(pkg)) { 10788 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10789 + "\" because it is a privileged app"); 10790 return false; 10791 } 10792 10793 return true; 10794 } 10795 10796 private String getActiveLauncherPackageName(int userId) { 10797 Intent intent = new Intent(Intent.ACTION_MAIN); 10798 intent.addCategory(Intent.CATEGORY_HOME); 10799 ResolveInfo resolveInfo = resolveIntent( 10800 intent, 10801 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10802 PackageManager.MATCH_DEFAULT_ONLY, 10803 userId); 10804 10805 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10806 } 10807 10808 @Override 10809 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10810 mContext.enforceCallingOrSelfPermission( 10811 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10812 "Only package verification agents can verify applications"); 10813 10814 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10815 final PackageVerificationResponse response = new PackageVerificationResponse( 10816 verificationCode, Binder.getCallingUid()); 10817 msg.arg1 = id; 10818 msg.obj = response; 10819 mHandler.sendMessage(msg); 10820 } 10821 10822 @Override 10823 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10824 long millisecondsToDelay) { 10825 mContext.enforceCallingOrSelfPermission( 10826 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10827 "Only package verification agents can extend verification timeouts"); 10828 10829 final PackageVerificationState state = mPendingVerification.get(id); 10830 final PackageVerificationResponse response = new PackageVerificationResponse( 10831 verificationCodeAtTimeout, Binder.getCallingUid()); 10832 10833 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10834 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10835 } 10836 if (millisecondsToDelay < 0) { 10837 millisecondsToDelay = 0; 10838 } 10839 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10840 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10841 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10842 } 10843 10844 if ((state != null) && !state.timeoutExtended()) { 10845 state.extendTimeout(); 10846 10847 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10848 msg.arg1 = id; 10849 msg.obj = response; 10850 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10851 } 10852 } 10853 10854 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10855 int verificationCode, UserHandle user) { 10856 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10857 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10858 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10859 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10860 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10861 10862 mContext.sendBroadcastAsUser(intent, user, 10863 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10864 } 10865 10866 private ComponentName matchComponentForVerifier(String packageName, 10867 List<ResolveInfo> receivers) { 10868 ActivityInfo targetReceiver = null; 10869 10870 final int NR = receivers.size(); 10871 for (int i = 0; i < NR; i++) { 10872 final ResolveInfo info = receivers.get(i); 10873 if (info.activityInfo == null) { 10874 continue; 10875 } 10876 10877 if (packageName.equals(info.activityInfo.packageName)) { 10878 targetReceiver = info.activityInfo; 10879 break; 10880 } 10881 } 10882 10883 if (targetReceiver == null) { 10884 return null; 10885 } 10886 10887 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10888 } 10889 10890 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10891 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10892 if (pkgInfo.verifiers.length == 0) { 10893 return null; 10894 } 10895 10896 final int N = pkgInfo.verifiers.length; 10897 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10898 for (int i = 0; i < N; i++) { 10899 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10900 10901 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10902 receivers); 10903 if (comp == null) { 10904 continue; 10905 } 10906 10907 final int verifierUid = getUidForVerifier(verifierInfo); 10908 if (verifierUid == -1) { 10909 continue; 10910 } 10911 10912 if (DEBUG_VERIFY) { 10913 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10914 + " with the correct signature"); 10915 } 10916 sufficientVerifiers.add(comp); 10917 verificationState.addSufficientVerifier(verifierUid); 10918 } 10919 10920 return sufficientVerifiers; 10921 } 10922 10923 private int getUidForVerifier(VerifierInfo verifierInfo) { 10924 synchronized (mPackages) { 10925 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10926 if (pkg == null) { 10927 return -1; 10928 } else if (pkg.mSignatures.length != 1) { 10929 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10930 + " has more than one signature; ignoring"); 10931 return -1; 10932 } 10933 10934 /* 10935 * If the public key of the package's signature does not match 10936 * our expected public key, then this is a different package and 10937 * we should skip. 10938 */ 10939 10940 final byte[] expectedPublicKey; 10941 try { 10942 final Signature verifierSig = pkg.mSignatures[0]; 10943 final PublicKey publicKey = verifierSig.getPublicKey(); 10944 expectedPublicKey = publicKey.getEncoded(); 10945 } catch (CertificateException e) { 10946 return -1; 10947 } 10948 10949 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10950 10951 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10952 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10953 + " does not have the expected public key; ignoring"); 10954 return -1; 10955 } 10956 10957 return pkg.applicationInfo.uid; 10958 } 10959 } 10960 10961 @Override 10962 public void finishPackageInstall(int token) { 10963 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10964 10965 if (DEBUG_INSTALL) { 10966 Slog.v(TAG, "BM finishing package install for " + token); 10967 } 10968 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10969 10970 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10971 mHandler.sendMessage(msg); 10972 } 10973 10974 /** 10975 * Get the verification agent timeout. 10976 * 10977 * @return verification timeout in milliseconds 10978 */ 10979 private long getVerificationTimeout() { 10980 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10981 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10982 DEFAULT_VERIFICATION_TIMEOUT); 10983 } 10984 10985 /** 10986 * Get the default verification agent response code. 10987 * 10988 * @return default verification response code 10989 */ 10990 private int getDefaultVerificationResponse() { 10991 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10992 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10993 DEFAULT_VERIFICATION_RESPONSE); 10994 } 10995 10996 /** 10997 * Check whether or not package verification has been enabled. 10998 * 10999 * @return true if verification should be performed 11000 */ 11001 private boolean isVerificationEnabled(int userId, int installFlags) { 11002 if (!DEFAULT_VERIFY_ENABLE) { 11003 return false; 11004 } 11005 // Ephemeral apps don't get the full verification treatment 11006 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11007 if (DEBUG_EPHEMERAL) { 11008 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11009 } 11010 return false; 11011 } 11012 11013 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11014 11015 // Check if installing from ADB 11016 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11017 // Do not run verification in a test harness environment 11018 if (ActivityManager.isRunningInTestHarness()) { 11019 return false; 11020 } 11021 if (ensureVerifyAppsEnabled) { 11022 return true; 11023 } 11024 // Check if the developer does not want package verification for ADB installs 11025 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11026 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11027 return false; 11028 } 11029 } 11030 11031 if (ensureVerifyAppsEnabled) { 11032 return true; 11033 } 11034 11035 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11036 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11037 } 11038 11039 @Override 11040 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11041 throws RemoteException { 11042 mContext.enforceCallingOrSelfPermission( 11043 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11044 "Only intentfilter verification agents can verify applications"); 11045 11046 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11047 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11048 Binder.getCallingUid(), verificationCode, failedDomains); 11049 msg.arg1 = id; 11050 msg.obj = response; 11051 mHandler.sendMessage(msg); 11052 } 11053 11054 @Override 11055 public int getIntentVerificationStatus(String packageName, int userId) { 11056 synchronized (mPackages) { 11057 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11058 } 11059 } 11060 11061 @Override 11062 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11063 mContext.enforceCallingOrSelfPermission( 11064 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11065 11066 boolean result = false; 11067 synchronized (mPackages) { 11068 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11069 } 11070 if (result) { 11071 scheduleWritePackageRestrictionsLocked(userId); 11072 } 11073 return result; 11074 } 11075 11076 @Override 11077 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11078 synchronized (mPackages) { 11079 return mSettings.getIntentFilterVerificationsLPr(packageName); 11080 } 11081 } 11082 11083 @Override 11084 public List<IntentFilter> getAllIntentFilters(String packageName) { 11085 if (TextUtils.isEmpty(packageName)) { 11086 return Collections.<IntentFilter>emptyList(); 11087 } 11088 synchronized (mPackages) { 11089 PackageParser.Package pkg = mPackages.get(packageName); 11090 if (pkg == null || pkg.activities == null) { 11091 return Collections.<IntentFilter>emptyList(); 11092 } 11093 final int count = pkg.activities.size(); 11094 ArrayList<IntentFilter> result = new ArrayList<>(); 11095 for (int n=0; n<count; n++) { 11096 PackageParser.Activity activity = pkg.activities.get(n); 11097 if (activity.intents != null && activity.intents.size() > 0) { 11098 result.addAll(activity.intents); 11099 } 11100 } 11101 return result; 11102 } 11103 } 11104 11105 @Override 11106 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11107 mContext.enforceCallingOrSelfPermission( 11108 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11109 11110 synchronized (mPackages) { 11111 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11112 if (packageName != null) { 11113 result |= updateIntentVerificationStatus(packageName, 11114 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11115 userId); 11116 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11117 packageName, userId); 11118 } 11119 return result; 11120 } 11121 } 11122 11123 @Override 11124 public String getDefaultBrowserPackageName(int userId) { 11125 synchronized (mPackages) { 11126 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11127 } 11128 } 11129 11130 /** 11131 * Get the "allow unknown sources" setting. 11132 * 11133 * @return the current "allow unknown sources" setting 11134 */ 11135 private int getUnknownSourcesSettings() { 11136 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11137 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11138 -1); 11139 } 11140 11141 @Override 11142 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11143 final int uid = Binder.getCallingUid(); 11144 // writer 11145 synchronized (mPackages) { 11146 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11147 if (targetPackageSetting == null) { 11148 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11149 } 11150 11151 PackageSetting installerPackageSetting; 11152 if (installerPackageName != null) { 11153 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11154 if (installerPackageSetting == null) { 11155 throw new IllegalArgumentException("Unknown installer package: " 11156 + installerPackageName); 11157 } 11158 } else { 11159 installerPackageSetting = null; 11160 } 11161 11162 Signature[] callerSignature; 11163 Object obj = mSettings.getUserIdLPr(uid); 11164 if (obj != null) { 11165 if (obj instanceof SharedUserSetting) { 11166 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11167 } else if (obj instanceof PackageSetting) { 11168 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11169 } else { 11170 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11171 } 11172 } else { 11173 throw new SecurityException("Unknown calling UID: " + uid); 11174 } 11175 11176 // Verify: can't set installerPackageName to a package that is 11177 // not signed with the same cert as the caller. 11178 if (installerPackageSetting != null) { 11179 if (compareSignatures(callerSignature, 11180 installerPackageSetting.signatures.mSignatures) 11181 != PackageManager.SIGNATURE_MATCH) { 11182 throw new SecurityException( 11183 "Caller does not have same cert as new installer package " 11184 + installerPackageName); 11185 } 11186 } 11187 11188 // Verify: if target already has an installer package, it must 11189 // be signed with the same cert as the caller. 11190 if (targetPackageSetting.installerPackageName != null) { 11191 PackageSetting setting = mSettings.mPackages.get( 11192 targetPackageSetting.installerPackageName); 11193 // If the currently set package isn't valid, then it's always 11194 // okay to change it. 11195 if (setting != null) { 11196 if (compareSignatures(callerSignature, 11197 setting.signatures.mSignatures) 11198 != PackageManager.SIGNATURE_MATCH) { 11199 throw new SecurityException( 11200 "Caller does not have same cert as old installer package " 11201 + targetPackageSetting.installerPackageName); 11202 } 11203 } 11204 } 11205 11206 // Okay! 11207 targetPackageSetting.installerPackageName = installerPackageName; 11208 scheduleWriteSettingsLocked(); 11209 } 11210 } 11211 11212 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11213 // Queue up an async operation since the package installation may take a little while. 11214 mHandler.post(new Runnable() { 11215 public void run() { 11216 mHandler.removeCallbacks(this); 11217 // Result object to be returned 11218 PackageInstalledInfo res = new PackageInstalledInfo(); 11219 res.setReturnCode(currentStatus); 11220 res.uid = -1; 11221 res.pkg = null; 11222 res.removedInfo = null; 11223 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11224 args.doPreInstall(res.returnCode); 11225 synchronized (mInstallLock) { 11226 installPackageTracedLI(args, res); 11227 } 11228 args.doPostInstall(res.returnCode, res.uid); 11229 } 11230 11231 // A restore should be performed at this point if (a) the install 11232 // succeeded, (b) the operation is not an update, and (c) the new 11233 // package has not opted out of backup participation. 11234 final boolean update = res.removedInfo != null 11235 && res.removedInfo.removedPackage != null; 11236 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11237 boolean doRestore = !update 11238 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11239 11240 // Set up the post-install work request bookkeeping. This will be used 11241 // and cleaned up by the post-install event handling regardless of whether 11242 // there's a restore pass performed. Token values are >= 1. 11243 int token; 11244 if (mNextInstallToken < 0) mNextInstallToken = 1; 11245 token = mNextInstallToken++; 11246 11247 PostInstallData data = new PostInstallData(args, res); 11248 mRunningInstalls.put(token, data); 11249 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11250 11251 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11252 // Pass responsibility to the Backup Manager. It will perform a 11253 // restore if appropriate, then pass responsibility back to the 11254 // Package Manager to run the post-install observer callbacks 11255 // and broadcasts. 11256 IBackupManager bm = IBackupManager.Stub.asInterface( 11257 ServiceManager.getService(Context.BACKUP_SERVICE)); 11258 if (bm != null) { 11259 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11260 + " to BM for possible restore"); 11261 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11262 try { 11263 // TODO: http://b/22388012 11264 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11265 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11266 } else { 11267 doRestore = false; 11268 } 11269 } catch (RemoteException e) { 11270 // can't happen; the backup manager is local 11271 } catch (Exception e) { 11272 Slog.e(TAG, "Exception trying to enqueue restore", e); 11273 doRestore = false; 11274 } 11275 } else { 11276 Slog.e(TAG, "Backup Manager not found!"); 11277 doRestore = false; 11278 } 11279 } 11280 11281 if (!doRestore) { 11282 // No restore possible, or the Backup Manager was mysteriously not 11283 // available -- just fire the post-install work request directly. 11284 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11285 11286 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11287 11288 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11289 mHandler.sendMessage(msg); 11290 } 11291 } 11292 }); 11293 } 11294 11295 private abstract class HandlerParams { 11296 private static final int MAX_RETRIES = 4; 11297 11298 /** 11299 * Number of times startCopy() has been attempted and had a non-fatal 11300 * error. 11301 */ 11302 private int mRetries = 0; 11303 11304 /** User handle for the user requesting the information or installation. */ 11305 private final UserHandle mUser; 11306 String traceMethod; 11307 int traceCookie; 11308 11309 HandlerParams(UserHandle user) { 11310 mUser = user; 11311 } 11312 11313 UserHandle getUser() { 11314 return mUser; 11315 } 11316 11317 HandlerParams setTraceMethod(String traceMethod) { 11318 this.traceMethod = traceMethod; 11319 return this; 11320 } 11321 11322 HandlerParams setTraceCookie(int traceCookie) { 11323 this.traceCookie = traceCookie; 11324 return this; 11325 } 11326 11327 final boolean startCopy() { 11328 boolean res; 11329 try { 11330 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11331 11332 if (++mRetries > MAX_RETRIES) { 11333 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11334 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11335 handleServiceError(); 11336 return false; 11337 } else { 11338 handleStartCopy(); 11339 res = true; 11340 } 11341 } catch (RemoteException e) { 11342 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11343 mHandler.sendEmptyMessage(MCS_RECONNECT); 11344 res = false; 11345 } 11346 handleReturnCode(); 11347 return res; 11348 } 11349 11350 final void serviceError() { 11351 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11352 handleServiceError(); 11353 handleReturnCode(); 11354 } 11355 11356 abstract void handleStartCopy() throws RemoteException; 11357 abstract void handleServiceError(); 11358 abstract void handleReturnCode(); 11359 } 11360 11361 class MeasureParams extends HandlerParams { 11362 private final PackageStats mStats; 11363 private boolean mSuccess; 11364 11365 private final IPackageStatsObserver mObserver; 11366 11367 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11368 super(new UserHandle(stats.userHandle)); 11369 mObserver = observer; 11370 mStats = stats; 11371 } 11372 11373 @Override 11374 public String toString() { 11375 return "MeasureParams{" 11376 + Integer.toHexString(System.identityHashCode(this)) 11377 + " " + mStats.packageName + "}"; 11378 } 11379 11380 @Override 11381 void handleStartCopy() throws RemoteException { 11382 synchronized (mInstallLock) { 11383 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11384 } 11385 11386 if (mSuccess) { 11387 final boolean mounted; 11388 if (Environment.isExternalStorageEmulated()) { 11389 mounted = true; 11390 } else { 11391 final String status = Environment.getExternalStorageState(); 11392 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11393 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11394 } 11395 11396 if (mounted) { 11397 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11398 11399 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11400 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11401 11402 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11403 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11404 11405 // Always subtract cache size, since it's a subdirectory 11406 mStats.externalDataSize -= mStats.externalCacheSize; 11407 11408 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11409 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11410 11411 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11412 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11413 } 11414 } 11415 } 11416 11417 @Override 11418 void handleReturnCode() { 11419 if (mObserver != null) { 11420 try { 11421 mObserver.onGetStatsCompleted(mStats, mSuccess); 11422 } catch (RemoteException e) { 11423 Slog.i(TAG, "Observer no longer exists."); 11424 } 11425 } 11426 } 11427 11428 @Override 11429 void handleServiceError() { 11430 Slog.e(TAG, "Could not measure application " + mStats.packageName 11431 + " external storage"); 11432 } 11433 } 11434 11435 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11436 throws RemoteException { 11437 long result = 0; 11438 for (File path : paths) { 11439 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11440 } 11441 return result; 11442 } 11443 11444 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11445 for (File path : paths) { 11446 try { 11447 mcs.clearDirectory(path.getAbsolutePath()); 11448 } catch (RemoteException e) { 11449 } 11450 } 11451 } 11452 11453 static class OriginInfo { 11454 /** 11455 * Location where install is coming from, before it has been 11456 * copied/renamed into place. This could be a single monolithic APK 11457 * file, or a cluster directory. This location may be untrusted. 11458 */ 11459 final File file; 11460 final String cid; 11461 11462 /** 11463 * Flag indicating that {@link #file} or {@link #cid} has already been 11464 * staged, meaning downstream users don't need to defensively copy the 11465 * contents. 11466 */ 11467 final boolean staged; 11468 11469 /** 11470 * Flag indicating that {@link #file} or {@link #cid} is an already 11471 * installed app that is being moved. 11472 */ 11473 final boolean existing; 11474 11475 final String resolvedPath; 11476 final File resolvedFile; 11477 11478 static OriginInfo fromNothing() { 11479 return new OriginInfo(null, null, false, false); 11480 } 11481 11482 static OriginInfo fromUntrustedFile(File file) { 11483 return new OriginInfo(file, null, false, false); 11484 } 11485 11486 static OriginInfo fromExistingFile(File file) { 11487 return new OriginInfo(file, null, false, true); 11488 } 11489 11490 static OriginInfo fromStagedFile(File file) { 11491 return new OriginInfo(file, null, true, false); 11492 } 11493 11494 static OriginInfo fromStagedContainer(String cid) { 11495 return new OriginInfo(null, cid, true, false); 11496 } 11497 11498 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11499 this.file = file; 11500 this.cid = cid; 11501 this.staged = staged; 11502 this.existing = existing; 11503 11504 if (cid != null) { 11505 resolvedPath = PackageHelper.getSdDir(cid); 11506 resolvedFile = new File(resolvedPath); 11507 } else if (file != null) { 11508 resolvedPath = file.getAbsolutePath(); 11509 resolvedFile = file; 11510 } else { 11511 resolvedPath = null; 11512 resolvedFile = null; 11513 } 11514 } 11515 } 11516 11517 static class MoveInfo { 11518 final int moveId; 11519 final String fromUuid; 11520 final String toUuid; 11521 final String packageName; 11522 final String dataAppName; 11523 final int appId; 11524 final String seinfo; 11525 final int targetSdkVersion; 11526 11527 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11528 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11529 this.moveId = moveId; 11530 this.fromUuid = fromUuid; 11531 this.toUuid = toUuid; 11532 this.packageName = packageName; 11533 this.dataAppName = dataAppName; 11534 this.appId = appId; 11535 this.seinfo = seinfo; 11536 this.targetSdkVersion = targetSdkVersion; 11537 } 11538 } 11539 11540 static class VerificationInfo { 11541 /** A constant used to indicate that a uid value is not present. */ 11542 public static final int NO_UID = -1; 11543 11544 /** URI referencing where the package was downloaded from. */ 11545 final Uri originatingUri; 11546 11547 /** HTTP referrer URI associated with the originatingURI. */ 11548 final Uri referrer; 11549 11550 /** UID of the application that the install request originated from. */ 11551 final int originatingUid; 11552 11553 /** UID of application requesting the install */ 11554 final int installerUid; 11555 11556 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11557 this.originatingUri = originatingUri; 11558 this.referrer = referrer; 11559 this.originatingUid = originatingUid; 11560 this.installerUid = installerUid; 11561 } 11562 } 11563 11564 class InstallParams extends HandlerParams { 11565 final OriginInfo origin; 11566 final MoveInfo move; 11567 final IPackageInstallObserver2 observer; 11568 int installFlags; 11569 final String installerPackageName; 11570 final String volumeUuid; 11571 private InstallArgs mArgs; 11572 private int mRet; 11573 final String packageAbiOverride; 11574 final String[] grantedRuntimePermissions; 11575 final VerificationInfo verificationInfo; 11576 11577 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11578 int installFlags, String installerPackageName, String volumeUuid, 11579 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11580 String[] grantedPermissions) { 11581 super(user); 11582 this.origin = origin; 11583 this.move = move; 11584 this.observer = observer; 11585 this.installFlags = installFlags; 11586 this.installerPackageName = installerPackageName; 11587 this.volumeUuid = volumeUuid; 11588 this.verificationInfo = verificationInfo; 11589 this.packageAbiOverride = packageAbiOverride; 11590 this.grantedRuntimePermissions = grantedPermissions; 11591 } 11592 11593 @Override 11594 public String toString() { 11595 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11596 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11597 } 11598 11599 private int installLocationPolicy(PackageInfoLite pkgLite) { 11600 String packageName = pkgLite.packageName; 11601 int installLocation = pkgLite.installLocation; 11602 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11603 // reader 11604 synchronized (mPackages) { 11605 // Currently installed package which the new package is attempting to replace or 11606 // null if no such package is installed. 11607 PackageParser.Package installedPkg = mPackages.get(packageName); 11608 // Package which currently owns the data which the new package will own if installed. 11609 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11610 // will be null whereas dataOwnerPkg will contain information about the package 11611 // which was uninstalled while keeping its data. 11612 PackageParser.Package dataOwnerPkg = installedPkg; 11613 if (dataOwnerPkg == null) { 11614 PackageSetting ps = mSettings.mPackages.get(packageName); 11615 if (ps != null) { 11616 dataOwnerPkg = ps.pkg; 11617 } 11618 } 11619 11620 if (dataOwnerPkg != null) { 11621 // If installed, the package will get access to data left on the device by its 11622 // predecessor. As a security measure, this is permited only if this is not a 11623 // version downgrade or if the predecessor package is marked as debuggable and 11624 // a downgrade is explicitly requested. 11625 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11626 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11627 try { 11628 checkDowngrade(dataOwnerPkg, pkgLite); 11629 } catch (PackageManagerException e) { 11630 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11631 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11632 } 11633 } 11634 } 11635 11636 if (installedPkg != null) { 11637 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11638 // Check for updated system application. 11639 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11640 if (onSd) { 11641 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11642 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11643 } 11644 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11645 } else { 11646 if (onSd) { 11647 // Install flag overrides everything. 11648 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11649 } 11650 // If current upgrade specifies particular preference 11651 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11652 // Application explicitly specified internal. 11653 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11654 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11655 // App explictly prefers external. Let policy decide 11656 } else { 11657 // Prefer previous location 11658 if (isExternal(installedPkg)) { 11659 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11660 } 11661 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11662 } 11663 } 11664 } else { 11665 // Invalid install. Return error code 11666 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11667 } 11668 } 11669 } 11670 // All the special cases have been taken care of. 11671 // Return result based on recommended install location. 11672 if (onSd) { 11673 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11674 } 11675 return pkgLite.recommendedInstallLocation; 11676 } 11677 11678 /* 11679 * Invoke remote method to get package information and install 11680 * location values. Override install location based on default 11681 * policy if needed and then create install arguments based 11682 * on the install location. 11683 */ 11684 public void handleStartCopy() throws RemoteException { 11685 int ret = PackageManager.INSTALL_SUCCEEDED; 11686 11687 // If we're already staged, we've firmly committed to an install location 11688 if (origin.staged) { 11689 if (origin.file != null) { 11690 installFlags |= PackageManager.INSTALL_INTERNAL; 11691 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11692 } else if (origin.cid != null) { 11693 installFlags |= PackageManager.INSTALL_EXTERNAL; 11694 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11695 } else { 11696 throw new IllegalStateException("Invalid stage location"); 11697 } 11698 } 11699 11700 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11701 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11702 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11703 PackageInfoLite pkgLite = null; 11704 11705 if (onInt && onSd) { 11706 // Check if both bits are set. 11707 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11708 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11709 } else if (onSd && ephemeral) { 11710 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11711 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11712 } else { 11713 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11714 packageAbiOverride); 11715 11716 if (DEBUG_EPHEMERAL && ephemeral) { 11717 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11718 } 11719 11720 /* 11721 * If we have too little free space, try to free cache 11722 * before giving up. 11723 */ 11724 if (!origin.staged && pkgLite.recommendedInstallLocation 11725 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11726 // TODO: focus freeing disk space on the target device 11727 final StorageManager storage = StorageManager.from(mContext); 11728 final long lowThreshold = storage.getStorageLowBytes( 11729 Environment.getDataDirectory()); 11730 11731 final long sizeBytes = mContainerService.calculateInstalledSize( 11732 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11733 11734 try { 11735 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11736 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11737 installFlags, packageAbiOverride); 11738 } catch (InstallerException e) { 11739 Slog.w(TAG, "Failed to free cache", e); 11740 } 11741 11742 /* 11743 * The cache free must have deleted the file we 11744 * downloaded to install. 11745 * 11746 * TODO: fix the "freeCache" call to not delete 11747 * the file we care about. 11748 */ 11749 if (pkgLite.recommendedInstallLocation 11750 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11751 pkgLite.recommendedInstallLocation 11752 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11753 } 11754 } 11755 } 11756 11757 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11758 int loc = pkgLite.recommendedInstallLocation; 11759 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11760 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11761 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11762 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11763 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11764 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11765 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11766 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11767 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11768 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11769 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11770 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11771 } else { 11772 // Override with defaults if needed. 11773 loc = installLocationPolicy(pkgLite); 11774 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11775 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11776 } else if (!onSd && !onInt) { 11777 // Override install location with flags 11778 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11779 // Set the flag to install on external media. 11780 installFlags |= PackageManager.INSTALL_EXTERNAL; 11781 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11782 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11783 if (DEBUG_EPHEMERAL) { 11784 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11785 } 11786 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11787 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11788 |PackageManager.INSTALL_INTERNAL); 11789 } else { 11790 // Make sure the flag for installing on external 11791 // media is unset 11792 installFlags |= PackageManager.INSTALL_INTERNAL; 11793 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11794 } 11795 } 11796 } 11797 } 11798 11799 final InstallArgs args = createInstallArgs(this); 11800 mArgs = args; 11801 11802 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11803 // TODO: http://b/22976637 11804 // Apps installed for "all" users use the device owner to verify the app 11805 UserHandle verifierUser = getUser(); 11806 if (verifierUser == UserHandle.ALL) { 11807 verifierUser = UserHandle.SYSTEM; 11808 } 11809 11810 /* 11811 * Determine if we have any installed package verifiers. If we 11812 * do, then we'll defer to them to verify the packages. 11813 */ 11814 final int requiredUid = mRequiredVerifierPackage == null ? -1 11815 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11816 verifierUser.getIdentifier()); 11817 if (!origin.existing && requiredUid != -1 11818 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11819 final Intent verification = new Intent( 11820 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11821 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11822 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11823 PACKAGE_MIME_TYPE); 11824 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11825 11826 // Query all live verifiers based on current user state 11827 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11828 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11829 11830 if (DEBUG_VERIFY) { 11831 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11832 + verification.toString() + " with " + pkgLite.verifiers.length 11833 + " optional verifiers"); 11834 } 11835 11836 final int verificationId = mPendingVerificationToken++; 11837 11838 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11839 11840 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11841 installerPackageName); 11842 11843 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11844 installFlags); 11845 11846 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11847 pkgLite.packageName); 11848 11849 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11850 pkgLite.versionCode); 11851 11852 if (verificationInfo != null) { 11853 if (verificationInfo.originatingUri != null) { 11854 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11855 verificationInfo.originatingUri); 11856 } 11857 if (verificationInfo.referrer != null) { 11858 verification.putExtra(Intent.EXTRA_REFERRER, 11859 verificationInfo.referrer); 11860 } 11861 if (verificationInfo.originatingUid >= 0) { 11862 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11863 verificationInfo.originatingUid); 11864 } 11865 if (verificationInfo.installerUid >= 0) { 11866 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11867 verificationInfo.installerUid); 11868 } 11869 } 11870 11871 final PackageVerificationState verificationState = new PackageVerificationState( 11872 requiredUid, args); 11873 11874 mPendingVerification.append(verificationId, verificationState); 11875 11876 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11877 receivers, verificationState); 11878 11879 /* 11880 * If any sufficient verifiers were listed in the package 11881 * manifest, attempt to ask them. 11882 */ 11883 if (sufficientVerifiers != null) { 11884 final int N = sufficientVerifiers.size(); 11885 if (N == 0) { 11886 Slog.i(TAG, "Additional verifiers required, but none installed."); 11887 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11888 } else { 11889 for (int i = 0; i < N; i++) { 11890 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11891 11892 final Intent sufficientIntent = new Intent(verification); 11893 sufficientIntent.setComponent(verifierComponent); 11894 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11895 } 11896 } 11897 } 11898 11899 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11900 mRequiredVerifierPackage, receivers); 11901 if (ret == PackageManager.INSTALL_SUCCEEDED 11902 && mRequiredVerifierPackage != null) { 11903 Trace.asyncTraceBegin( 11904 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11905 /* 11906 * Send the intent to the required verification agent, 11907 * but only start the verification timeout after the 11908 * target BroadcastReceivers have run. 11909 */ 11910 verification.setComponent(requiredVerifierComponent); 11911 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11912 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11913 new BroadcastReceiver() { 11914 @Override 11915 public void onReceive(Context context, Intent intent) { 11916 final Message msg = mHandler 11917 .obtainMessage(CHECK_PENDING_VERIFICATION); 11918 msg.arg1 = verificationId; 11919 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11920 } 11921 }, null, 0, null, null); 11922 11923 /* 11924 * We don't want the copy to proceed until verification 11925 * succeeds, so null out this field. 11926 */ 11927 mArgs = null; 11928 } 11929 } else { 11930 /* 11931 * No package verification is enabled, so immediately start 11932 * the remote call to initiate copy using temporary file. 11933 */ 11934 ret = args.copyApk(mContainerService, true); 11935 } 11936 } 11937 11938 mRet = ret; 11939 } 11940 11941 @Override 11942 void handleReturnCode() { 11943 // If mArgs is null, then MCS couldn't be reached. When it 11944 // reconnects, it will try again to install. At that point, this 11945 // will succeed. 11946 if (mArgs != null) { 11947 processPendingInstall(mArgs, mRet); 11948 } 11949 } 11950 11951 @Override 11952 void handleServiceError() { 11953 mArgs = createInstallArgs(this); 11954 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11955 } 11956 11957 public boolean isForwardLocked() { 11958 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11959 } 11960 } 11961 11962 /** 11963 * Used during creation of InstallArgs 11964 * 11965 * @param installFlags package installation flags 11966 * @return true if should be installed on external storage 11967 */ 11968 private static boolean installOnExternalAsec(int installFlags) { 11969 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11970 return false; 11971 } 11972 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11973 return true; 11974 } 11975 return false; 11976 } 11977 11978 /** 11979 * Used during creation of InstallArgs 11980 * 11981 * @param installFlags package installation flags 11982 * @return true if should be installed as forward locked 11983 */ 11984 private static boolean installForwardLocked(int installFlags) { 11985 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11986 } 11987 11988 private InstallArgs createInstallArgs(InstallParams params) { 11989 if (params.move != null) { 11990 return new MoveInstallArgs(params); 11991 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11992 return new AsecInstallArgs(params); 11993 } else { 11994 return new FileInstallArgs(params); 11995 } 11996 } 11997 11998 /** 11999 * Create args that describe an existing installed package. Typically used 12000 * when cleaning up old installs, or used as a move source. 12001 */ 12002 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12003 String resourcePath, String[] instructionSets) { 12004 final boolean isInAsec; 12005 if (installOnExternalAsec(installFlags)) { 12006 /* Apps on SD card are always in ASEC containers. */ 12007 isInAsec = true; 12008 } else if (installForwardLocked(installFlags) 12009 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12010 /* 12011 * Forward-locked apps are only in ASEC containers if they're the 12012 * new style 12013 */ 12014 isInAsec = true; 12015 } else { 12016 isInAsec = false; 12017 } 12018 12019 if (isInAsec) { 12020 return new AsecInstallArgs(codePath, instructionSets, 12021 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12022 } else { 12023 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12024 } 12025 } 12026 12027 static abstract class InstallArgs { 12028 /** @see InstallParams#origin */ 12029 final OriginInfo origin; 12030 /** @see InstallParams#move */ 12031 final MoveInfo move; 12032 12033 final IPackageInstallObserver2 observer; 12034 // Always refers to PackageManager flags only 12035 final int installFlags; 12036 final String installerPackageName; 12037 final String volumeUuid; 12038 final UserHandle user; 12039 final String abiOverride; 12040 final String[] installGrantPermissions; 12041 /** If non-null, drop an async trace when the install completes */ 12042 final String traceMethod; 12043 final int traceCookie; 12044 12045 // The list of instruction sets supported by this app. This is currently 12046 // only used during the rmdex() phase to clean up resources. We can get rid of this 12047 // if we move dex files under the common app path. 12048 /* nullable */ String[] instructionSets; 12049 12050 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12051 int installFlags, String installerPackageName, String volumeUuid, 12052 UserHandle user, String[] instructionSets, 12053 String abiOverride, String[] installGrantPermissions, 12054 String traceMethod, int traceCookie) { 12055 this.origin = origin; 12056 this.move = move; 12057 this.installFlags = installFlags; 12058 this.observer = observer; 12059 this.installerPackageName = installerPackageName; 12060 this.volumeUuid = volumeUuid; 12061 this.user = user; 12062 this.instructionSets = instructionSets; 12063 this.abiOverride = abiOverride; 12064 this.installGrantPermissions = installGrantPermissions; 12065 this.traceMethod = traceMethod; 12066 this.traceCookie = traceCookie; 12067 } 12068 12069 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12070 abstract int doPreInstall(int status); 12071 12072 /** 12073 * Rename package into final resting place. All paths on the given 12074 * scanned package should be updated to reflect the rename. 12075 */ 12076 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12077 abstract int doPostInstall(int status, int uid); 12078 12079 /** @see PackageSettingBase#codePathString */ 12080 abstract String getCodePath(); 12081 /** @see PackageSettingBase#resourcePathString */ 12082 abstract String getResourcePath(); 12083 12084 // Need installer lock especially for dex file removal. 12085 abstract void cleanUpResourcesLI(); 12086 abstract boolean doPostDeleteLI(boolean delete); 12087 12088 /** 12089 * Called before the source arguments are copied. This is used mostly 12090 * for MoveParams when it needs to read the source file to put it in the 12091 * destination. 12092 */ 12093 int doPreCopy() { 12094 return PackageManager.INSTALL_SUCCEEDED; 12095 } 12096 12097 /** 12098 * Called after the source arguments are copied. This is used mostly for 12099 * MoveParams when it needs to read the source file to put it in the 12100 * destination. 12101 * 12102 * @return 12103 */ 12104 int doPostCopy(int uid) { 12105 return PackageManager.INSTALL_SUCCEEDED; 12106 } 12107 12108 protected boolean isFwdLocked() { 12109 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12110 } 12111 12112 protected boolean isExternalAsec() { 12113 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12114 } 12115 12116 protected boolean isEphemeral() { 12117 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12118 } 12119 12120 UserHandle getUser() { 12121 return user; 12122 } 12123 } 12124 12125 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12126 if (!allCodePaths.isEmpty()) { 12127 if (instructionSets == null) { 12128 throw new IllegalStateException("instructionSet == null"); 12129 } 12130 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12131 for (String codePath : allCodePaths) { 12132 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12133 try { 12134 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12135 } catch (InstallerException ignored) { 12136 } 12137 } 12138 } 12139 } 12140 } 12141 12142 /** 12143 * Logic to handle installation of non-ASEC applications, including copying 12144 * and renaming logic. 12145 */ 12146 class FileInstallArgs extends InstallArgs { 12147 private File codeFile; 12148 private File resourceFile; 12149 12150 // Example topology: 12151 // /data/app/com.example/base.apk 12152 // /data/app/com.example/split_foo.apk 12153 // /data/app/com.example/lib/arm/libfoo.so 12154 // /data/app/com.example/lib/arm64/libfoo.so 12155 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12156 12157 /** New install */ 12158 FileInstallArgs(InstallParams params) { 12159 super(params.origin, params.move, params.observer, params.installFlags, 12160 params.installerPackageName, params.volumeUuid, 12161 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12162 params.grantedRuntimePermissions, 12163 params.traceMethod, params.traceCookie); 12164 if (isFwdLocked()) { 12165 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12166 } 12167 } 12168 12169 /** Existing install */ 12170 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12171 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12172 null, null, null, 0); 12173 this.codeFile = (codePath != null) ? new File(codePath) : null; 12174 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12175 } 12176 12177 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12179 try { 12180 return doCopyApk(imcs, temp); 12181 } finally { 12182 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12183 } 12184 } 12185 12186 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12187 if (origin.staged) { 12188 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12189 codeFile = origin.file; 12190 resourceFile = origin.file; 12191 return PackageManager.INSTALL_SUCCEEDED; 12192 } 12193 12194 try { 12195 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12196 final File tempDir = 12197 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12198 codeFile = tempDir; 12199 resourceFile = tempDir; 12200 } catch (IOException e) { 12201 Slog.w(TAG, "Failed to create copy file: " + e); 12202 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12203 } 12204 12205 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12206 @Override 12207 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12208 if (!FileUtils.isValidExtFilename(name)) { 12209 throw new IllegalArgumentException("Invalid filename: " + name); 12210 } 12211 try { 12212 final File file = new File(codeFile, name); 12213 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12214 O_RDWR | O_CREAT, 0644); 12215 Os.chmod(file.getAbsolutePath(), 0644); 12216 return new ParcelFileDescriptor(fd); 12217 } catch (ErrnoException e) { 12218 throw new RemoteException("Failed to open: " + e.getMessage()); 12219 } 12220 } 12221 }; 12222 12223 int ret = PackageManager.INSTALL_SUCCEEDED; 12224 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12225 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12226 Slog.e(TAG, "Failed to copy package"); 12227 return ret; 12228 } 12229 12230 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12231 NativeLibraryHelper.Handle handle = null; 12232 try { 12233 handle = NativeLibraryHelper.Handle.create(codeFile); 12234 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12235 abiOverride); 12236 } catch (IOException e) { 12237 Slog.e(TAG, "Copying native libraries failed", e); 12238 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12239 } finally { 12240 IoUtils.closeQuietly(handle); 12241 } 12242 12243 return ret; 12244 } 12245 12246 int doPreInstall(int status) { 12247 if (status != PackageManager.INSTALL_SUCCEEDED) { 12248 cleanUp(); 12249 } 12250 return status; 12251 } 12252 12253 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12254 if (status != PackageManager.INSTALL_SUCCEEDED) { 12255 cleanUp(); 12256 return false; 12257 } 12258 12259 final File targetDir = codeFile.getParentFile(); 12260 final File beforeCodeFile = codeFile; 12261 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12262 12263 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12264 try { 12265 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12266 } catch (ErrnoException e) { 12267 Slog.w(TAG, "Failed to rename", e); 12268 return false; 12269 } 12270 12271 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12272 Slog.w(TAG, "Failed to restorecon"); 12273 return false; 12274 } 12275 12276 // Reflect the rename internally 12277 codeFile = afterCodeFile; 12278 resourceFile = afterCodeFile; 12279 12280 // Reflect the rename in scanned details 12281 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12282 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12283 afterCodeFile, pkg.baseCodePath)); 12284 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12285 afterCodeFile, pkg.splitCodePaths)); 12286 12287 // Reflect the rename in app info 12288 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12289 pkg.setApplicationInfoCodePath(pkg.codePath); 12290 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12291 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12292 pkg.setApplicationInfoResourcePath(pkg.codePath); 12293 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12294 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12295 12296 return true; 12297 } 12298 12299 int doPostInstall(int status, int uid) { 12300 if (status != PackageManager.INSTALL_SUCCEEDED) { 12301 cleanUp(); 12302 } 12303 return status; 12304 } 12305 12306 @Override 12307 String getCodePath() { 12308 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12309 } 12310 12311 @Override 12312 String getResourcePath() { 12313 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12314 } 12315 12316 private boolean cleanUp() { 12317 if (codeFile == null || !codeFile.exists()) { 12318 return false; 12319 } 12320 12321 removeCodePathLI(codeFile); 12322 12323 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12324 resourceFile.delete(); 12325 } 12326 12327 return true; 12328 } 12329 12330 void cleanUpResourcesLI() { 12331 // Try enumerating all code paths before deleting 12332 List<String> allCodePaths = Collections.EMPTY_LIST; 12333 if (codeFile != null && codeFile.exists()) { 12334 try { 12335 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12336 allCodePaths = pkg.getAllCodePaths(); 12337 } catch (PackageParserException e) { 12338 // Ignored; we tried our best 12339 } 12340 } 12341 12342 cleanUp(); 12343 removeDexFiles(allCodePaths, instructionSets); 12344 } 12345 12346 boolean doPostDeleteLI(boolean delete) { 12347 // XXX err, shouldn't we respect the delete flag? 12348 cleanUpResourcesLI(); 12349 return true; 12350 } 12351 } 12352 12353 private boolean isAsecExternal(String cid) { 12354 final String asecPath = PackageHelper.getSdFilesystem(cid); 12355 return !asecPath.startsWith(mAsecInternalPath); 12356 } 12357 12358 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12359 PackageManagerException { 12360 if (copyRet < 0) { 12361 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12362 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12363 throw new PackageManagerException(copyRet, message); 12364 } 12365 } 12366 } 12367 12368 /** 12369 * Extract the MountService "container ID" from the full code path of an 12370 * .apk. 12371 */ 12372 static String cidFromCodePath(String fullCodePath) { 12373 int eidx = fullCodePath.lastIndexOf("/"); 12374 String subStr1 = fullCodePath.substring(0, eidx); 12375 int sidx = subStr1.lastIndexOf("/"); 12376 return subStr1.substring(sidx+1, eidx); 12377 } 12378 12379 /** 12380 * Logic to handle installation of ASEC applications, including copying and 12381 * renaming logic. 12382 */ 12383 class AsecInstallArgs extends InstallArgs { 12384 static final String RES_FILE_NAME = "pkg.apk"; 12385 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12386 12387 String cid; 12388 String packagePath; 12389 String resourcePath; 12390 12391 /** New install */ 12392 AsecInstallArgs(InstallParams params) { 12393 super(params.origin, params.move, params.observer, params.installFlags, 12394 params.installerPackageName, params.volumeUuid, 12395 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12396 params.grantedRuntimePermissions, 12397 params.traceMethod, params.traceCookie); 12398 } 12399 12400 /** Existing install */ 12401 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12402 boolean isExternal, boolean isForwardLocked) { 12403 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12404 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12405 instructionSets, null, null, null, 0); 12406 // Hackily pretend we're still looking at a full code path 12407 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12408 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12409 } 12410 12411 // Extract cid from fullCodePath 12412 int eidx = fullCodePath.lastIndexOf("/"); 12413 String subStr1 = fullCodePath.substring(0, eidx); 12414 int sidx = subStr1.lastIndexOf("/"); 12415 cid = subStr1.substring(sidx+1, eidx); 12416 setMountPath(subStr1); 12417 } 12418 12419 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12420 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12421 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12422 instructionSets, null, null, null, 0); 12423 this.cid = cid; 12424 setMountPath(PackageHelper.getSdDir(cid)); 12425 } 12426 12427 void createCopyFile() { 12428 cid = mInstallerService.allocateExternalStageCidLegacy(); 12429 } 12430 12431 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12432 if (origin.staged && origin.cid != null) { 12433 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12434 cid = origin.cid; 12435 setMountPath(PackageHelper.getSdDir(cid)); 12436 return PackageManager.INSTALL_SUCCEEDED; 12437 } 12438 12439 if (temp) { 12440 createCopyFile(); 12441 } else { 12442 /* 12443 * Pre-emptively destroy the container since it's destroyed if 12444 * copying fails due to it existing anyway. 12445 */ 12446 PackageHelper.destroySdDir(cid); 12447 } 12448 12449 final String newMountPath = imcs.copyPackageToContainer( 12450 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12451 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12452 12453 if (newMountPath != null) { 12454 setMountPath(newMountPath); 12455 return PackageManager.INSTALL_SUCCEEDED; 12456 } else { 12457 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12458 } 12459 } 12460 12461 @Override 12462 String getCodePath() { 12463 return packagePath; 12464 } 12465 12466 @Override 12467 String getResourcePath() { 12468 return resourcePath; 12469 } 12470 12471 int doPreInstall(int status) { 12472 if (status != PackageManager.INSTALL_SUCCEEDED) { 12473 // Destroy container 12474 PackageHelper.destroySdDir(cid); 12475 } else { 12476 boolean mounted = PackageHelper.isContainerMounted(cid); 12477 if (!mounted) { 12478 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12479 Process.SYSTEM_UID); 12480 if (newMountPath != null) { 12481 setMountPath(newMountPath); 12482 } else { 12483 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12484 } 12485 } 12486 } 12487 return status; 12488 } 12489 12490 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12491 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12492 String newMountPath = null; 12493 if (PackageHelper.isContainerMounted(cid)) { 12494 // Unmount the container 12495 if (!PackageHelper.unMountSdDir(cid)) { 12496 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12497 return false; 12498 } 12499 } 12500 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12501 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12502 " which might be stale. Will try to clean up."); 12503 // Clean up the stale container and proceed to recreate. 12504 if (!PackageHelper.destroySdDir(newCacheId)) { 12505 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12506 return false; 12507 } 12508 // Successfully cleaned up stale container. Try to rename again. 12509 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12510 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12511 + " inspite of cleaning it up."); 12512 return false; 12513 } 12514 } 12515 if (!PackageHelper.isContainerMounted(newCacheId)) { 12516 Slog.w(TAG, "Mounting container " + newCacheId); 12517 newMountPath = PackageHelper.mountSdDir(newCacheId, 12518 getEncryptKey(), Process.SYSTEM_UID); 12519 } else { 12520 newMountPath = PackageHelper.getSdDir(newCacheId); 12521 } 12522 if (newMountPath == null) { 12523 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12524 return false; 12525 } 12526 Log.i(TAG, "Succesfully renamed " + cid + 12527 " to " + newCacheId + 12528 " at new path: " + newMountPath); 12529 cid = newCacheId; 12530 12531 final File beforeCodeFile = new File(packagePath); 12532 setMountPath(newMountPath); 12533 final File afterCodeFile = new File(packagePath); 12534 12535 // Reflect the rename in scanned details 12536 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12537 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12538 afterCodeFile, pkg.baseCodePath)); 12539 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12540 afterCodeFile, pkg.splitCodePaths)); 12541 12542 // Reflect the rename in app info 12543 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12544 pkg.setApplicationInfoCodePath(pkg.codePath); 12545 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12546 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12547 pkg.setApplicationInfoResourcePath(pkg.codePath); 12548 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12549 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12550 12551 return true; 12552 } 12553 12554 private void setMountPath(String mountPath) { 12555 final File mountFile = new File(mountPath); 12556 12557 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12558 if (monolithicFile.exists()) { 12559 packagePath = monolithicFile.getAbsolutePath(); 12560 if (isFwdLocked()) { 12561 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12562 } else { 12563 resourcePath = packagePath; 12564 } 12565 } else { 12566 packagePath = mountFile.getAbsolutePath(); 12567 resourcePath = packagePath; 12568 } 12569 } 12570 12571 int doPostInstall(int status, int uid) { 12572 if (status != PackageManager.INSTALL_SUCCEEDED) { 12573 cleanUp(); 12574 } else { 12575 final int groupOwner; 12576 final String protectedFile; 12577 if (isFwdLocked()) { 12578 groupOwner = UserHandle.getSharedAppGid(uid); 12579 protectedFile = RES_FILE_NAME; 12580 } else { 12581 groupOwner = -1; 12582 protectedFile = null; 12583 } 12584 12585 if (uid < Process.FIRST_APPLICATION_UID 12586 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12587 Slog.e(TAG, "Failed to finalize " + cid); 12588 PackageHelper.destroySdDir(cid); 12589 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12590 } 12591 12592 boolean mounted = PackageHelper.isContainerMounted(cid); 12593 if (!mounted) { 12594 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12595 } 12596 } 12597 return status; 12598 } 12599 12600 private void cleanUp() { 12601 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12602 12603 // Destroy secure container 12604 PackageHelper.destroySdDir(cid); 12605 } 12606 12607 private List<String> getAllCodePaths() { 12608 final File codeFile = new File(getCodePath()); 12609 if (codeFile != null && codeFile.exists()) { 12610 try { 12611 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12612 return pkg.getAllCodePaths(); 12613 } catch (PackageParserException e) { 12614 // Ignored; we tried our best 12615 } 12616 } 12617 return Collections.EMPTY_LIST; 12618 } 12619 12620 void cleanUpResourcesLI() { 12621 // Enumerate all code paths before deleting 12622 cleanUpResourcesLI(getAllCodePaths()); 12623 } 12624 12625 private void cleanUpResourcesLI(List<String> allCodePaths) { 12626 cleanUp(); 12627 removeDexFiles(allCodePaths, instructionSets); 12628 } 12629 12630 String getPackageName() { 12631 return getAsecPackageName(cid); 12632 } 12633 12634 boolean doPostDeleteLI(boolean delete) { 12635 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12636 final List<String> allCodePaths = getAllCodePaths(); 12637 boolean mounted = PackageHelper.isContainerMounted(cid); 12638 if (mounted) { 12639 // Unmount first 12640 if (PackageHelper.unMountSdDir(cid)) { 12641 mounted = false; 12642 } 12643 } 12644 if (!mounted && delete) { 12645 cleanUpResourcesLI(allCodePaths); 12646 } 12647 return !mounted; 12648 } 12649 12650 @Override 12651 int doPreCopy() { 12652 if (isFwdLocked()) { 12653 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12654 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12655 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12656 } 12657 } 12658 12659 return PackageManager.INSTALL_SUCCEEDED; 12660 } 12661 12662 @Override 12663 int doPostCopy(int uid) { 12664 if (isFwdLocked()) { 12665 if (uid < Process.FIRST_APPLICATION_UID 12666 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12667 RES_FILE_NAME)) { 12668 Slog.e(TAG, "Failed to finalize " + cid); 12669 PackageHelper.destroySdDir(cid); 12670 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12671 } 12672 } 12673 12674 return PackageManager.INSTALL_SUCCEEDED; 12675 } 12676 } 12677 12678 /** 12679 * Logic to handle movement of existing installed applications. 12680 */ 12681 class MoveInstallArgs extends InstallArgs { 12682 private File codeFile; 12683 private File resourceFile; 12684 12685 /** New install */ 12686 MoveInstallArgs(InstallParams params) { 12687 super(params.origin, params.move, params.observer, params.installFlags, 12688 params.installerPackageName, params.volumeUuid, 12689 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12690 params.grantedRuntimePermissions, 12691 params.traceMethod, params.traceCookie); 12692 } 12693 12694 int copyApk(IMediaContainerService imcs, boolean temp) { 12695 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12696 + move.fromUuid + " to " + move.toUuid); 12697 synchronized (mInstaller) { 12698 try { 12699 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12700 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12701 } catch (InstallerException e) { 12702 Slog.w(TAG, "Failed to move app", e); 12703 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12704 } 12705 } 12706 12707 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12708 resourceFile = codeFile; 12709 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12710 12711 return PackageManager.INSTALL_SUCCEEDED; 12712 } 12713 12714 int doPreInstall(int status) { 12715 if (status != PackageManager.INSTALL_SUCCEEDED) { 12716 cleanUp(move.toUuid); 12717 } 12718 return status; 12719 } 12720 12721 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12722 if (status != PackageManager.INSTALL_SUCCEEDED) { 12723 cleanUp(move.toUuid); 12724 return false; 12725 } 12726 12727 // Reflect the move in app info 12728 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12729 pkg.setApplicationInfoCodePath(pkg.codePath); 12730 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12731 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12732 pkg.setApplicationInfoResourcePath(pkg.codePath); 12733 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12734 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12735 12736 return true; 12737 } 12738 12739 int doPostInstall(int status, int uid) { 12740 if (status == PackageManager.INSTALL_SUCCEEDED) { 12741 cleanUp(move.fromUuid); 12742 } else { 12743 cleanUp(move.toUuid); 12744 } 12745 return status; 12746 } 12747 12748 @Override 12749 String getCodePath() { 12750 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12751 } 12752 12753 @Override 12754 String getResourcePath() { 12755 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12756 } 12757 12758 private boolean cleanUp(String volumeUuid) { 12759 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12760 move.dataAppName); 12761 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12762 synchronized (mInstallLock) { 12763 // Clean up both app data and code 12764 removeDataDirsLI(volumeUuid, move.packageName); 12765 removeCodePathLI(codeFile); 12766 } 12767 return true; 12768 } 12769 12770 void cleanUpResourcesLI() { 12771 throw new UnsupportedOperationException(); 12772 } 12773 12774 boolean doPostDeleteLI(boolean delete) { 12775 throw new UnsupportedOperationException(); 12776 } 12777 } 12778 12779 static String getAsecPackageName(String packageCid) { 12780 int idx = packageCid.lastIndexOf("-"); 12781 if (idx == -1) { 12782 return packageCid; 12783 } 12784 return packageCid.substring(0, idx); 12785 } 12786 12787 // Utility method used to create code paths based on package name and available index. 12788 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12789 String idxStr = ""; 12790 int idx = 1; 12791 // Fall back to default value of idx=1 if prefix is not 12792 // part of oldCodePath 12793 if (oldCodePath != null) { 12794 String subStr = oldCodePath; 12795 // Drop the suffix right away 12796 if (suffix != null && subStr.endsWith(suffix)) { 12797 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12798 } 12799 // If oldCodePath already contains prefix find out the 12800 // ending index to either increment or decrement. 12801 int sidx = subStr.lastIndexOf(prefix); 12802 if (sidx != -1) { 12803 subStr = subStr.substring(sidx + prefix.length()); 12804 if (subStr != null) { 12805 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12806 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12807 } 12808 try { 12809 idx = Integer.parseInt(subStr); 12810 if (idx <= 1) { 12811 idx++; 12812 } else { 12813 idx--; 12814 } 12815 } catch(NumberFormatException e) { 12816 } 12817 } 12818 } 12819 } 12820 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12821 return prefix + idxStr; 12822 } 12823 12824 private File getNextCodePath(File targetDir, String packageName) { 12825 int suffix = 1; 12826 File result; 12827 do { 12828 result = new File(targetDir, packageName + "-" + suffix); 12829 suffix++; 12830 } while (result.exists()); 12831 return result; 12832 } 12833 12834 // Utility method that returns the relative package path with respect 12835 // to the installation directory. Like say for /data/data/com.test-1.apk 12836 // string com.test-1 is returned. 12837 static String deriveCodePathName(String codePath) { 12838 if (codePath == null) { 12839 return null; 12840 } 12841 final File codeFile = new File(codePath); 12842 final String name = codeFile.getName(); 12843 if (codeFile.isDirectory()) { 12844 return name; 12845 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12846 final int lastDot = name.lastIndexOf('.'); 12847 return name.substring(0, lastDot); 12848 } else { 12849 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12850 return null; 12851 } 12852 } 12853 12854 static class PackageInstalledInfo { 12855 String name; 12856 int uid; 12857 // The set of users that originally had this package installed. 12858 int[] origUsers; 12859 // The set of users that now have this package installed. 12860 int[] newUsers; 12861 PackageParser.Package pkg; 12862 int returnCode; 12863 String returnMsg; 12864 PackageRemovedInfo removedInfo; 12865 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12866 12867 public void setError(int code, String msg) { 12868 setReturnCode(code); 12869 setReturnMessage(msg); 12870 Slog.w(TAG, msg); 12871 } 12872 12873 public void setError(String msg, PackageParserException e) { 12874 setReturnCode(e.error); 12875 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12876 Slog.w(TAG, msg, e); 12877 } 12878 12879 public void setError(String msg, PackageManagerException e) { 12880 returnCode = e.error; 12881 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12882 Slog.w(TAG, msg, e); 12883 } 12884 12885 public void setReturnCode(int returnCode) { 12886 this.returnCode = returnCode; 12887 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12888 for (int i = 0; i < childCount; i++) { 12889 addedChildPackages.valueAt(i).returnCode = returnCode; 12890 } 12891 } 12892 12893 private void setReturnMessage(String returnMsg) { 12894 this.returnMsg = returnMsg; 12895 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12896 for (int i = 0; i < childCount; i++) { 12897 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12898 } 12899 } 12900 12901 // In some error cases we want to convey more info back to the observer 12902 String origPackage; 12903 String origPermission; 12904 } 12905 12906 /* 12907 * Install a non-existing package. 12908 */ 12909 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12910 UserHandle user, String installerPackageName, String volumeUuid, 12911 PackageInstalledInfo res) { 12912 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12913 12914 // Remember this for later, in case we need to rollback this install 12915 String pkgName = pkg.packageName; 12916 12917 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12918 12919 synchronized(mPackages) { 12920 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12921 // A package with the same name is already installed, though 12922 // it has been renamed to an older name. The package we 12923 // are trying to install should be installed as an update to 12924 // the existing one, but that has not been requested, so bail. 12925 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12926 + " without first uninstalling package running as " 12927 + mSettings.mRenamedPackages.get(pkgName)); 12928 return; 12929 } 12930 if (mPackages.containsKey(pkgName)) { 12931 // Don't allow installation over an existing package with the same name. 12932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12933 + " without first uninstalling."); 12934 return; 12935 } 12936 } 12937 12938 try { 12939 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12940 System.currentTimeMillis(), user); 12941 12942 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12943 12944 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12945 prepareAppDataAfterInstall(newPackage); 12946 12947 } else { 12948 // Remove package from internal structures, but keep around any 12949 // data that might have already existed 12950 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12951 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12952 } 12953 } catch (PackageManagerException e) { 12954 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12955 } 12956 12957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12958 } 12959 12960 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12961 // Can't rotate keys during boot or if sharedUser. 12962 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12963 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12964 return false; 12965 } 12966 // app is using upgradeKeySets; make sure all are valid 12967 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12968 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12969 for (int i = 0; i < upgradeKeySets.length; i++) { 12970 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12971 Slog.wtf(TAG, "Package " 12972 + (oldPs.name != null ? oldPs.name : "<null>") 12973 + " contains upgrade-key-set reference to unknown key-set: " 12974 + upgradeKeySets[i] 12975 + " reverting to signatures check."); 12976 return false; 12977 } 12978 } 12979 return true; 12980 } 12981 12982 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12983 // Upgrade keysets are being used. Determine if new package has a superset of the 12984 // required keys. 12985 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12986 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12987 for (int i = 0; i < upgradeKeySets.length; i++) { 12988 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12989 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12990 return true; 12991 } 12992 } 12993 return false; 12994 } 12995 12996 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12997 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12998 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12999 13000 final PackageParser.Package oldPackage; 13001 final String pkgName = pkg.packageName; 13002 final int[] allUsers; 13003 13004 // First find the old package info and check signatures 13005 synchronized(mPackages) { 13006 oldPackage = mPackages.get(pkgName); 13007 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13008 if (isEphemeral && !oldIsEphemeral) { 13009 // can't downgrade from full to ephemeral 13010 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13011 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13012 return; 13013 } 13014 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13015 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13016 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13017 if (!checkUpgradeKeySetLP(ps, pkg)) { 13018 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13019 "New package not signed by keys specified by upgrade-keysets: " 13020 + pkgName); 13021 return; 13022 } 13023 } else { 13024 // default to original signature matching 13025 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13026 != PackageManager.SIGNATURE_MATCH) { 13027 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13028 "New package has a different signature: " + pkgName); 13029 return; 13030 } 13031 } 13032 13033 // In case of rollback, remember per-user/profile install state 13034 allUsers = sUserManager.getUserIds(); 13035 } 13036 13037 // Update what is removed 13038 res.removedInfo = new PackageRemovedInfo(); 13039 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13040 res.removedInfo.removedPackage = oldPackage.packageName; 13041 res.removedInfo.isUpdate = true; 13042 final int childCount = (oldPackage.childPackages != null) 13043 ? oldPackage.childPackages.size() : 0; 13044 for (int i = 0; i < childCount; i++) { 13045 boolean childPackageUpdated = false; 13046 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13047 if (res.addedChildPackages != null) { 13048 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13049 if (childRes != null) { 13050 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13051 childRes.removedInfo.removedPackage = childPkg.packageName; 13052 childRes.removedInfo.isUpdate = true; 13053 childPackageUpdated = true; 13054 } 13055 } 13056 if (!childPackageUpdated) { 13057 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13058 childRemovedRes.removedPackage = childPkg.packageName; 13059 childRemovedRes.isUpdate = false; 13060 childRemovedRes.dataRemoved = true; 13061 synchronized (mPackages) { 13062 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13063 if (childPs != null) { 13064 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13065 } 13066 } 13067 if (res.removedInfo.removedChildPackages == null) { 13068 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13069 } 13070 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13071 } 13072 } 13073 13074 boolean sysPkg = (isSystemApp(oldPackage)); 13075 if (sysPkg) { 13076 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13077 user, allUsers, installerPackageName, res); 13078 } else { 13079 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13080 user, allUsers, installerPackageName, res); 13081 } 13082 } 13083 13084 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13085 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13086 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13087 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13088 + deletedPackage); 13089 13090 String pkgName = deletedPackage.packageName; 13091 boolean deletedPkg = true; 13092 boolean addedPkg = false; 13093 13094 final long origUpdateTime = (pkg.mExtras != null) 13095 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13096 13097 // First delete the existing package while retaining the data directory 13098 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13099 res.removedInfo, true, pkg)) { 13100 // If the existing package wasn't successfully deleted 13101 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13102 deletedPkg = false; 13103 } else { 13104 // Successfully deleted the old package; proceed with replace. 13105 13106 // If deleted package lived in a container, give users a chance to 13107 // relinquish resources before killing. 13108 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13109 if (DEBUG_INSTALL) { 13110 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13111 } 13112 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13113 final ArrayList<String> pkgList = new ArrayList<String>(1); 13114 pkgList.add(deletedPackage.applicationInfo.packageName); 13115 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13116 } 13117 13118 deleteCodeCacheDirsLI(pkg); 13119 13120 try { 13121 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13122 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13123 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13124 prepareAppDataAfterInstall(newPackage); 13125 addedPkg = true; 13126 } catch (PackageManagerException e) { 13127 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13128 } 13129 } 13130 13131 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13132 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13133 13134 // Revert all internal state mutations and added folders for the failed install 13135 if (addedPkg) { 13136 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13137 res.removedInfo, true, null); 13138 } 13139 13140 // Restore the old package 13141 if (deletedPkg) { 13142 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13143 File restoreFile = new File(deletedPackage.codePath); 13144 // Parse old package 13145 boolean oldExternal = isExternal(deletedPackage); 13146 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13147 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13148 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13149 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13150 try { 13151 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13152 null); 13153 } catch (PackageManagerException e) { 13154 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13155 + e.getMessage()); 13156 return; 13157 } 13158 13159 synchronized (mPackages) { 13160 // Ensure the installer package name up to date 13161 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13162 13163 // Update permissions for restored package 13164 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13165 13166 mSettings.writeLPr(); 13167 } 13168 13169 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13170 } 13171 } else { 13172 synchronized (mPackages) { 13173 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13174 if (ps != null) { 13175 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13176 if (res.removedInfo.removedChildPackages != null) { 13177 final int childCount = res.removedInfo.removedChildPackages.size(); 13178 // Iterate in reverse as we may modify the collection 13179 for (int i = childCount - 1; i >= 0; i--) { 13180 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13181 if (res.addedChildPackages.containsKey(childPackageName)) { 13182 res.removedInfo.removedChildPackages.removeAt(i); 13183 } else { 13184 PackageRemovedInfo childInfo = res.removedInfo 13185 .removedChildPackages.valueAt(i); 13186 childInfo.removedForAllUsers = mPackages.get( 13187 childInfo.removedPackage) == null; 13188 } 13189 } 13190 } 13191 } 13192 } 13193 } 13194 } 13195 13196 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13197 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13198 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13199 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13200 + ", old=" + deletedPackage); 13201 13202 final boolean disabledSystem; 13203 13204 // Set the system/privileged flags as needed 13205 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13206 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13207 != 0) { 13208 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13209 } 13210 13211 // Kill package processes including services, providers, etc. 13212 killPackage(deletedPackage, "replace sys pkg"); 13213 13214 // Remove existing system package 13215 removePackageLI(deletedPackage, true); 13216 13217 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13218 if (!disabledSystem) { 13219 // We didn't need to disable the .apk as a current system package, 13220 // which means we are replacing another update that is already 13221 // installed. We need to make sure to delete the older one's .apk. 13222 res.removedInfo.args = createInstallArgsForExisting(0, 13223 deletedPackage.applicationInfo.getCodePath(), 13224 deletedPackage.applicationInfo.getResourcePath(), 13225 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13226 } else { 13227 res.removedInfo.args = null; 13228 } 13229 13230 // Successfully disabled the old package. Now proceed with re-installation 13231 deleteCodeCacheDirsLI(pkg); 13232 13233 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13234 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13235 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13236 13237 PackageParser.Package newPackage = null; 13238 try { 13239 // Add the package to the internal data structures 13240 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13241 13242 // Set the update and install times 13243 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13244 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13245 System.currentTimeMillis()); 13246 13247 // Check for shared user id changes 13248 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13249 deletedPackage, newPackage); 13250 if (invalidPackageName != null) { 13251 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13252 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13253 + " to " + invalidPackageName); 13254 } 13255 13256 // Update the package dynamic state if succeeded 13257 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13258 // Now that the install succeeded make sure we remove data 13259 // directories for any child package the update removed. 13260 final int deletedChildCount = (deletedPackage.childPackages != null) 13261 ? deletedPackage.childPackages.size() : 0; 13262 final int newChildCount = (newPackage.childPackages != null) 13263 ? newPackage.childPackages.size() : 0; 13264 for (int i = 0; i < deletedChildCount; i++) { 13265 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13266 boolean childPackageDeleted = true; 13267 for (int j = 0; j < newChildCount; j++) { 13268 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13269 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13270 childPackageDeleted = false; 13271 break; 13272 } 13273 } 13274 if (childPackageDeleted) { 13275 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13276 deletedChildPkg.packageName); 13277 if (ps != null && res.removedInfo.removedChildPackages != null) { 13278 PackageRemovedInfo removedChildRes = res.removedInfo 13279 .removedChildPackages.get(deletedChildPkg.packageName); 13280 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13281 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13282 } 13283 } 13284 } 13285 13286 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13287 prepareAppDataAfterInstall(newPackage); 13288 } 13289 } catch (PackageManagerException e) { 13290 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13291 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13292 } 13293 13294 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13295 // Re installation failed. Restore old information 13296 // Remove new pkg information 13297 if (newPackage != null) { 13298 removeInstalledPackageLI(newPackage, true); 13299 } 13300 // Add back the old system package 13301 try { 13302 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13303 } catch (PackageManagerException e) { 13304 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13305 } 13306 13307 synchronized (mPackages) { 13308 if (disabledSystem) { 13309 enableSystemPackageLPw(deletedPackage); 13310 } 13311 13312 // Ensure the installer package name up to date 13313 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13314 13315 // Update permissions for restored package 13316 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13317 13318 mSettings.writeLPr(); 13319 } 13320 13321 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13322 + " after failed upgrade"); 13323 } 13324 } 13325 13326 /** 13327 * Checks whether the parent or any of the child packages have a change shared 13328 * user. For a package to be a valid update the shred users of the parent and 13329 * the children should match. We may later support changing child shared users. 13330 * @param oldPkg The updated package. 13331 * @param newPkg The update package. 13332 * @return The shared user that change between the versions. 13333 */ 13334 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13335 PackageParser.Package newPkg) { 13336 // Check parent shared user 13337 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13338 return newPkg.packageName; 13339 } 13340 // Check child shared users 13341 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13342 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13343 for (int i = 0; i < newChildCount; i++) { 13344 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13345 // If this child was present, did it have the same shared user? 13346 for (int j = 0; j < oldChildCount; j++) { 13347 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13348 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13349 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13350 return newChildPkg.packageName; 13351 } 13352 } 13353 } 13354 return null; 13355 } 13356 13357 private void removeNativeBinariesLI(PackageSetting ps) { 13358 // Remove the lib path for the parent package 13359 if (ps != null) { 13360 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13361 // Remove the lib path for the child packages 13362 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13363 for (int i = 0; i < childCount; i++) { 13364 PackageSetting childPs = null; 13365 synchronized (mPackages) { 13366 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13367 } 13368 if (childPs != null) { 13369 NativeLibraryHelper.removeNativeBinariesLI(childPs 13370 .legacyNativeLibraryPathString); 13371 } 13372 } 13373 } 13374 } 13375 13376 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13377 // Enable the parent package 13378 mSettings.enableSystemPackageLPw(pkg.packageName); 13379 // Enable the child packages 13380 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13381 for (int i = 0; i < childCount; i++) { 13382 PackageParser.Package childPkg = pkg.childPackages.get(i); 13383 mSettings.enableSystemPackageLPw(childPkg.packageName); 13384 } 13385 } 13386 13387 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13388 PackageParser.Package newPkg) { 13389 // Disable the parent package (parent always replaced) 13390 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13391 // Disable the child packages 13392 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13393 for (int i = 0; i < childCount; i++) { 13394 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13395 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13396 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13397 } 13398 return disabled; 13399 } 13400 13401 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13402 String installerPackageName) { 13403 // Enable the parent package 13404 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13405 // Enable the child packages 13406 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13407 for (int i = 0; i < childCount; i++) { 13408 PackageParser.Package childPkg = pkg.childPackages.get(i); 13409 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13410 } 13411 } 13412 13413 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13414 // Collect all used permissions in the UID 13415 ArraySet<String> usedPermissions = new ArraySet<>(); 13416 final int packageCount = su.packages.size(); 13417 for (int i = 0; i < packageCount; i++) { 13418 PackageSetting ps = su.packages.valueAt(i); 13419 if (ps.pkg == null) { 13420 continue; 13421 } 13422 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13423 for (int j = 0; j < requestedPermCount; j++) { 13424 String permission = ps.pkg.requestedPermissions.get(j); 13425 BasePermission bp = mSettings.mPermissions.get(permission); 13426 if (bp != null) { 13427 usedPermissions.add(permission); 13428 } 13429 } 13430 } 13431 13432 PermissionsState permissionsState = su.getPermissionsState(); 13433 // Prune install permissions 13434 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13435 final int installPermCount = installPermStates.size(); 13436 for (int i = installPermCount - 1; i >= 0; i--) { 13437 PermissionState permissionState = installPermStates.get(i); 13438 if (!usedPermissions.contains(permissionState.getName())) { 13439 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13440 if (bp != null) { 13441 permissionsState.revokeInstallPermission(bp); 13442 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13443 PackageManager.MASK_PERMISSION_FLAGS, 0); 13444 } 13445 } 13446 } 13447 13448 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13449 13450 // Prune runtime permissions 13451 for (int userId : allUserIds) { 13452 List<PermissionState> runtimePermStates = permissionsState 13453 .getRuntimePermissionStates(userId); 13454 final int runtimePermCount = runtimePermStates.size(); 13455 for (int i = runtimePermCount - 1; i >= 0; i--) { 13456 PermissionState permissionState = runtimePermStates.get(i); 13457 if (!usedPermissions.contains(permissionState.getName())) { 13458 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13459 if (bp != null) { 13460 permissionsState.revokeRuntimePermission(bp, userId); 13461 permissionsState.updatePermissionFlags(bp, userId, 13462 PackageManager.MASK_PERMISSION_FLAGS, 0); 13463 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13464 runtimePermissionChangedUserIds, userId); 13465 } 13466 } 13467 } 13468 } 13469 13470 return runtimePermissionChangedUserIds; 13471 } 13472 13473 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13474 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13475 // Update the parent package setting 13476 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13477 res, user); 13478 // Update the child packages setting 13479 final int childCount = (newPackage.childPackages != null) 13480 ? newPackage.childPackages.size() : 0; 13481 for (int i = 0; i < childCount; i++) { 13482 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13483 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13484 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13485 childRes.origUsers, childRes, user); 13486 } 13487 } 13488 13489 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13490 String installerPackageName, int[] allUsers, int[] installedForUsers, 13491 PackageInstalledInfo res, UserHandle user) { 13492 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13493 13494 String pkgName = newPackage.packageName; 13495 synchronized (mPackages) { 13496 //write settings. the installStatus will be incomplete at this stage. 13497 //note that the new package setting would have already been 13498 //added to mPackages. It hasn't been persisted yet. 13499 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13501 mSettings.writeLPr(); 13502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13503 } 13504 13505 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13506 synchronized (mPackages) { 13507 updatePermissionsLPw(newPackage.packageName, newPackage, 13508 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13509 ? UPDATE_PERMISSIONS_ALL : 0)); 13510 // For system-bundled packages, we assume that installing an upgraded version 13511 // of the package implies that the user actually wants to run that new code, 13512 // so we enable the package. 13513 PackageSetting ps = mSettings.mPackages.get(pkgName); 13514 final int userId = user.getIdentifier(); 13515 if (ps != null) { 13516 if (isSystemApp(newPackage)) { 13517 if (DEBUG_INSTALL) { 13518 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13519 } 13520 // Enable system package for requested users 13521 if (res.origUsers != null) { 13522 for (int origUserId : res.origUsers) { 13523 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13524 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13525 origUserId, installerPackageName); 13526 } 13527 } 13528 } 13529 // Also convey the prior install/uninstall state 13530 if (allUsers != null && installedForUsers != null) { 13531 for (int currentUserId : allUsers) { 13532 final boolean installed = ArrayUtils.contains( 13533 installedForUsers, currentUserId); 13534 if (DEBUG_INSTALL) { 13535 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13536 } 13537 ps.setInstalled(installed, currentUserId); 13538 } 13539 // these install state changes will be persisted in the 13540 // upcoming call to mSettings.writeLPr(). 13541 } 13542 } 13543 // It's implied that when a user requests installation, they want the app to be 13544 // installed and enabled. 13545 if (userId != UserHandle.USER_ALL) { 13546 ps.setInstalled(true, userId); 13547 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13548 } 13549 } 13550 res.name = pkgName; 13551 res.uid = newPackage.applicationInfo.uid; 13552 res.pkg = newPackage; 13553 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13554 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13555 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13556 //to update install status 13557 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13558 mSettings.writeLPr(); 13559 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13560 } 13561 13562 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13563 } 13564 13565 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13566 try { 13567 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13568 installPackageLI(args, res); 13569 } finally { 13570 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13571 } 13572 } 13573 13574 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13575 final int installFlags = args.installFlags; 13576 final String installerPackageName = args.installerPackageName; 13577 final String volumeUuid = args.volumeUuid; 13578 final File tmpPackageFile = new File(args.getCodePath()); 13579 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13580 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13581 || (args.volumeUuid != null)); 13582 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13583 boolean replace = false; 13584 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13585 if (args.move != null) { 13586 // moving a complete application; perform an initial scan on the new install location 13587 scanFlags |= SCAN_INITIAL; 13588 } 13589 13590 // Result object to be returned 13591 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13592 13593 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13594 13595 // Sanity check 13596 if (ephemeral && (forwardLocked || onExternal)) { 13597 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13598 + " external=" + onExternal); 13599 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13600 return; 13601 } 13602 13603 // Retrieve PackageSettings and parse package 13604 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13605 | PackageParser.PARSE_ENFORCE_CODE 13606 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13607 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13608 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13609 PackageParser pp = new PackageParser(); 13610 pp.setSeparateProcesses(mSeparateProcesses); 13611 pp.setDisplayMetrics(mMetrics); 13612 13613 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13614 final PackageParser.Package pkg; 13615 try { 13616 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13617 } catch (PackageParserException e) { 13618 res.setError("Failed parse during installPackageLI", e); 13619 return; 13620 } finally { 13621 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13622 } 13623 13624 // If we are installing a clustered package add results for the children 13625 if (pkg.childPackages != null) { 13626 synchronized (mPackages) { 13627 final int childCount = pkg.childPackages.size(); 13628 for (int i = 0; i < childCount; i++) { 13629 PackageParser.Package childPkg = pkg.childPackages.get(i); 13630 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13631 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13632 childRes.pkg = childPkg; 13633 childRes.name = childPkg.packageName; 13634 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13635 if (childPs != null) { 13636 childRes.origUsers = childPs.queryInstalledUsers( 13637 sUserManager.getUserIds(), true); 13638 } 13639 if ((mPackages.containsKey(childPkg.packageName))) { 13640 childRes.removedInfo = new PackageRemovedInfo(); 13641 childRes.removedInfo.removedPackage = childPkg.packageName; 13642 } 13643 if (res.addedChildPackages == null) { 13644 res.addedChildPackages = new ArrayMap<>(); 13645 } 13646 res.addedChildPackages.put(childPkg.packageName, childRes); 13647 } 13648 } 13649 } 13650 13651 // If package doesn't declare API override, mark that we have an install 13652 // time CPU ABI override. 13653 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13654 pkg.cpuAbiOverride = args.abiOverride; 13655 } 13656 13657 String pkgName = res.name = pkg.packageName; 13658 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13659 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13660 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13661 return; 13662 } 13663 } 13664 13665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13666 try { 13667 PackageParser.collectCertificates(pkg, parseFlags); 13668 } catch (PackageParserException e) { 13669 res.setError("Failed collect during installPackageLI", e); 13670 return; 13671 } finally { 13672 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13673 } 13674 13675 // Get rid of all references to package scan path via parser. 13676 pp = null; 13677 String oldCodePath = null; 13678 boolean systemApp = false; 13679 synchronized (mPackages) { 13680 // Check if installing already existing package 13681 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13682 String oldName = mSettings.mRenamedPackages.get(pkgName); 13683 if (pkg.mOriginalPackages != null 13684 && pkg.mOriginalPackages.contains(oldName) 13685 && mPackages.containsKey(oldName)) { 13686 // This package is derived from an original package, 13687 // and this device has been updating from that original 13688 // name. We must continue using the original name, so 13689 // rename the new package here. 13690 pkg.setPackageName(oldName); 13691 pkgName = pkg.packageName; 13692 replace = true; 13693 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13694 + oldName + " pkgName=" + pkgName); 13695 } else if (mPackages.containsKey(pkgName)) { 13696 // This package, under its official name, already exists 13697 // on the device; we should replace it. 13698 replace = true; 13699 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13700 } 13701 13702 // Child packages are installed through the parent package 13703 if (pkg.parentPackage != null) { 13704 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13705 "Package " + pkg.packageName + " is child of package " 13706 + pkg.parentPackage.parentPackage + ". Child packages " 13707 + "can be updated only through the parent package."); 13708 return; 13709 } 13710 13711 if (replace) { 13712 // Prevent apps opting out from runtime permissions 13713 PackageParser.Package oldPackage = mPackages.get(pkgName); 13714 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13715 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13716 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13717 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13718 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13719 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13720 + " doesn't support runtime permissions but the old" 13721 + " target SDK " + oldTargetSdk + " does."); 13722 return; 13723 } 13724 13725 // Prevent installing of child packages 13726 if (oldPackage.parentPackage != null) { 13727 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13728 "Package " + pkg.packageName + " is child of package " 13729 + oldPackage.parentPackage + ". Child packages " 13730 + "can be updated only through the parent package."); 13731 return; 13732 } 13733 } 13734 } 13735 13736 PackageSetting ps = mSettings.mPackages.get(pkgName); 13737 if (ps != null) { 13738 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13739 13740 // Quick sanity check that we're signed correctly if updating; 13741 // we'll check this again later when scanning, but we want to 13742 // bail early here before tripping over redefined permissions. 13743 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13744 if (!checkUpgradeKeySetLP(ps, pkg)) { 13745 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13746 + pkg.packageName + " upgrade keys do not match the " 13747 + "previously installed version"); 13748 return; 13749 } 13750 } else { 13751 try { 13752 verifySignaturesLP(ps, pkg); 13753 } catch (PackageManagerException e) { 13754 res.setError(e.error, e.getMessage()); 13755 return; 13756 } 13757 } 13758 13759 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13760 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13761 systemApp = (ps.pkg.applicationInfo.flags & 13762 ApplicationInfo.FLAG_SYSTEM) != 0; 13763 } 13764 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13765 } 13766 13767 // Check whether the newly-scanned package wants to define an already-defined perm 13768 int N = pkg.permissions.size(); 13769 for (int i = N-1; i >= 0; i--) { 13770 PackageParser.Permission perm = pkg.permissions.get(i); 13771 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13772 if (bp != null) { 13773 // If the defining package is signed with our cert, it's okay. This 13774 // also includes the "updating the same package" case, of course. 13775 // "updating same package" could also involve key-rotation. 13776 final boolean sigsOk; 13777 if (bp.sourcePackage.equals(pkg.packageName) 13778 && (bp.packageSetting instanceof PackageSetting) 13779 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13780 scanFlags))) { 13781 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13782 } else { 13783 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13784 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13785 } 13786 if (!sigsOk) { 13787 // If the owning package is the system itself, we log but allow 13788 // install to proceed; we fail the install on all other permission 13789 // redefinitions. 13790 if (!bp.sourcePackage.equals("android")) { 13791 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13792 + pkg.packageName + " attempting to redeclare permission " 13793 + perm.info.name + " already owned by " + bp.sourcePackage); 13794 res.origPermission = perm.info.name; 13795 res.origPackage = bp.sourcePackage; 13796 return; 13797 } else { 13798 Slog.w(TAG, "Package " + pkg.packageName 13799 + " attempting to redeclare system permission " 13800 + perm.info.name + "; ignoring new declaration"); 13801 pkg.permissions.remove(i); 13802 } 13803 } 13804 } 13805 } 13806 } 13807 13808 if (systemApp) { 13809 if (onExternal) { 13810 // Abort update; system app can't be replaced with app on sdcard 13811 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13812 "Cannot install updates to system apps on sdcard"); 13813 return; 13814 } else if (ephemeral) { 13815 // Abort update; system app can't be replaced with an ephemeral app 13816 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13817 "Cannot update a system app with an ephemeral app"); 13818 return; 13819 } 13820 } 13821 13822 if (args.move != null) { 13823 // We did an in-place move, so dex is ready to roll 13824 scanFlags |= SCAN_NO_DEX; 13825 scanFlags |= SCAN_MOVE; 13826 13827 synchronized (mPackages) { 13828 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13829 if (ps == null) { 13830 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13831 "Missing settings for moved package " + pkgName); 13832 } 13833 13834 // We moved the entire application as-is, so bring over the 13835 // previously derived ABI information. 13836 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13837 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13838 } 13839 13840 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13841 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13842 scanFlags |= SCAN_NO_DEX; 13843 13844 try { 13845 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13846 args.abiOverride : pkg.cpuAbiOverride); 13847 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13848 true /* extract libs */); 13849 } catch (PackageManagerException pme) { 13850 Slog.e(TAG, "Error deriving application ABI", pme); 13851 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13852 return; 13853 } 13854 13855 // Extract package to save the VM unzipping the APK in memory during 13856 // launch. Only do this if profile-guided compilation is enabled because 13857 // otherwise BackgroundDexOptService will not dexopt the package later. 13858 if (mUseJitProfiles) { 13859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13860 // Do not run PackageDexOptimizer through the local performDexOpt 13861 // method because `pkg` is not in `mPackages` yet. 13862 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13863 false /* useProfiles */, true /* extractOnly */); 13864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13865 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13866 String msg = "Extracking package failed for " + pkgName; 13867 res.setError(INSTALL_FAILED_DEXOPT, msg); 13868 return; 13869 } 13870 } 13871 } 13872 13873 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13874 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13875 return; 13876 } 13877 13878 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13879 13880 if (replace) { 13881 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13882 installerPackageName, res); 13883 } else { 13884 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13885 args.user, installerPackageName, volumeUuid, res); 13886 } 13887 synchronized (mPackages) { 13888 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13889 if (ps != null) { 13890 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13891 } 13892 13893 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13894 for (int i = 0; i < childCount; i++) { 13895 PackageParser.Package childPkg = pkg.childPackages.get(i); 13896 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13897 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13898 if (childPs != null) { 13899 childRes.newUsers = childPs.queryInstalledUsers( 13900 sUserManager.getUserIds(), true); 13901 } 13902 } 13903 } 13904 } 13905 13906 private void startIntentFilterVerifications(int userId, boolean replacing, 13907 PackageParser.Package pkg) { 13908 if (mIntentFilterVerifierComponent == null) { 13909 Slog.w(TAG, "No IntentFilter verification will not be done as " 13910 + "there is no IntentFilterVerifier available!"); 13911 return; 13912 } 13913 13914 final int verifierUid = getPackageUid( 13915 mIntentFilterVerifierComponent.getPackageName(), 13916 MATCH_DEBUG_TRIAGED_MISSING, 13917 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13918 13919 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13920 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13921 mHandler.sendMessage(msg); 13922 13923 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13924 for (int i = 0; i < childCount; i++) { 13925 PackageParser.Package childPkg = pkg.childPackages.get(i); 13926 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13927 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13928 mHandler.sendMessage(msg); 13929 } 13930 } 13931 13932 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13933 PackageParser.Package pkg) { 13934 int size = pkg.activities.size(); 13935 if (size == 0) { 13936 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13937 "No activity, so no need to verify any IntentFilter!"); 13938 return; 13939 } 13940 13941 final boolean hasDomainURLs = hasDomainURLs(pkg); 13942 if (!hasDomainURLs) { 13943 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13944 "No domain URLs, so no need to verify any IntentFilter!"); 13945 return; 13946 } 13947 13948 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13949 + " if any IntentFilter from the " + size 13950 + " Activities needs verification ..."); 13951 13952 int count = 0; 13953 final String packageName = pkg.packageName; 13954 13955 synchronized (mPackages) { 13956 // If this is a new install and we see that we've already run verification for this 13957 // package, we have nothing to do: it means the state was restored from backup. 13958 if (!replacing) { 13959 IntentFilterVerificationInfo ivi = 13960 mSettings.getIntentFilterVerificationLPr(packageName); 13961 if (ivi != null) { 13962 if (DEBUG_DOMAIN_VERIFICATION) { 13963 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13964 + ivi.getStatusString()); 13965 } 13966 return; 13967 } 13968 } 13969 13970 // If any filters need to be verified, then all need to be. 13971 boolean needToVerify = false; 13972 for (PackageParser.Activity a : pkg.activities) { 13973 for (ActivityIntentInfo filter : a.intents) { 13974 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13975 if (DEBUG_DOMAIN_VERIFICATION) { 13976 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13977 } 13978 needToVerify = true; 13979 break; 13980 } 13981 } 13982 } 13983 13984 if (needToVerify) { 13985 final int verificationId = mIntentFilterVerificationToken++; 13986 for (PackageParser.Activity a : pkg.activities) { 13987 for (ActivityIntentInfo filter : a.intents) { 13988 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13989 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13990 "Verification needed for IntentFilter:" + filter.toString()); 13991 mIntentFilterVerifier.addOneIntentFilterVerification( 13992 verifierUid, userId, verificationId, filter, packageName); 13993 count++; 13994 } 13995 } 13996 } 13997 } 13998 } 13999 14000 if (count > 0) { 14001 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14002 + " IntentFilter verification" + (count > 1 ? "s" : "") 14003 + " for userId:" + userId); 14004 mIntentFilterVerifier.startVerifications(userId); 14005 } else { 14006 if (DEBUG_DOMAIN_VERIFICATION) { 14007 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14008 } 14009 } 14010 } 14011 14012 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14013 final ComponentName cn = filter.activity.getComponentName(); 14014 final String packageName = cn.getPackageName(); 14015 14016 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14017 packageName); 14018 if (ivi == null) { 14019 return true; 14020 } 14021 int status = ivi.getStatus(); 14022 switch (status) { 14023 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14024 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14025 return true; 14026 14027 default: 14028 // Nothing to do 14029 return false; 14030 } 14031 } 14032 14033 private static boolean isMultiArch(ApplicationInfo info) { 14034 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14035 } 14036 14037 private static boolean isExternal(PackageParser.Package pkg) { 14038 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14039 } 14040 14041 private static boolean isExternal(PackageSetting ps) { 14042 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14043 } 14044 14045 private static boolean isEphemeral(PackageParser.Package pkg) { 14046 return pkg.applicationInfo.isEphemeralApp(); 14047 } 14048 14049 private static boolean isEphemeral(PackageSetting ps) { 14050 return ps.pkg != null && isEphemeral(ps.pkg); 14051 } 14052 14053 private static boolean isSystemApp(PackageParser.Package pkg) { 14054 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14055 } 14056 14057 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14058 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14059 } 14060 14061 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14062 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14063 } 14064 14065 private static boolean isSystemApp(PackageSetting ps) { 14066 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14067 } 14068 14069 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14070 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14071 } 14072 14073 private int packageFlagsToInstallFlags(PackageSetting ps) { 14074 int installFlags = 0; 14075 if (isEphemeral(ps)) { 14076 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14077 } 14078 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14079 // This existing package was an external ASEC install when we have 14080 // the external flag without a UUID 14081 installFlags |= PackageManager.INSTALL_EXTERNAL; 14082 } 14083 if (ps.isForwardLocked()) { 14084 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14085 } 14086 return installFlags; 14087 } 14088 14089 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14090 if (isExternal(pkg)) { 14091 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14092 return StorageManager.UUID_PRIMARY_PHYSICAL; 14093 } else { 14094 return pkg.volumeUuid; 14095 } 14096 } else { 14097 return StorageManager.UUID_PRIVATE_INTERNAL; 14098 } 14099 } 14100 14101 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14102 if (isExternal(pkg)) { 14103 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14104 return mSettings.getExternalVersion(); 14105 } else { 14106 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14107 } 14108 } else { 14109 return mSettings.getInternalVersion(); 14110 } 14111 } 14112 14113 private void deleteTempPackageFiles() { 14114 final FilenameFilter filter = new FilenameFilter() { 14115 public boolean accept(File dir, String name) { 14116 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14117 } 14118 }; 14119 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14120 file.delete(); 14121 } 14122 } 14123 14124 @Override 14125 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14126 int flags) { 14127 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14128 flags); 14129 } 14130 14131 @Override 14132 public void deletePackage(final String packageName, 14133 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14134 mContext.enforceCallingOrSelfPermission( 14135 android.Manifest.permission.DELETE_PACKAGES, null); 14136 Preconditions.checkNotNull(packageName); 14137 Preconditions.checkNotNull(observer); 14138 final int uid = Binder.getCallingUid(); 14139 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14140 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14141 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14142 mContext.enforceCallingOrSelfPermission( 14143 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14144 "deletePackage for user " + userId); 14145 } 14146 14147 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14148 try { 14149 observer.onPackageDeleted(packageName, 14150 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14151 } catch (RemoteException re) { 14152 } 14153 return; 14154 } 14155 14156 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14157 try { 14158 observer.onPackageDeleted(packageName, 14159 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14160 } catch (RemoteException re) { 14161 } 14162 return; 14163 } 14164 14165 if (DEBUG_REMOVE) { 14166 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14167 + " deleteAllUsers: " + deleteAllUsers ); 14168 } 14169 // Queue up an async operation since the package deletion may take a little while. 14170 mHandler.post(new Runnable() { 14171 public void run() { 14172 mHandler.removeCallbacks(this); 14173 int returnCode; 14174 if (!deleteAllUsers) { 14175 returnCode = deletePackageX(packageName, userId, flags); 14176 } else { 14177 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14178 // If nobody is blocking uninstall, proceed with delete for all users 14179 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14180 returnCode = deletePackageX(packageName, userId, flags); 14181 } else { 14182 // Otherwise uninstall individually for users with blockUninstalls=false 14183 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14184 for (int userId : users) { 14185 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14186 returnCode = deletePackageX(packageName, userId, userFlags); 14187 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14188 Slog.w(TAG, "Package delete failed for user " + userId 14189 + ", returnCode " + returnCode); 14190 } 14191 } 14192 } 14193 // The app has only been marked uninstalled for certain users. 14194 // We still need to report that delete was blocked 14195 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14196 } 14197 } 14198 try { 14199 observer.onPackageDeleted(packageName, returnCode, null); 14200 } catch (RemoteException e) { 14201 Log.i(TAG, "Observer no longer exists."); 14202 } //end catch 14203 } //end run 14204 }); 14205 } 14206 14207 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14208 int[] result = EMPTY_INT_ARRAY; 14209 for (int userId : userIds) { 14210 if (getBlockUninstallForUser(packageName, userId)) { 14211 result = ArrayUtils.appendInt(result, userId); 14212 } 14213 } 14214 return result; 14215 } 14216 14217 @Override 14218 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14219 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14220 } 14221 14222 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14223 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14224 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14225 try { 14226 if (dpm != null) { 14227 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14228 /* callingUserOnly =*/ false); 14229 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14230 : deviceOwnerComponentName.getPackageName(); 14231 // Does the package contains the device owner? 14232 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14233 // this check is probably not needed, since DO should be registered as a device 14234 // admin on some user too. (Original bug for this: b/17657954) 14235 if (packageName.equals(deviceOwnerPackageName)) { 14236 return true; 14237 } 14238 // Does it contain a device admin for any user? 14239 int[] users; 14240 if (userId == UserHandle.USER_ALL) { 14241 users = sUserManager.getUserIds(); 14242 } else { 14243 users = new int[]{userId}; 14244 } 14245 for (int i = 0; i < users.length; ++i) { 14246 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14247 return true; 14248 } 14249 } 14250 } 14251 } catch (RemoteException e) { 14252 } 14253 return false; 14254 } 14255 14256 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14257 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14258 } 14259 14260 /** 14261 * This method is an internal method that could be get invoked either 14262 * to delete an installed package or to clean up a failed installation. 14263 * After deleting an installed package, a broadcast is sent to notify any 14264 * listeners that the package has been installed. For cleaning up a failed 14265 * installation, the broadcast is not necessary since the package's 14266 * installation wouldn't have sent the initial broadcast either 14267 * The key steps in deleting a package are 14268 * deleting the package information in internal structures like mPackages, 14269 * deleting the packages base directories through installd 14270 * updating mSettings to reflect current status 14271 * persisting settings for later use 14272 * sending a broadcast if necessary 14273 */ 14274 private int deletePackageX(String packageName, int userId, int flags) { 14275 final PackageRemovedInfo info = new PackageRemovedInfo(); 14276 final boolean res; 14277 14278 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14279 ? UserHandle.ALL : new UserHandle(userId); 14280 14281 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14282 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14283 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14284 } 14285 14286 PackageSetting uninstalledPs = null; 14287 14288 // for the uninstall-updates case and restricted profiles, remember the per- 14289 // user handle installed state 14290 int[] allUsers; 14291 synchronized (mPackages) { 14292 uninstalledPs = mSettings.mPackages.get(packageName); 14293 if (uninstalledPs == null) { 14294 Slog.w(TAG, "Not removing non-existent package " + packageName); 14295 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14296 } 14297 allUsers = sUserManager.getUserIds(); 14298 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14299 } 14300 14301 synchronized (mInstallLock) { 14302 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14303 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14304 flags | REMOVE_CHATTY, info, true, null); 14305 synchronized (mPackages) { 14306 if (res) { 14307 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14308 } 14309 } 14310 } 14311 14312 if (res) { 14313 info.sendPackageRemovedBroadcasts(); 14314 info.sendSystemPackageUpdatedBroadcasts(); 14315 info.sendSystemPackageAppearedBroadcasts(); 14316 } 14317 // Force a gc here. 14318 Runtime.getRuntime().gc(); 14319 // Delete the resources here after sending the broadcast to let 14320 // other processes clean up before deleting resources. 14321 if (info.args != null) { 14322 synchronized (mInstallLock) { 14323 info.args.doPostDeleteLI(true); 14324 } 14325 } 14326 14327 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14328 } 14329 14330 class PackageRemovedInfo { 14331 String removedPackage; 14332 int uid = -1; 14333 int removedAppId = -1; 14334 int[] origUsers; 14335 int[] removedUsers = null; 14336 boolean isRemovedPackageSystemUpdate = false; 14337 boolean isUpdate; 14338 boolean dataRemoved; 14339 boolean removedForAllUsers; 14340 // Clean up resources deleted packages. 14341 InstallArgs args = null; 14342 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14343 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14344 14345 void sendPackageRemovedBroadcasts() { 14346 sendPackageRemovedBroadcastInternal(); 14347 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14348 for (int i = 0; i < childCount; i++) { 14349 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14350 childInfo.sendPackageRemovedBroadcastInternal(); 14351 } 14352 } 14353 14354 void sendSystemPackageUpdatedBroadcasts() { 14355 if (isRemovedPackageSystemUpdate) { 14356 sendSystemPackageUpdatedBroadcastsInternal(); 14357 final int childCount = (removedChildPackages != null) 14358 ? removedChildPackages.size() : 0; 14359 for (int i = 0; i < childCount; i++) { 14360 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14361 if (childInfo.isRemovedPackageSystemUpdate) { 14362 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14363 } 14364 } 14365 } 14366 } 14367 14368 void sendSystemPackageAppearedBroadcasts() { 14369 final int packageCount = (appearedChildPackages != null) 14370 ? appearedChildPackages.size() : 0; 14371 for (int i = 0; i < packageCount; i++) { 14372 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14373 for (int userId : installedInfo.newUsers) { 14374 sendPackageAddedForUser(installedInfo.name, true, 14375 UserHandle.getAppId(installedInfo.uid), userId); 14376 } 14377 } 14378 } 14379 14380 private void sendSystemPackageUpdatedBroadcastsInternal() { 14381 Bundle extras = new Bundle(2); 14382 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14383 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14384 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14385 extras, 0, null, null, null); 14386 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14387 extras, 0, null, null, null); 14388 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14389 null, 0, removedPackage, null, null); 14390 } 14391 14392 private void sendPackageRemovedBroadcastInternal() { 14393 Bundle extras = new Bundle(2); 14394 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14395 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14396 if (isUpdate || isRemovedPackageSystemUpdate) { 14397 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14398 } 14399 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14400 if (removedPackage != null) { 14401 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14402 extras, 0, null, null, removedUsers); 14403 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14404 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14405 removedPackage, extras, 0, null, null, removedUsers); 14406 } 14407 } 14408 if (removedAppId >= 0) { 14409 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14410 removedUsers); 14411 } 14412 } 14413 } 14414 14415 /* 14416 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14417 * flag is not set, the data directory is removed as well. 14418 * make sure this flag is set for partially installed apps. If not its meaningless to 14419 * delete a partially installed application. 14420 */ 14421 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14422 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14423 String packageName = ps.name; 14424 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14425 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14426 // Retrieve object to delete permissions for shared user later on 14427 final PackageSetting deletedPs; 14428 // reader 14429 synchronized (mPackages) { 14430 deletedPs = mSettings.mPackages.get(packageName); 14431 if (outInfo != null) { 14432 outInfo.removedPackage = packageName; 14433 outInfo.removedUsers = deletedPs != null 14434 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14435 : null; 14436 } 14437 } 14438 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14439 removeDataDirsLI(ps.volumeUuid, packageName); 14440 if (outInfo != null) { 14441 outInfo.dataRemoved = true; 14442 } 14443 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14444 } 14445 // writer 14446 synchronized (mPackages) { 14447 if (deletedPs != null) { 14448 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14449 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14450 clearDefaultBrowserIfNeeded(packageName); 14451 if (outInfo != null) { 14452 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14453 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14454 } 14455 updatePermissionsLPw(deletedPs.name, null, 0); 14456 if (deletedPs.sharedUser != null) { 14457 // Remove permissions associated with package. Since runtime 14458 // permissions are per user we have to kill the removed package 14459 // or packages running under the shared user of the removed 14460 // package if revoking the permissions requested only by the removed 14461 // package is successful and this causes a change in gids. 14462 for (int userId : UserManagerService.getInstance().getUserIds()) { 14463 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14464 userId); 14465 if (userIdToKill == UserHandle.USER_ALL 14466 || userIdToKill >= UserHandle.USER_SYSTEM) { 14467 // If gids changed for this user, kill all affected packages. 14468 mHandler.post(new Runnable() { 14469 @Override 14470 public void run() { 14471 // This has to happen with no lock held. 14472 killApplication(deletedPs.name, deletedPs.appId, 14473 KILL_APP_REASON_GIDS_CHANGED); 14474 } 14475 }); 14476 break; 14477 } 14478 } 14479 } 14480 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14481 } 14482 // make sure to preserve per-user disabled state if this removal was just 14483 // a downgrade of a system app to the factory package 14484 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14485 if (DEBUG_REMOVE) { 14486 Slog.d(TAG, "Propagating install state across downgrade"); 14487 } 14488 for (int userId : allUserHandles) { 14489 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14490 if (DEBUG_REMOVE) { 14491 Slog.d(TAG, " user " + userId + " => " + installed); 14492 } 14493 ps.setInstalled(installed, userId); 14494 } 14495 } 14496 } 14497 // can downgrade to reader 14498 if (writeSettings) { 14499 // Save settings now 14500 mSettings.writeLPr(); 14501 } 14502 } 14503 if (outInfo != null) { 14504 // A user ID was deleted here. Go through all users and remove it 14505 // from KeyStore. 14506 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14507 } 14508 } 14509 14510 static boolean locationIsPrivileged(File path) { 14511 try { 14512 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14513 .getCanonicalPath(); 14514 return path.getCanonicalPath().startsWith(privilegedAppDir); 14515 } catch (IOException e) { 14516 Slog.e(TAG, "Unable to access code path " + path); 14517 } 14518 return false; 14519 } 14520 14521 /* 14522 * Tries to delete system package. 14523 */ 14524 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14525 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14526 boolean writeSettings) { 14527 if (deletedPs.parentPackageName != null) { 14528 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14529 return false; 14530 } 14531 14532 final boolean applyUserRestrictions 14533 = (allUserHandles != null) && (outInfo.origUsers != null); 14534 final PackageSetting disabledPs; 14535 // Confirm if the system package has been updated 14536 // An updated system app can be deleted. This will also have to restore 14537 // the system pkg from system partition 14538 // reader 14539 synchronized (mPackages) { 14540 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14541 } 14542 14543 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14544 + " disabledPs=" + disabledPs); 14545 14546 if (disabledPs == null) { 14547 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14548 return false; 14549 } else if (DEBUG_REMOVE) { 14550 Slog.d(TAG, "Deleting system pkg from data partition"); 14551 } 14552 14553 if (DEBUG_REMOVE) { 14554 if (applyUserRestrictions) { 14555 Slog.d(TAG, "Remembering install states:"); 14556 for (int userId : allUserHandles) { 14557 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14558 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14559 } 14560 } 14561 } 14562 14563 // Delete the updated package 14564 outInfo.isRemovedPackageSystemUpdate = true; 14565 if (outInfo.removedChildPackages != null) { 14566 final int childCount = (deletedPs.childPackageNames != null) 14567 ? deletedPs.childPackageNames.size() : 0; 14568 for (int i = 0; i < childCount; i++) { 14569 String childPackageName = deletedPs.childPackageNames.get(i); 14570 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14571 .contains(childPackageName)) { 14572 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14573 childPackageName); 14574 if (childInfo != null) { 14575 childInfo.isRemovedPackageSystemUpdate = true; 14576 } 14577 } 14578 } 14579 } 14580 14581 if (disabledPs.versionCode < deletedPs.versionCode) { 14582 // Delete data for downgrades 14583 flags &= ~PackageManager.DELETE_KEEP_DATA; 14584 } else { 14585 // Preserve data by setting flag 14586 flags |= PackageManager.DELETE_KEEP_DATA; 14587 } 14588 14589 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14590 outInfo, writeSettings, disabledPs.pkg); 14591 if (!ret) { 14592 return false; 14593 } 14594 14595 // writer 14596 synchronized (mPackages) { 14597 // Reinstate the old system package 14598 enableSystemPackageLPw(disabledPs.pkg); 14599 // Remove any native libraries from the upgraded package. 14600 removeNativeBinariesLI(deletedPs); 14601 } 14602 14603 // Install the system package 14604 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14605 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14606 if (locationIsPrivileged(disabledPs.codePath)) { 14607 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14608 } 14609 14610 final PackageParser.Package newPkg; 14611 try { 14612 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14613 } catch (PackageManagerException e) { 14614 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14615 + e.getMessage()); 14616 return false; 14617 } 14618 14619 prepareAppDataAfterInstall(newPkg); 14620 14621 // writer 14622 synchronized (mPackages) { 14623 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14624 14625 // Propagate the permissions state as we do not want to drop on the floor 14626 // runtime permissions. The update permissions method below will take 14627 // care of removing obsolete permissions and grant install permissions. 14628 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14629 updatePermissionsLPw(newPkg.packageName, newPkg, 14630 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14631 14632 if (applyUserRestrictions) { 14633 if (DEBUG_REMOVE) { 14634 Slog.d(TAG, "Propagating install state across reinstall"); 14635 } 14636 for (int userId : allUserHandles) { 14637 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14638 if (DEBUG_REMOVE) { 14639 Slog.d(TAG, " user " + userId + " => " + installed); 14640 } 14641 ps.setInstalled(installed, userId); 14642 14643 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14644 } 14645 // Regardless of writeSettings we need to ensure that this restriction 14646 // state propagation is persisted 14647 mSettings.writeAllUsersPackageRestrictionsLPr(); 14648 } 14649 // can downgrade to reader here 14650 if (writeSettings) { 14651 mSettings.writeLPr(); 14652 } 14653 } 14654 return true; 14655 } 14656 14657 private boolean deleteInstalledPackageLI(PackageSetting ps, 14658 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14659 PackageRemovedInfo outInfo, boolean writeSettings, 14660 PackageParser.Package replacingPackage) { 14661 synchronized (mPackages) { 14662 if (outInfo != null) { 14663 outInfo.uid = ps.appId; 14664 } 14665 14666 if (outInfo != null && outInfo.removedChildPackages != null) { 14667 final int childCount = (ps.childPackageNames != null) 14668 ? ps.childPackageNames.size() : 0; 14669 for (int i = 0; i < childCount; i++) { 14670 String childPackageName = ps.childPackageNames.get(i); 14671 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14672 if (childPs == null) { 14673 return false; 14674 } 14675 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14676 childPackageName); 14677 if (childInfo != null) { 14678 childInfo.uid = childPs.appId; 14679 } 14680 } 14681 } 14682 } 14683 14684 // Delete package data from internal structures and also remove data if flag is set 14685 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14686 14687 // Delete the child packages data 14688 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14689 for (int i = 0; i < childCount; i++) { 14690 PackageSetting childPs; 14691 synchronized (mPackages) { 14692 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14693 } 14694 if (childPs != null) { 14695 PackageRemovedInfo childOutInfo = (outInfo != null 14696 && outInfo.removedChildPackages != null) 14697 ? outInfo.removedChildPackages.get(childPs.name) : null; 14698 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14699 && (replacingPackage != null 14700 && !replacingPackage.hasChildPackage(childPs.name)) 14701 ? flags & ~DELETE_KEEP_DATA : flags; 14702 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14703 deleteFlags, writeSettings); 14704 } 14705 } 14706 14707 // Delete application code and resources only for parent packages 14708 if (ps.parentPackageName == null) { 14709 if (deleteCodeAndResources && (outInfo != null)) { 14710 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14711 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14712 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14713 } 14714 } 14715 14716 return true; 14717 } 14718 14719 @Override 14720 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14721 int userId) { 14722 mContext.enforceCallingOrSelfPermission( 14723 android.Manifest.permission.DELETE_PACKAGES, null); 14724 synchronized (mPackages) { 14725 PackageSetting ps = mSettings.mPackages.get(packageName); 14726 if (ps == null) { 14727 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14728 return false; 14729 } 14730 if (!ps.getInstalled(userId)) { 14731 // Can't block uninstall for an app that is not installed or enabled. 14732 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14733 return false; 14734 } 14735 ps.setBlockUninstall(blockUninstall, userId); 14736 mSettings.writePackageRestrictionsLPr(userId); 14737 } 14738 return true; 14739 } 14740 14741 @Override 14742 public boolean getBlockUninstallForUser(String packageName, int userId) { 14743 synchronized (mPackages) { 14744 PackageSetting ps = mSettings.mPackages.get(packageName); 14745 if (ps == null) { 14746 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14747 return false; 14748 } 14749 return ps.getBlockUninstall(userId); 14750 } 14751 } 14752 14753 @Override 14754 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14755 int callingUid = Binder.getCallingUid(); 14756 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14757 throw new SecurityException( 14758 "setRequiredForSystemUser can only be run by the system or root"); 14759 } 14760 synchronized (mPackages) { 14761 PackageSetting ps = mSettings.mPackages.get(packageName); 14762 if (ps == null) { 14763 Log.w(TAG, "Package doesn't exist: " + packageName); 14764 return false; 14765 } 14766 if (systemUserApp) { 14767 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14768 } else { 14769 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14770 } 14771 mSettings.writeLPr(); 14772 } 14773 return true; 14774 } 14775 14776 /* 14777 * This method handles package deletion in general 14778 */ 14779 private boolean deletePackageLI(String packageName, UserHandle user, 14780 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14781 PackageRemovedInfo outInfo, boolean writeSettings, 14782 PackageParser.Package replacingPackage) { 14783 if (packageName == null) { 14784 Slog.w(TAG, "Attempt to delete null packageName."); 14785 return false; 14786 } 14787 14788 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14789 14790 PackageSetting ps; 14791 14792 synchronized (mPackages) { 14793 ps = mSettings.mPackages.get(packageName); 14794 if (ps == null) { 14795 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14796 return false; 14797 } 14798 14799 if (ps.parentPackageName != null && (!isSystemApp(ps) 14800 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14801 if (DEBUG_REMOVE) { 14802 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14803 + ((user == null) ? UserHandle.USER_ALL : user)); 14804 } 14805 final int removedUserId = (user != null) ? user.getIdentifier() 14806 : UserHandle.USER_ALL; 14807 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14808 return false; 14809 } 14810 markPackageUninstalledForUserLPw(ps, user); 14811 scheduleWritePackageRestrictionsLocked(user); 14812 return true; 14813 } 14814 } 14815 14816 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14817 && user.getIdentifier() != UserHandle.USER_ALL)) { 14818 // The caller is asking that the package only be deleted for a single 14819 // user. To do this, we just mark its uninstalled state and delete 14820 // its data. If this is a system app, we only allow this to happen if 14821 // they have set the special DELETE_SYSTEM_APP which requests different 14822 // semantics than normal for uninstalling system apps. 14823 markPackageUninstalledForUserLPw(ps, user); 14824 14825 if (!isSystemApp(ps)) { 14826 // Do not uninstall the APK if an app should be cached 14827 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14828 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14829 // Other user still have this package installed, so all 14830 // we need to do is clear this user's data and save that 14831 // it is uninstalled. 14832 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14833 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14834 return false; 14835 } 14836 scheduleWritePackageRestrictionsLocked(user); 14837 return true; 14838 } else { 14839 // We need to set it back to 'installed' so the uninstall 14840 // broadcasts will be sent correctly. 14841 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14842 ps.setInstalled(true, user.getIdentifier()); 14843 } 14844 } else { 14845 // This is a system app, so we assume that the 14846 // other users still have this package installed, so all 14847 // we need to do is clear this user's data and save that 14848 // it is uninstalled. 14849 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14850 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14851 return false; 14852 } 14853 scheduleWritePackageRestrictionsLocked(user); 14854 return true; 14855 } 14856 } 14857 14858 // If we are deleting a composite package for all users, keep track 14859 // of result for each child. 14860 if (ps.childPackageNames != null && outInfo != null) { 14861 synchronized (mPackages) { 14862 final int childCount = ps.childPackageNames.size(); 14863 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14864 for (int i = 0; i < childCount; i++) { 14865 String childPackageName = ps.childPackageNames.get(i); 14866 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14867 childInfo.removedPackage = childPackageName; 14868 outInfo.removedChildPackages.put(childPackageName, childInfo); 14869 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14870 if (childPs != null) { 14871 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14872 } 14873 } 14874 } 14875 } 14876 14877 boolean ret = false; 14878 if (isSystemApp(ps)) { 14879 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14880 // When an updated system application is deleted we delete the existing resources 14881 // as well and fall back to existing code in system partition 14882 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14883 } else { 14884 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14885 // Kill application pre-emptively especially for apps on sd. 14886 killApplication(packageName, ps.appId, "uninstall pkg"); 14887 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14888 outInfo, writeSettings, replacingPackage); 14889 } 14890 14891 // Take a note whether we deleted the package for all users 14892 if (outInfo != null) { 14893 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14894 if (outInfo.removedChildPackages != null) { 14895 synchronized (mPackages) { 14896 final int childCount = outInfo.removedChildPackages.size(); 14897 for (int i = 0; i < childCount; i++) { 14898 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14899 if (childInfo != null) { 14900 childInfo.removedForAllUsers = mPackages.get( 14901 childInfo.removedPackage) == null; 14902 } 14903 } 14904 } 14905 } 14906 // If we uninstalled an update to a system app there may be some 14907 // child packages that appeared as they are declared in the system 14908 // app but were not declared in the update. 14909 if (isSystemApp(ps)) { 14910 synchronized (mPackages) { 14911 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14912 final int childCount = (updatedPs.childPackageNames != null) 14913 ? updatedPs.childPackageNames.size() : 0; 14914 for (int i = 0; i < childCount; i++) { 14915 String childPackageName = updatedPs.childPackageNames.get(i); 14916 if (outInfo.removedChildPackages == null 14917 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14918 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14919 if (childPs == null) { 14920 continue; 14921 } 14922 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14923 installRes.name = childPackageName; 14924 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14925 installRes.pkg = mPackages.get(childPackageName); 14926 installRes.uid = childPs.pkg.applicationInfo.uid; 14927 if (outInfo.appearedChildPackages == null) { 14928 outInfo.appearedChildPackages = new ArrayMap<>(); 14929 } 14930 outInfo.appearedChildPackages.put(childPackageName, installRes); 14931 } 14932 } 14933 } 14934 } 14935 } 14936 14937 return ret; 14938 } 14939 14940 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14941 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14942 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14943 for (int nextUserId : userIds) { 14944 if (DEBUG_REMOVE) { 14945 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14946 } 14947 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14948 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14949 false /*hidden*/, false /*suspended*/, null, null, null, 14950 false /*blockUninstall*/, 14951 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14952 } 14953 } 14954 14955 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14956 PackageRemovedInfo outInfo) { 14957 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14958 : new int[] {userId}; 14959 for (int nextUserId : userIds) { 14960 if (DEBUG_REMOVE) { 14961 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14962 + nextUserId); 14963 } 14964 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14965 try { 14966 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14967 } catch (InstallerException e) { 14968 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14969 return false; 14970 } 14971 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14972 schedulePackageCleaning(ps.name, nextUserId, false); 14973 synchronized (mPackages) { 14974 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14975 scheduleWritePackageRestrictionsLocked(nextUserId); 14976 } 14977 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14978 } 14979 } 14980 14981 if (outInfo != null) { 14982 outInfo.removedPackage = ps.name; 14983 outInfo.removedAppId = ps.appId; 14984 outInfo.removedUsers = userIds; 14985 } 14986 14987 return true; 14988 } 14989 14990 private final class ClearStorageConnection implements ServiceConnection { 14991 IMediaContainerService mContainerService; 14992 14993 @Override 14994 public void onServiceConnected(ComponentName name, IBinder service) { 14995 synchronized (this) { 14996 mContainerService = IMediaContainerService.Stub.asInterface(service); 14997 notifyAll(); 14998 } 14999 } 15000 15001 @Override 15002 public void onServiceDisconnected(ComponentName name) { 15003 } 15004 } 15005 15006 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15007 final boolean mounted; 15008 if (Environment.isExternalStorageEmulated()) { 15009 mounted = true; 15010 } else { 15011 final String status = Environment.getExternalStorageState(); 15012 15013 mounted = status.equals(Environment.MEDIA_MOUNTED) 15014 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15015 } 15016 15017 if (!mounted) { 15018 return; 15019 } 15020 15021 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15022 int[] users; 15023 if (userId == UserHandle.USER_ALL) { 15024 users = sUserManager.getUserIds(); 15025 } else { 15026 users = new int[] { userId }; 15027 } 15028 final ClearStorageConnection conn = new ClearStorageConnection(); 15029 if (mContext.bindServiceAsUser( 15030 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15031 try { 15032 for (int curUser : users) { 15033 long timeout = SystemClock.uptimeMillis() + 5000; 15034 synchronized (conn) { 15035 long now = SystemClock.uptimeMillis(); 15036 while (conn.mContainerService == null && now < timeout) { 15037 try { 15038 conn.wait(timeout - now); 15039 } catch (InterruptedException e) { 15040 } 15041 } 15042 } 15043 if (conn.mContainerService == null) { 15044 return; 15045 } 15046 15047 final UserEnvironment userEnv = new UserEnvironment(curUser); 15048 clearDirectory(conn.mContainerService, 15049 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15050 if (allData) { 15051 clearDirectory(conn.mContainerService, 15052 userEnv.buildExternalStorageAppDataDirs(packageName)); 15053 clearDirectory(conn.mContainerService, 15054 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15055 } 15056 } 15057 } finally { 15058 mContext.unbindService(conn); 15059 } 15060 } 15061 } 15062 15063 @Override 15064 public void clearApplicationUserData(final String packageName, 15065 final IPackageDataObserver observer, final int userId) { 15066 mContext.enforceCallingOrSelfPermission( 15067 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15069 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15070 // Queue up an async operation since the package deletion may take a little while. 15071 mHandler.post(new Runnable() { 15072 public void run() { 15073 mHandler.removeCallbacks(this); 15074 final boolean succeeded; 15075 synchronized (mInstallLock) { 15076 succeeded = clearApplicationUserDataLI(packageName, userId); 15077 } 15078 clearExternalStorageDataSync(packageName, userId, true); 15079 if (succeeded) { 15080 // invoke DeviceStorageMonitor's update method to clear any notifications 15081 DeviceStorageMonitorInternal 15082 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15083 if (dsm != null) { 15084 dsm.checkMemory(); 15085 } 15086 } 15087 if(observer != null) { 15088 try { 15089 observer.onRemoveCompleted(packageName, succeeded); 15090 } catch (RemoteException e) { 15091 Log.i(TAG, "Observer no longer exists."); 15092 } 15093 } //end if observer 15094 } //end run 15095 }); 15096 } 15097 15098 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15099 if (packageName == null) { 15100 Slog.w(TAG, "Attempt to delete null packageName."); 15101 return false; 15102 } 15103 15104 // Try finding details about the requested package 15105 PackageParser.Package pkg; 15106 synchronized (mPackages) { 15107 pkg = mPackages.get(packageName); 15108 if (pkg == null) { 15109 final PackageSetting ps = mSettings.mPackages.get(packageName); 15110 if (ps != null) { 15111 pkg = ps.pkg; 15112 } 15113 } 15114 15115 if (pkg == null) { 15116 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15117 return false; 15118 } 15119 15120 PackageSetting ps = (PackageSetting) pkg.mExtras; 15121 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15122 } 15123 15124 // Always delete data directories for package, even if we found no other 15125 // record of app. This helps users recover from UID mismatches without 15126 // resorting to a full data wipe. 15127 // TODO: triage flags as part of 26466827 15128 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15129 try { 15130 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15131 } catch (InstallerException e) { 15132 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15133 return false; 15134 } 15135 15136 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15137 removeKeystoreDataIfNeeded(userId, appId); 15138 15139 // Create a native library symlink only if we have native libraries 15140 // and if the native libraries are 32 bit libraries. We do not provide 15141 // this symlink for 64 bit libraries. 15142 if (pkg.applicationInfo.primaryCpuAbi != null && 15143 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15144 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15145 try { 15146 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15147 nativeLibPath, userId); 15148 } catch (InstallerException e) { 15149 Slog.w(TAG, "Failed linking native library dir", e); 15150 return false; 15151 } 15152 } 15153 15154 return true; 15155 } 15156 15157 /** 15158 * Reverts user permission state changes (permissions and flags) in 15159 * all packages for a given user. 15160 * 15161 * @param userId The device user for which to do a reset. 15162 */ 15163 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15164 final int packageCount = mPackages.size(); 15165 for (int i = 0; i < packageCount; i++) { 15166 PackageParser.Package pkg = mPackages.valueAt(i); 15167 PackageSetting ps = (PackageSetting) pkg.mExtras; 15168 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15169 } 15170 } 15171 15172 /** 15173 * Reverts user permission state changes (permissions and flags). 15174 * 15175 * @param ps The package for which to reset. 15176 * @param userId The device user for which to do a reset. 15177 */ 15178 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15179 final PackageSetting ps, final int userId) { 15180 if (ps.pkg == null) { 15181 return; 15182 } 15183 15184 // These are flags that can change base on user actions. 15185 final int userSettableMask = FLAG_PERMISSION_USER_SET 15186 | FLAG_PERMISSION_USER_FIXED 15187 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15188 | FLAG_PERMISSION_REVIEW_REQUIRED; 15189 15190 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15191 | FLAG_PERMISSION_POLICY_FIXED; 15192 15193 boolean writeInstallPermissions = false; 15194 boolean writeRuntimePermissions = false; 15195 15196 final int permissionCount = ps.pkg.requestedPermissions.size(); 15197 for (int i = 0; i < permissionCount; i++) { 15198 String permission = ps.pkg.requestedPermissions.get(i); 15199 15200 BasePermission bp = mSettings.mPermissions.get(permission); 15201 if (bp == null) { 15202 continue; 15203 } 15204 15205 // If shared user we just reset the state to which only this app contributed. 15206 if (ps.sharedUser != null) { 15207 boolean used = false; 15208 final int packageCount = ps.sharedUser.packages.size(); 15209 for (int j = 0; j < packageCount; j++) { 15210 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15211 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15212 && pkg.pkg.requestedPermissions.contains(permission)) { 15213 used = true; 15214 break; 15215 } 15216 } 15217 if (used) { 15218 continue; 15219 } 15220 } 15221 15222 PermissionsState permissionsState = ps.getPermissionsState(); 15223 15224 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15225 15226 // Always clear the user settable flags. 15227 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15228 bp.name) != null; 15229 // If permission review is enabled and this is a legacy app, mark the 15230 // permission as requiring a review as this is the initial state. 15231 int flags = 0; 15232 if (Build.PERMISSIONS_REVIEW_REQUIRED 15233 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15234 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15235 } 15236 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15237 if (hasInstallState) { 15238 writeInstallPermissions = true; 15239 } else { 15240 writeRuntimePermissions = true; 15241 } 15242 } 15243 15244 // Below is only runtime permission handling. 15245 if (!bp.isRuntime()) { 15246 continue; 15247 } 15248 15249 // Never clobber system or policy. 15250 if ((oldFlags & policyOrSystemFlags) != 0) { 15251 continue; 15252 } 15253 15254 // If this permission was granted by default, make sure it is. 15255 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15256 if (permissionsState.grantRuntimePermission(bp, userId) 15257 != PERMISSION_OPERATION_FAILURE) { 15258 writeRuntimePermissions = true; 15259 } 15260 // If permission review is enabled the permissions for a legacy apps 15261 // are represented as constantly granted runtime ones, so don't revoke. 15262 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15263 // Otherwise, reset the permission. 15264 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15265 switch (revokeResult) { 15266 case PERMISSION_OPERATION_SUCCESS: { 15267 writeRuntimePermissions = true; 15268 } break; 15269 15270 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15271 writeRuntimePermissions = true; 15272 final int appId = ps.appId; 15273 mHandler.post(new Runnable() { 15274 @Override 15275 public void run() { 15276 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15277 } 15278 }); 15279 } break; 15280 } 15281 } 15282 } 15283 15284 // Synchronously write as we are taking permissions away. 15285 if (writeRuntimePermissions) { 15286 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15287 } 15288 15289 // Synchronously write as we are taking permissions away. 15290 if (writeInstallPermissions) { 15291 mSettings.writeLPr(); 15292 } 15293 } 15294 15295 /** 15296 * Remove entries from the keystore daemon. Will only remove it if the 15297 * {@code appId} is valid. 15298 */ 15299 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15300 if (appId < 0) { 15301 return; 15302 } 15303 15304 final KeyStore keyStore = KeyStore.getInstance(); 15305 if (keyStore != null) { 15306 if (userId == UserHandle.USER_ALL) { 15307 for (final int individual : sUserManager.getUserIds()) { 15308 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15309 } 15310 } else { 15311 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15312 } 15313 } else { 15314 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15315 } 15316 } 15317 15318 @Override 15319 public void deleteApplicationCacheFiles(final String packageName, 15320 final IPackageDataObserver observer) { 15321 mContext.enforceCallingOrSelfPermission( 15322 android.Manifest.permission.DELETE_CACHE_FILES, null); 15323 // Queue up an async operation since the package deletion may take a little while. 15324 final int userId = UserHandle.getCallingUserId(); 15325 mHandler.post(new Runnable() { 15326 public void run() { 15327 mHandler.removeCallbacks(this); 15328 final boolean succeded; 15329 synchronized (mInstallLock) { 15330 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15331 } 15332 clearExternalStorageDataSync(packageName, userId, false); 15333 if (observer != null) { 15334 try { 15335 observer.onRemoveCompleted(packageName, succeded); 15336 } catch (RemoteException e) { 15337 Log.i(TAG, "Observer no longer exists."); 15338 } 15339 } //end if observer 15340 } //end run 15341 }); 15342 } 15343 15344 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15345 if (packageName == null) { 15346 Slog.w(TAG, "Attempt to delete null packageName."); 15347 return false; 15348 } 15349 PackageParser.Package p; 15350 synchronized (mPackages) { 15351 p = mPackages.get(packageName); 15352 } 15353 if (p == null) { 15354 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15355 return false; 15356 } 15357 final ApplicationInfo applicationInfo = p.applicationInfo; 15358 if (applicationInfo == null) { 15359 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15360 return false; 15361 } 15362 // TODO: triage flags as part of 26466827 15363 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15364 try { 15365 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15366 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15367 } catch (InstallerException e) { 15368 Slog.w(TAG, "Couldn't remove cache files for package " 15369 + packageName + " u" + userId, e); 15370 return false; 15371 } 15372 return true; 15373 } 15374 15375 @Override 15376 public void getPackageSizeInfo(final String packageName, int userHandle, 15377 final IPackageStatsObserver observer) { 15378 mContext.enforceCallingOrSelfPermission( 15379 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15380 if (packageName == null) { 15381 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15382 } 15383 15384 PackageStats stats = new PackageStats(packageName, userHandle); 15385 15386 /* 15387 * Queue up an async operation since the package measurement may take a 15388 * little while. 15389 */ 15390 Message msg = mHandler.obtainMessage(INIT_COPY); 15391 msg.obj = new MeasureParams(stats, observer); 15392 mHandler.sendMessage(msg); 15393 } 15394 15395 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15396 PackageStats pStats) { 15397 if (packageName == null) { 15398 Slog.w(TAG, "Attempt to get size of null packageName."); 15399 return false; 15400 } 15401 PackageParser.Package p; 15402 boolean dataOnly = false; 15403 String libDirRoot = null; 15404 String asecPath = null; 15405 PackageSetting ps = null; 15406 synchronized (mPackages) { 15407 p = mPackages.get(packageName); 15408 ps = mSettings.mPackages.get(packageName); 15409 if(p == null) { 15410 dataOnly = true; 15411 if((ps == null) || (ps.pkg == null)) { 15412 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15413 return false; 15414 } 15415 p = ps.pkg; 15416 } 15417 if (ps != null) { 15418 libDirRoot = ps.legacyNativeLibraryPathString; 15419 } 15420 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15421 final long token = Binder.clearCallingIdentity(); 15422 try { 15423 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15424 if (secureContainerId != null) { 15425 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15426 } 15427 } finally { 15428 Binder.restoreCallingIdentity(token); 15429 } 15430 } 15431 } 15432 String publicSrcDir = null; 15433 if(!dataOnly) { 15434 final ApplicationInfo applicationInfo = p.applicationInfo; 15435 if (applicationInfo == null) { 15436 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15437 return false; 15438 } 15439 if (p.isForwardLocked()) { 15440 publicSrcDir = applicationInfo.getBaseResourcePath(); 15441 } 15442 } 15443 // TODO: extend to measure size of split APKs 15444 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15445 // not just the first level. 15446 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15447 // just the primary. 15448 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15449 15450 String apkPath; 15451 File packageDir = new File(p.codePath); 15452 15453 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15454 apkPath = packageDir.getAbsolutePath(); 15455 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15456 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15457 libDirRoot = null; 15458 } 15459 } else { 15460 apkPath = p.baseCodePath; 15461 } 15462 15463 // TODO: triage flags as part of 26466827 15464 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15465 try { 15466 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15467 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15468 } catch (InstallerException e) { 15469 return false; 15470 } 15471 15472 // Fix-up for forward-locked applications in ASEC containers. 15473 if (!isExternal(p)) { 15474 pStats.codeSize += pStats.externalCodeSize; 15475 pStats.externalCodeSize = 0L; 15476 } 15477 15478 return true; 15479 } 15480 15481 15482 @Override 15483 public void addPackageToPreferred(String packageName) { 15484 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15485 } 15486 15487 @Override 15488 public void removePackageFromPreferred(String packageName) { 15489 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15490 } 15491 15492 @Override 15493 public List<PackageInfo> getPreferredPackages(int flags) { 15494 return new ArrayList<PackageInfo>(); 15495 } 15496 15497 private int getUidTargetSdkVersionLockedLPr(int uid) { 15498 Object obj = mSettings.getUserIdLPr(uid); 15499 if (obj instanceof SharedUserSetting) { 15500 final SharedUserSetting sus = (SharedUserSetting) obj; 15501 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15502 final Iterator<PackageSetting> it = sus.packages.iterator(); 15503 while (it.hasNext()) { 15504 final PackageSetting ps = it.next(); 15505 if (ps.pkg != null) { 15506 int v = ps.pkg.applicationInfo.targetSdkVersion; 15507 if (v < vers) vers = v; 15508 } 15509 } 15510 return vers; 15511 } else if (obj instanceof PackageSetting) { 15512 final PackageSetting ps = (PackageSetting) obj; 15513 if (ps.pkg != null) { 15514 return ps.pkg.applicationInfo.targetSdkVersion; 15515 } 15516 } 15517 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15518 } 15519 15520 @Override 15521 public void addPreferredActivity(IntentFilter filter, int match, 15522 ComponentName[] set, ComponentName activity, int userId) { 15523 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15524 "Adding preferred"); 15525 } 15526 15527 private void addPreferredActivityInternal(IntentFilter filter, int match, 15528 ComponentName[] set, ComponentName activity, boolean always, int userId, 15529 String opname) { 15530 // writer 15531 int callingUid = Binder.getCallingUid(); 15532 enforceCrossUserPermission(callingUid, userId, 15533 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15534 if (filter.countActions() == 0) { 15535 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15536 return; 15537 } 15538 synchronized (mPackages) { 15539 if (mContext.checkCallingOrSelfPermission( 15540 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15541 != PackageManager.PERMISSION_GRANTED) { 15542 if (getUidTargetSdkVersionLockedLPr(callingUid) 15543 < Build.VERSION_CODES.FROYO) { 15544 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15545 + callingUid); 15546 return; 15547 } 15548 mContext.enforceCallingOrSelfPermission( 15549 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15550 } 15551 15552 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15553 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15554 + userId + ":"); 15555 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15556 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15557 scheduleWritePackageRestrictionsLocked(userId); 15558 } 15559 } 15560 15561 @Override 15562 public void replacePreferredActivity(IntentFilter filter, int match, 15563 ComponentName[] set, ComponentName activity, int userId) { 15564 if (filter.countActions() != 1) { 15565 throw new IllegalArgumentException( 15566 "replacePreferredActivity expects filter to have only 1 action."); 15567 } 15568 if (filter.countDataAuthorities() != 0 15569 || filter.countDataPaths() != 0 15570 || filter.countDataSchemes() > 1 15571 || filter.countDataTypes() != 0) { 15572 throw new IllegalArgumentException( 15573 "replacePreferredActivity expects filter to have no data authorities, " + 15574 "paths, or types; and at most one scheme."); 15575 } 15576 15577 final int callingUid = Binder.getCallingUid(); 15578 enforceCrossUserPermission(callingUid, userId, 15579 true /* requireFullPermission */, false /* checkShell */, 15580 "replace preferred activity"); 15581 synchronized (mPackages) { 15582 if (mContext.checkCallingOrSelfPermission( 15583 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15584 != PackageManager.PERMISSION_GRANTED) { 15585 if (getUidTargetSdkVersionLockedLPr(callingUid) 15586 < Build.VERSION_CODES.FROYO) { 15587 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15588 + Binder.getCallingUid()); 15589 return; 15590 } 15591 mContext.enforceCallingOrSelfPermission( 15592 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15593 } 15594 15595 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15596 if (pir != null) { 15597 // Get all of the existing entries that exactly match this filter. 15598 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15599 if (existing != null && existing.size() == 1) { 15600 PreferredActivity cur = existing.get(0); 15601 if (DEBUG_PREFERRED) { 15602 Slog.i(TAG, "Checking replace of preferred:"); 15603 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15604 if (!cur.mPref.mAlways) { 15605 Slog.i(TAG, " -- CUR; not mAlways!"); 15606 } else { 15607 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15608 Slog.i(TAG, " -- CUR: mSet=" 15609 + Arrays.toString(cur.mPref.mSetComponents)); 15610 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15611 Slog.i(TAG, " -- NEW: mMatch=" 15612 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15613 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15614 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15615 } 15616 } 15617 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15618 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15619 && cur.mPref.sameSet(set)) { 15620 // Setting the preferred activity to what it happens to be already 15621 if (DEBUG_PREFERRED) { 15622 Slog.i(TAG, "Replacing with same preferred activity " 15623 + cur.mPref.mShortComponent + " for user " 15624 + userId + ":"); 15625 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15626 } 15627 return; 15628 } 15629 } 15630 15631 if (existing != null) { 15632 if (DEBUG_PREFERRED) { 15633 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15634 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15635 } 15636 for (int i = 0; i < existing.size(); i++) { 15637 PreferredActivity pa = existing.get(i); 15638 if (DEBUG_PREFERRED) { 15639 Slog.i(TAG, "Removing existing preferred activity " 15640 + pa.mPref.mComponent + ":"); 15641 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15642 } 15643 pir.removeFilter(pa); 15644 } 15645 } 15646 } 15647 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15648 "Replacing preferred"); 15649 } 15650 } 15651 15652 @Override 15653 public void clearPackagePreferredActivities(String packageName) { 15654 final int uid = Binder.getCallingUid(); 15655 // writer 15656 synchronized (mPackages) { 15657 PackageParser.Package pkg = mPackages.get(packageName); 15658 if (pkg == null || pkg.applicationInfo.uid != uid) { 15659 if (mContext.checkCallingOrSelfPermission( 15660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15661 != PackageManager.PERMISSION_GRANTED) { 15662 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15663 < Build.VERSION_CODES.FROYO) { 15664 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15665 + Binder.getCallingUid()); 15666 return; 15667 } 15668 mContext.enforceCallingOrSelfPermission( 15669 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15670 } 15671 } 15672 15673 int user = UserHandle.getCallingUserId(); 15674 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15675 scheduleWritePackageRestrictionsLocked(user); 15676 } 15677 } 15678 } 15679 15680 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15681 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15682 ArrayList<PreferredActivity> removed = null; 15683 boolean changed = false; 15684 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15685 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15686 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15687 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15688 continue; 15689 } 15690 Iterator<PreferredActivity> it = pir.filterIterator(); 15691 while (it.hasNext()) { 15692 PreferredActivity pa = it.next(); 15693 // Mark entry for removal only if it matches the package name 15694 // and the entry is of type "always". 15695 if (packageName == null || 15696 (pa.mPref.mComponent.getPackageName().equals(packageName) 15697 && pa.mPref.mAlways)) { 15698 if (removed == null) { 15699 removed = new ArrayList<PreferredActivity>(); 15700 } 15701 removed.add(pa); 15702 } 15703 } 15704 if (removed != null) { 15705 for (int j=0; j<removed.size(); j++) { 15706 PreferredActivity pa = removed.get(j); 15707 pir.removeFilter(pa); 15708 } 15709 changed = true; 15710 } 15711 } 15712 return changed; 15713 } 15714 15715 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15716 private void clearIntentFilterVerificationsLPw(int userId) { 15717 final int packageCount = mPackages.size(); 15718 for (int i = 0; i < packageCount; i++) { 15719 PackageParser.Package pkg = mPackages.valueAt(i); 15720 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15721 } 15722 } 15723 15724 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15725 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15726 if (userId == UserHandle.USER_ALL) { 15727 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15728 sUserManager.getUserIds())) { 15729 for (int oneUserId : sUserManager.getUserIds()) { 15730 scheduleWritePackageRestrictionsLocked(oneUserId); 15731 } 15732 } 15733 } else { 15734 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15735 scheduleWritePackageRestrictionsLocked(userId); 15736 } 15737 } 15738 } 15739 15740 void clearDefaultBrowserIfNeeded(String packageName) { 15741 for (int oneUserId : sUserManager.getUserIds()) { 15742 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15743 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15744 if (packageName.equals(defaultBrowserPackageName)) { 15745 setDefaultBrowserPackageName(null, oneUserId); 15746 } 15747 } 15748 } 15749 15750 @Override 15751 public void resetApplicationPreferences(int userId) { 15752 mContext.enforceCallingOrSelfPermission( 15753 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15754 // writer 15755 synchronized (mPackages) { 15756 final long identity = Binder.clearCallingIdentity(); 15757 try { 15758 clearPackagePreferredActivitiesLPw(null, userId); 15759 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15760 // TODO: We have to reset the default SMS and Phone. This requires 15761 // significant refactoring to keep all default apps in the package 15762 // manager (cleaner but more work) or have the services provide 15763 // callbacks to the package manager to request a default app reset. 15764 applyFactoryDefaultBrowserLPw(userId); 15765 clearIntentFilterVerificationsLPw(userId); 15766 primeDomainVerificationsLPw(userId); 15767 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15768 scheduleWritePackageRestrictionsLocked(userId); 15769 } finally { 15770 Binder.restoreCallingIdentity(identity); 15771 } 15772 } 15773 } 15774 15775 @Override 15776 public int getPreferredActivities(List<IntentFilter> outFilters, 15777 List<ComponentName> outActivities, String packageName) { 15778 15779 int num = 0; 15780 final int userId = UserHandle.getCallingUserId(); 15781 // reader 15782 synchronized (mPackages) { 15783 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15784 if (pir != null) { 15785 final Iterator<PreferredActivity> it = pir.filterIterator(); 15786 while (it.hasNext()) { 15787 final PreferredActivity pa = it.next(); 15788 if (packageName == null 15789 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15790 && pa.mPref.mAlways)) { 15791 if (outFilters != null) { 15792 outFilters.add(new IntentFilter(pa)); 15793 } 15794 if (outActivities != null) { 15795 outActivities.add(pa.mPref.mComponent); 15796 } 15797 } 15798 } 15799 } 15800 } 15801 15802 return num; 15803 } 15804 15805 @Override 15806 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15807 int userId) { 15808 int callingUid = Binder.getCallingUid(); 15809 if (callingUid != Process.SYSTEM_UID) { 15810 throw new SecurityException( 15811 "addPersistentPreferredActivity can only be run by the system"); 15812 } 15813 if (filter.countActions() == 0) { 15814 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15815 return; 15816 } 15817 synchronized (mPackages) { 15818 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15819 ":"); 15820 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15821 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15822 new PersistentPreferredActivity(filter, activity)); 15823 scheduleWritePackageRestrictionsLocked(userId); 15824 } 15825 } 15826 15827 @Override 15828 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15829 int callingUid = Binder.getCallingUid(); 15830 if (callingUid != Process.SYSTEM_UID) { 15831 throw new SecurityException( 15832 "clearPackagePersistentPreferredActivities can only be run by the system"); 15833 } 15834 ArrayList<PersistentPreferredActivity> removed = null; 15835 boolean changed = false; 15836 synchronized (mPackages) { 15837 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15838 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15839 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15840 .valueAt(i); 15841 if (userId != thisUserId) { 15842 continue; 15843 } 15844 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15845 while (it.hasNext()) { 15846 PersistentPreferredActivity ppa = it.next(); 15847 // Mark entry for removal only if it matches the package name. 15848 if (ppa.mComponent.getPackageName().equals(packageName)) { 15849 if (removed == null) { 15850 removed = new ArrayList<PersistentPreferredActivity>(); 15851 } 15852 removed.add(ppa); 15853 } 15854 } 15855 if (removed != null) { 15856 for (int j=0; j<removed.size(); j++) { 15857 PersistentPreferredActivity ppa = removed.get(j); 15858 ppir.removeFilter(ppa); 15859 } 15860 changed = true; 15861 } 15862 } 15863 15864 if (changed) { 15865 scheduleWritePackageRestrictionsLocked(userId); 15866 } 15867 } 15868 } 15869 15870 /** 15871 * Common machinery for picking apart a restored XML blob and passing 15872 * it to a caller-supplied functor to be applied to the running system. 15873 */ 15874 private void restoreFromXml(XmlPullParser parser, int userId, 15875 String expectedStartTag, BlobXmlRestorer functor) 15876 throws IOException, XmlPullParserException { 15877 int type; 15878 while ((type = parser.next()) != XmlPullParser.START_TAG 15879 && type != XmlPullParser.END_DOCUMENT) { 15880 } 15881 if (type != XmlPullParser.START_TAG) { 15882 // oops didn't find a start tag?! 15883 if (DEBUG_BACKUP) { 15884 Slog.e(TAG, "Didn't find start tag during restore"); 15885 } 15886 return; 15887 } 15888Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15889 // this is supposed to be TAG_PREFERRED_BACKUP 15890 if (!expectedStartTag.equals(parser.getName())) { 15891 if (DEBUG_BACKUP) { 15892 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15893 } 15894 return; 15895 } 15896 15897 // skip interfering stuff, then we're aligned with the backing implementation 15898 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15899Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15900 functor.apply(parser, userId); 15901 } 15902 15903 private interface BlobXmlRestorer { 15904 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15905 } 15906 15907 /** 15908 * Non-Binder method, support for the backup/restore mechanism: write the 15909 * full set of preferred activities in its canonical XML format. Returns the 15910 * XML output as a byte array, or null if there is none. 15911 */ 15912 @Override 15913 public byte[] getPreferredActivityBackup(int userId) { 15914 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15915 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15916 } 15917 15918 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15919 try { 15920 final XmlSerializer serializer = new FastXmlSerializer(); 15921 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15922 serializer.startDocument(null, true); 15923 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15924 15925 synchronized (mPackages) { 15926 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15927 } 15928 15929 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15930 serializer.endDocument(); 15931 serializer.flush(); 15932 } catch (Exception e) { 15933 if (DEBUG_BACKUP) { 15934 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15935 } 15936 return null; 15937 } 15938 15939 return dataStream.toByteArray(); 15940 } 15941 15942 @Override 15943 public void restorePreferredActivities(byte[] backup, int userId) { 15944 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15945 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15946 } 15947 15948 try { 15949 final XmlPullParser parser = Xml.newPullParser(); 15950 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15951 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15952 new BlobXmlRestorer() { 15953 @Override 15954 public void apply(XmlPullParser parser, int userId) 15955 throws XmlPullParserException, IOException { 15956 synchronized (mPackages) { 15957 mSettings.readPreferredActivitiesLPw(parser, userId); 15958 } 15959 } 15960 } ); 15961 } catch (Exception e) { 15962 if (DEBUG_BACKUP) { 15963 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15964 } 15965 } 15966 } 15967 15968 /** 15969 * Non-Binder method, support for the backup/restore mechanism: write the 15970 * default browser (etc) settings in its canonical XML format. Returns the default 15971 * browser XML representation as a byte array, or null if there is none. 15972 */ 15973 @Override 15974 public byte[] getDefaultAppsBackup(int userId) { 15975 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15976 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15977 } 15978 15979 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15980 try { 15981 final XmlSerializer serializer = new FastXmlSerializer(); 15982 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15983 serializer.startDocument(null, true); 15984 serializer.startTag(null, TAG_DEFAULT_APPS); 15985 15986 synchronized (mPackages) { 15987 mSettings.writeDefaultAppsLPr(serializer, userId); 15988 } 15989 15990 serializer.endTag(null, TAG_DEFAULT_APPS); 15991 serializer.endDocument(); 15992 serializer.flush(); 15993 } catch (Exception e) { 15994 if (DEBUG_BACKUP) { 15995 Slog.e(TAG, "Unable to write default apps for backup", e); 15996 } 15997 return null; 15998 } 15999 16000 return dataStream.toByteArray(); 16001 } 16002 16003 @Override 16004 public void restoreDefaultApps(byte[] backup, int userId) { 16005 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16006 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16007 } 16008 16009 try { 16010 final XmlPullParser parser = Xml.newPullParser(); 16011 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16012 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16013 new BlobXmlRestorer() { 16014 @Override 16015 public void apply(XmlPullParser parser, int userId) 16016 throws XmlPullParserException, IOException { 16017 synchronized (mPackages) { 16018 mSettings.readDefaultAppsLPw(parser, userId); 16019 } 16020 } 16021 } ); 16022 } catch (Exception e) { 16023 if (DEBUG_BACKUP) { 16024 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16025 } 16026 } 16027 } 16028 16029 @Override 16030 public byte[] getIntentFilterVerificationBackup(int userId) { 16031 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16032 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16033 } 16034 16035 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16036 try { 16037 final XmlSerializer serializer = new FastXmlSerializer(); 16038 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16039 serializer.startDocument(null, true); 16040 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16041 16042 synchronized (mPackages) { 16043 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16044 } 16045 16046 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16047 serializer.endDocument(); 16048 serializer.flush(); 16049 } catch (Exception e) { 16050 if (DEBUG_BACKUP) { 16051 Slog.e(TAG, "Unable to write default apps for backup", e); 16052 } 16053 return null; 16054 } 16055 16056 return dataStream.toByteArray(); 16057 } 16058 16059 @Override 16060 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16061 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16062 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16063 } 16064 16065 try { 16066 final XmlPullParser parser = Xml.newPullParser(); 16067 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16068 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16069 new BlobXmlRestorer() { 16070 @Override 16071 public void apply(XmlPullParser parser, int userId) 16072 throws XmlPullParserException, IOException { 16073 synchronized (mPackages) { 16074 mSettings.readAllDomainVerificationsLPr(parser, userId); 16075 mSettings.writeLPr(); 16076 } 16077 } 16078 } ); 16079 } catch (Exception e) { 16080 if (DEBUG_BACKUP) { 16081 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16082 } 16083 } 16084 } 16085 16086 @Override 16087 public byte[] getPermissionGrantBackup(int userId) { 16088 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16089 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16090 } 16091 16092 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16093 try { 16094 final XmlSerializer serializer = new FastXmlSerializer(); 16095 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16096 serializer.startDocument(null, true); 16097 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16098 16099 synchronized (mPackages) { 16100 serializeRuntimePermissionGrantsLPr(serializer, userId); 16101 } 16102 16103 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16104 serializer.endDocument(); 16105 serializer.flush(); 16106 } catch (Exception e) { 16107 if (DEBUG_BACKUP) { 16108 Slog.e(TAG, "Unable to write default apps for backup", e); 16109 } 16110 return null; 16111 } 16112 16113 return dataStream.toByteArray(); 16114 } 16115 16116 @Override 16117 public void restorePermissionGrants(byte[] backup, int userId) { 16118 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16119 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16120 } 16121 16122 try { 16123 final XmlPullParser parser = Xml.newPullParser(); 16124 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16125 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16126 new BlobXmlRestorer() { 16127 @Override 16128 public void apply(XmlPullParser parser, int userId) 16129 throws XmlPullParserException, IOException { 16130 synchronized (mPackages) { 16131 processRestoredPermissionGrantsLPr(parser, userId); 16132 } 16133 } 16134 } ); 16135 } catch (Exception e) { 16136 if (DEBUG_BACKUP) { 16137 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16138 } 16139 } 16140 } 16141 16142 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16143 throws IOException { 16144 serializer.startTag(null, TAG_ALL_GRANTS); 16145 16146 final int N = mSettings.mPackages.size(); 16147 for (int i = 0; i < N; i++) { 16148 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16149 boolean pkgGrantsKnown = false; 16150 16151 PermissionsState packagePerms = ps.getPermissionsState(); 16152 16153 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16154 final int grantFlags = state.getFlags(); 16155 // only look at grants that are not system/policy fixed 16156 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16157 final boolean isGranted = state.isGranted(); 16158 // And only back up the user-twiddled state bits 16159 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16160 final String packageName = mSettings.mPackages.keyAt(i); 16161 if (!pkgGrantsKnown) { 16162 serializer.startTag(null, TAG_GRANT); 16163 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16164 pkgGrantsKnown = true; 16165 } 16166 16167 final boolean userSet = 16168 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16169 final boolean userFixed = 16170 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16171 final boolean revoke = 16172 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16173 16174 serializer.startTag(null, TAG_PERMISSION); 16175 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16176 if (isGranted) { 16177 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16178 } 16179 if (userSet) { 16180 serializer.attribute(null, ATTR_USER_SET, "true"); 16181 } 16182 if (userFixed) { 16183 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16184 } 16185 if (revoke) { 16186 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16187 } 16188 serializer.endTag(null, TAG_PERMISSION); 16189 } 16190 } 16191 } 16192 16193 if (pkgGrantsKnown) { 16194 serializer.endTag(null, TAG_GRANT); 16195 } 16196 } 16197 16198 serializer.endTag(null, TAG_ALL_GRANTS); 16199 } 16200 16201 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16202 throws XmlPullParserException, IOException { 16203 String pkgName = null; 16204 int outerDepth = parser.getDepth(); 16205 int type; 16206 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16207 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16208 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16209 continue; 16210 } 16211 16212 final String tagName = parser.getName(); 16213 if (tagName.equals(TAG_GRANT)) { 16214 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16215 if (DEBUG_BACKUP) { 16216 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16217 } 16218 } else if (tagName.equals(TAG_PERMISSION)) { 16219 16220 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16221 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16222 16223 int newFlagSet = 0; 16224 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16225 newFlagSet |= FLAG_PERMISSION_USER_SET; 16226 } 16227 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16228 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16229 } 16230 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16231 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16232 } 16233 if (DEBUG_BACKUP) { 16234 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16235 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16236 } 16237 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16238 if (ps != null) { 16239 // Already installed so we apply the grant immediately 16240 if (DEBUG_BACKUP) { 16241 Slog.v(TAG, " + already installed; applying"); 16242 } 16243 PermissionsState perms = ps.getPermissionsState(); 16244 BasePermission bp = mSettings.mPermissions.get(permName); 16245 if (bp != null) { 16246 if (isGranted) { 16247 perms.grantRuntimePermission(bp, userId); 16248 } 16249 if (newFlagSet != 0) { 16250 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16251 } 16252 } 16253 } else { 16254 // Need to wait for post-restore install to apply the grant 16255 if (DEBUG_BACKUP) { 16256 Slog.v(TAG, " - not yet installed; saving for later"); 16257 } 16258 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16259 isGranted, newFlagSet, userId); 16260 } 16261 } else { 16262 PackageManagerService.reportSettingsProblem(Log.WARN, 16263 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16264 XmlUtils.skipCurrentTag(parser); 16265 } 16266 } 16267 16268 scheduleWriteSettingsLocked(); 16269 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16270 } 16271 16272 @Override 16273 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16274 int sourceUserId, int targetUserId, int flags) { 16275 mContext.enforceCallingOrSelfPermission( 16276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16277 int callingUid = Binder.getCallingUid(); 16278 enforceOwnerRights(ownerPackage, callingUid); 16279 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16280 if (intentFilter.countActions() == 0) { 16281 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16282 return; 16283 } 16284 synchronized (mPackages) { 16285 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16286 ownerPackage, targetUserId, flags); 16287 CrossProfileIntentResolver resolver = 16288 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16289 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16290 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16291 if (existing != null) { 16292 int size = existing.size(); 16293 for (int i = 0; i < size; i++) { 16294 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16295 return; 16296 } 16297 } 16298 } 16299 resolver.addFilter(newFilter); 16300 scheduleWritePackageRestrictionsLocked(sourceUserId); 16301 } 16302 } 16303 16304 @Override 16305 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16306 mContext.enforceCallingOrSelfPermission( 16307 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16308 int callingUid = Binder.getCallingUid(); 16309 enforceOwnerRights(ownerPackage, callingUid); 16310 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16311 synchronized (mPackages) { 16312 CrossProfileIntentResolver resolver = 16313 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16314 ArraySet<CrossProfileIntentFilter> set = 16315 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16316 for (CrossProfileIntentFilter filter : set) { 16317 if (filter.getOwnerPackage().equals(ownerPackage)) { 16318 resolver.removeFilter(filter); 16319 } 16320 } 16321 scheduleWritePackageRestrictionsLocked(sourceUserId); 16322 } 16323 } 16324 16325 // Enforcing that callingUid is owning pkg on userId 16326 private void enforceOwnerRights(String pkg, int callingUid) { 16327 // The system owns everything. 16328 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16329 return; 16330 } 16331 int callingUserId = UserHandle.getUserId(callingUid); 16332 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16333 if (pi == null) { 16334 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16335 + callingUserId); 16336 } 16337 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16338 throw new SecurityException("Calling uid " + callingUid 16339 + " does not own package " + pkg); 16340 } 16341 } 16342 16343 @Override 16344 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16345 Intent intent = new Intent(Intent.ACTION_MAIN); 16346 intent.addCategory(Intent.CATEGORY_HOME); 16347 16348 final int callingUserId = UserHandle.getCallingUserId(); 16349 List<ResolveInfo> list = queryIntentActivities(intent, null, 16350 PackageManager.GET_META_DATA, callingUserId); 16351 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16352 true, false, false, callingUserId); 16353 16354 allHomeCandidates.clear(); 16355 if (list != null) { 16356 for (ResolveInfo ri : list) { 16357 allHomeCandidates.add(ri); 16358 } 16359 } 16360 return (preferred == null || preferred.activityInfo == null) 16361 ? null 16362 : new ComponentName(preferred.activityInfo.packageName, 16363 preferred.activityInfo.name); 16364 } 16365 16366 @Override 16367 public void setApplicationEnabledSetting(String appPackageName, 16368 int newState, int flags, int userId, String callingPackage) { 16369 if (!sUserManager.exists(userId)) return; 16370 if (callingPackage == null) { 16371 callingPackage = Integer.toString(Binder.getCallingUid()); 16372 } 16373 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16374 } 16375 16376 @Override 16377 public void setComponentEnabledSetting(ComponentName componentName, 16378 int newState, int flags, int userId) { 16379 if (!sUserManager.exists(userId)) return; 16380 setEnabledSetting(componentName.getPackageName(), 16381 componentName.getClassName(), newState, flags, userId, null); 16382 } 16383 16384 private void setEnabledSetting(final String packageName, String className, int newState, 16385 final int flags, int userId, String callingPackage) { 16386 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16387 || newState == COMPONENT_ENABLED_STATE_ENABLED 16388 || newState == COMPONENT_ENABLED_STATE_DISABLED 16389 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16390 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16391 throw new IllegalArgumentException("Invalid new component state: " 16392 + newState); 16393 } 16394 PackageSetting pkgSetting; 16395 final int uid = Binder.getCallingUid(); 16396 final int permission = mContext.checkCallingOrSelfPermission( 16397 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16398 enforceCrossUserPermission(uid, userId, 16399 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16400 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16401 boolean sendNow = false; 16402 boolean isApp = (className == null); 16403 String componentName = isApp ? packageName : className; 16404 int packageUid = -1; 16405 ArrayList<String> components; 16406 16407 // writer 16408 synchronized (mPackages) { 16409 pkgSetting = mSettings.mPackages.get(packageName); 16410 if (pkgSetting == null) { 16411 if (className == null) { 16412 throw new IllegalArgumentException("Unknown package: " + packageName); 16413 } 16414 throw new IllegalArgumentException( 16415 "Unknown component: " + packageName + "/" + className); 16416 } 16417 // Allow root and verify that userId is not being specified by a different user 16418 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16419 throw new SecurityException( 16420 "Permission Denial: attempt to change component state from pid=" 16421 + Binder.getCallingPid() 16422 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16423 } 16424 if (className == null) { 16425 // We're dealing with an application/package level state change 16426 if (pkgSetting.getEnabled(userId) == newState) { 16427 // Nothing to do 16428 return; 16429 } 16430 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16431 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16432 // Don't care about who enables an app. 16433 callingPackage = null; 16434 } 16435 pkgSetting.setEnabled(newState, userId, callingPackage); 16436 // pkgSetting.pkg.mSetEnabled = newState; 16437 } else { 16438 // We're dealing with a component level state change 16439 // First, verify that this is a valid class name. 16440 PackageParser.Package pkg = pkgSetting.pkg; 16441 if (pkg == null || !pkg.hasComponentClassName(className)) { 16442 if (pkg != null && 16443 pkg.applicationInfo.targetSdkVersion >= 16444 Build.VERSION_CODES.JELLY_BEAN) { 16445 throw new IllegalArgumentException("Component class " + className 16446 + " does not exist in " + packageName); 16447 } else { 16448 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16449 + className + " does not exist in " + packageName); 16450 } 16451 } 16452 switch (newState) { 16453 case COMPONENT_ENABLED_STATE_ENABLED: 16454 if (!pkgSetting.enableComponentLPw(className, userId)) { 16455 return; 16456 } 16457 break; 16458 case COMPONENT_ENABLED_STATE_DISABLED: 16459 if (!pkgSetting.disableComponentLPw(className, userId)) { 16460 return; 16461 } 16462 break; 16463 case COMPONENT_ENABLED_STATE_DEFAULT: 16464 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16465 return; 16466 } 16467 break; 16468 default: 16469 Slog.e(TAG, "Invalid new component state: " + newState); 16470 return; 16471 } 16472 } 16473 scheduleWritePackageRestrictionsLocked(userId); 16474 components = mPendingBroadcasts.get(userId, packageName); 16475 final boolean newPackage = components == null; 16476 if (newPackage) { 16477 components = new ArrayList<String>(); 16478 } 16479 if (!components.contains(componentName)) { 16480 components.add(componentName); 16481 } 16482 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16483 sendNow = true; 16484 // Purge entry from pending broadcast list if another one exists already 16485 // since we are sending one right away. 16486 mPendingBroadcasts.remove(userId, packageName); 16487 } else { 16488 if (newPackage) { 16489 mPendingBroadcasts.put(userId, packageName, components); 16490 } 16491 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16492 // Schedule a message 16493 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16494 } 16495 } 16496 } 16497 16498 long callingId = Binder.clearCallingIdentity(); 16499 try { 16500 if (sendNow) { 16501 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16502 sendPackageChangedBroadcast(packageName, 16503 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16504 } 16505 } finally { 16506 Binder.restoreCallingIdentity(callingId); 16507 } 16508 } 16509 16510 private void sendPackageChangedBroadcast(String packageName, 16511 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16512 if (DEBUG_INSTALL) 16513 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16514 + componentNames); 16515 Bundle extras = new Bundle(4); 16516 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16517 String nameList[] = new String[componentNames.size()]; 16518 componentNames.toArray(nameList); 16519 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16520 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16521 extras.putInt(Intent.EXTRA_UID, packageUid); 16522 // If this is not reporting a change of the overall package, then only send it 16523 // to registered receivers. We don't want to launch a swath of apps for every 16524 // little component state change. 16525 final int flags = !componentNames.contains(packageName) 16526 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16527 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16528 new int[] {UserHandle.getUserId(packageUid)}); 16529 } 16530 16531 @Override 16532 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16533 if (!sUserManager.exists(userId)) return; 16534 final int uid = Binder.getCallingUid(); 16535 final int permission = mContext.checkCallingOrSelfPermission( 16536 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16537 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16538 enforceCrossUserPermission(uid, userId, 16539 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16540 // writer 16541 synchronized (mPackages) { 16542 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16543 allowedByPermission, uid, userId)) { 16544 scheduleWritePackageRestrictionsLocked(userId); 16545 } 16546 } 16547 } 16548 16549 @Override 16550 public String getInstallerPackageName(String packageName) { 16551 // reader 16552 synchronized (mPackages) { 16553 return mSettings.getInstallerPackageNameLPr(packageName); 16554 } 16555 } 16556 16557 @Override 16558 public int getApplicationEnabledSetting(String packageName, int userId) { 16559 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16560 int uid = Binder.getCallingUid(); 16561 enforceCrossUserPermission(uid, userId, 16562 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16563 // reader 16564 synchronized (mPackages) { 16565 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16566 } 16567 } 16568 16569 @Override 16570 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16571 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16572 int uid = Binder.getCallingUid(); 16573 enforceCrossUserPermission(uid, userId, 16574 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16575 // reader 16576 synchronized (mPackages) { 16577 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16578 } 16579 } 16580 16581 @Override 16582 public void enterSafeMode() { 16583 enforceSystemOrRoot("Only the system can request entering safe mode"); 16584 16585 if (!mSystemReady) { 16586 mSafeMode = true; 16587 } 16588 } 16589 16590 @Override 16591 public void systemReady() { 16592 mSystemReady = true; 16593 16594 // Read the compatibilty setting when the system is ready. 16595 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16596 mContext.getContentResolver(), 16597 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16598 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16599 if (DEBUG_SETTINGS) { 16600 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16601 } 16602 16603 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16604 16605 synchronized (mPackages) { 16606 // Verify that all of the preferred activity components actually 16607 // exist. It is possible for applications to be updated and at 16608 // that point remove a previously declared activity component that 16609 // had been set as a preferred activity. We try to clean this up 16610 // the next time we encounter that preferred activity, but it is 16611 // possible for the user flow to never be able to return to that 16612 // situation so here we do a sanity check to make sure we haven't 16613 // left any junk around. 16614 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16615 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16616 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16617 removed.clear(); 16618 for (PreferredActivity pa : pir.filterSet()) { 16619 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16620 removed.add(pa); 16621 } 16622 } 16623 if (removed.size() > 0) { 16624 for (int r=0; r<removed.size(); r++) { 16625 PreferredActivity pa = removed.get(r); 16626 Slog.w(TAG, "Removing dangling preferred activity: " 16627 + pa.mPref.mComponent); 16628 pir.removeFilter(pa); 16629 } 16630 mSettings.writePackageRestrictionsLPr( 16631 mSettings.mPreferredActivities.keyAt(i)); 16632 } 16633 } 16634 16635 for (int userId : UserManagerService.getInstance().getUserIds()) { 16636 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16637 grantPermissionsUserIds = ArrayUtils.appendInt( 16638 grantPermissionsUserIds, userId); 16639 } 16640 } 16641 } 16642 sUserManager.systemReady(); 16643 16644 // If we upgraded grant all default permissions before kicking off. 16645 for (int userId : grantPermissionsUserIds) { 16646 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16647 } 16648 16649 // Kick off any messages waiting for system ready 16650 if (mPostSystemReadyMessages != null) { 16651 for (Message msg : mPostSystemReadyMessages) { 16652 msg.sendToTarget(); 16653 } 16654 mPostSystemReadyMessages = null; 16655 } 16656 16657 // Watch for external volumes that come and go over time 16658 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16659 storage.registerListener(mStorageListener); 16660 16661 mInstallerService.systemReady(); 16662 mPackageDexOptimizer.systemReady(); 16663 16664 MountServiceInternal mountServiceInternal = LocalServices.getService( 16665 MountServiceInternal.class); 16666 mountServiceInternal.addExternalStoragePolicy( 16667 new MountServiceInternal.ExternalStorageMountPolicy() { 16668 @Override 16669 public int getMountMode(int uid, String packageName) { 16670 if (Process.isIsolated(uid)) { 16671 return Zygote.MOUNT_EXTERNAL_NONE; 16672 } 16673 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16674 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16675 } 16676 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16677 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16678 } 16679 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16680 return Zygote.MOUNT_EXTERNAL_READ; 16681 } 16682 return Zygote.MOUNT_EXTERNAL_WRITE; 16683 } 16684 16685 @Override 16686 public boolean hasExternalStorage(int uid, String packageName) { 16687 return true; 16688 } 16689 }); 16690 } 16691 16692 @Override 16693 public boolean isSafeMode() { 16694 return mSafeMode; 16695 } 16696 16697 @Override 16698 public boolean hasSystemUidErrors() { 16699 return mHasSystemUidErrors; 16700 } 16701 16702 static String arrayToString(int[] array) { 16703 StringBuffer buf = new StringBuffer(128); 16704 buf.append('['); 16705 if (array != null) { 16706 for (int i=0; i<array.length; i++) { 16707 if (i > 0) buf.append(", "); 16708 buf.append(array[i]); 16709 } 16710 } 16711 buf.append(']'); 16712 return buf.toString(); 16713 } 16714 16715 static class DumpState { 16716 public static final int DUMP_LIBS = 1 << 0; 16717 public static final int DUMP_FEATURES = 1 << 1; 16718 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16719 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16720 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16721 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16722 public static final int DUMP_PERMISSIONS = 1 << 6; 16723 public static final int DUMP_PACKAGES = 1 << 7; 16724 public static final int DUMP_SHARED_USERS = 1 << 8; 16725 public static final int DUMP_MESSAGES = 1 << 9; 16726 public static final int DUMP_PROVIDERS = 1 << 10; 16727 public static final int DUMP_VERIFIERS = 1 << 11; 16728 public static final int DUMP_PREFERRED = 1 << 12; 16729 public static final int DUMP_PREFERRED_XML = 1 << 13; 16730 public static final int DUMP_KEYSETS = 1 << 14; 16731 public static final int DUMP_VERSION = 1 << 15; 16732 public static final int DUMP_INSTALLS = 1 << 16; 16733 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16734 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16735 16736 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16737 16738 private int mTypes; 16739 16740 private int mOptions; 16741 16742 private boolean mTitlePrinted; 16743 16744 private SharedUserSetting mSharedUser; 16745 16746 public boolean isDumping(int type) { 16747 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16748 return true; 16749 } 16750 16751 return (mTypes & type) != 0; 16752 } 16753 16754 public void setDump(int type) { 16755 mTypes |= type; 16756 } 16757 16758 public boolean isOptionEnabled(int option) { 16759 return (mOptions & option) != 0; 16760 } 16761 16762 public void setOptionEnabled(int option) { 16763 mOptions |= option; 16764 } 16765 16766 public boolean onTitlePrinted() { 16767 final boolean printed = mTitlePrinted; 16768 mTitlePrinted = true; 16769 return printed; 16770 } 16771 16772 public boolean getTitlePrinted() { 16773 return mTitlePrinted; 16774 } 16775 16776 public void setTitlePrinted(boolean enabled) { 16777 mTitlePrinted = enabled; 16778 } 16779 16780 public SharedUserSetting getSharedUser() { 16781 return mSharedUser; 16782 } 16783 16784 public void setSharedUser(SharedUserSetting user) { 16785 mSharedUser = user; 16786 } 16787 } 16788 16789 @Override 16790 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16791 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16792 (new PackageManagerShellCommand(this)).exec( 16793 this, in, out, err, args, resultReceiver); 16794 } 16795 16796 @Override 16797 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16798 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16799 != PackageManager.PERMISSION_GRANTED) { 16800 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16801 + Binder.getCallingPid() 16802 + ", uid=" + Binder.getCallingUid() 16803 + " without permission " 16804 + android.Manifest.permission.DUMP); 16805 return; 16806 } 16807 16808 DumpState dumpState = new DumpState(); 16809 boolean fullPreferred = false; 16810 boolean checkin = false; 16811 16812 String packageName = null; 16813 ArraySet<String> permissionNames = null; 16814 16815 int opti = 0; 16816 while (opti < args.length) { 16817 String opt = args[opti]; 16818 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16819 break; 16820 } 16821 opti++; 16822 16823 if ("-a".equals(opt)) { 16824 // Right now we only know how to print all. 16825 } else if ("-h".equals(opt)) { 16826 pw.println("Package manager dump options:"); 16827 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16828 pw.println(" --checkin: dump for a checkin"); 16829 pw.println(" -f: print details of intent filters"); 16830 pw.println(" -h: print this help"); 16831 pw.println(" cmd may be one of:"); 16832 pw.println(" l[ibraries]: list known shared libraries"); 16833 pw.println(" f[eatures]: list device features"); 16834 pw.println(" k[eysets]: print known keysets"); 16835 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16836 pw.println(" perm[issions]: dump permissions"); 16837 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16838 pw.println(" pref[erred]: print preferred package settings"); 16839 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16840 pw.println(" prov[iders]: dump content providers"); 16841 pw.println(" p[ackages]: dump installed packages"); 16842 pw.println(" s[hared-users]: dump shared user IDs"); 16843 pw.println(" m[essages]: print collected runtime messages"); 16844 pw.println(" v[erifiers]: print package verifier info"); 16845 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16846 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16847 pw.println(" version: print database version info"); 16848 pw.println(" write: write current settings now"); 16849 pw.println(" installs: details about install sessions"); 16850 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16851 pw.println(" <package.name>: info about given package"); 16852 return; 16853 } else if ("--checkin".equals(opt)) { 16854 checkin = true; 16855 } else if ("-f".equals(opt)) { 16856 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16857 } else { 16858 pw.println("Unknown argument: " + opt + "; use -h for help"); 16859 } 16860 } 16861 16862 // Is the caller requesting to dump a particular piece of data? 16863 if (opti < args.length) { 16864 String cmd = args[opti]; 16865 opti++; 16866 // Is this a package name? 16867 if ("android".equals(cmd) || cmd.contains(".")) { 16868 packageName = cmd; 16869 // When dumping a single package, we always dump all of its 16870 // filter information since the amount of data will be reasonable. 16871 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16872 } else if ("check-permission".equals(cmd)) { 16873 if (opti >= args.length) { 16874 pw.println("Error: check-permission missing permission argument"); 16875 return; 16876 } 16877 String perm = args[opti]; 16878 opti++; 16879 if (opti >= args.length) { 16880 pw.println("Error: check-permission missing package argument"); 16881 return; 16882 } 16883 String pkg = args[opti]; 16884 opti++; 16885 int user = UserHandle.getUserId(Binder.getCallingUid()); 16886 if (opti < args.length) { 16887 try { 16888 user = Integer.parseInt(args[opti]); 16889 } catch (NumberFormatException e) { 16890 pw.println("Error: check-permission user argument is not a number: " 16891 + args[opti]); 16892 return; 16893 } 16894 } 16895 pw.println(checkPermission(perm, pkg, user)); 16896 return; 16897 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16898 dumpState.setDump(DumpState.DUMP_LIBS); 16899 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16900 dumpState.setDump(DumpState.DUMP_FEATURES); 16901 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16902 if (opti >= args.length) { 16903 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16904 | DumpState.DUMP_SERVICE_RESOLVERS 16905 | DumpState.DUMP_RECEIVER_RESOLVERS 16906 | DumpState.DUMP_CONTENT_RESOLVERS); 16907 } else { 16908 while (opti < args.length) { 16909 String name = args[opti]; 16910 if ("a".equals(name) || "activity".equals(name)) { 16911 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16912 } else if ("s".equals(name) || "service".equals(name)) { 16913 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16914 } else if ("r".equals(name) || "receiver".equals(name)) { 16915 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16916 } else if ("c".equals(name) || "content".equals(name)) { 16917 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16918 } else { 16919 pw.println("Error: unknown resolver table type: " + name); 16920 return; 16921 } 16922 opti++; 16923 } 16924 } 16925 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16926 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16927 } else if ("permission".equals(cmd)) { 16928 if (opti >= args.length) { 16929 pw.println("Error: permission requires permission name"); 16930 return; 16931 } 16932 permissionNames = new ArraySet<>(); 16933 while (opti < args.length) { 16934 permissionNames.add(args[opti]); 16935 opti++; 16936 } 16937 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16938 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16939 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16940 dumpState.setDump(DumpState.DUMP_PREFERRED); 16941 } else if ("preferred-xml".equals(cmd)) { 16942 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16943 if (opti < args.length && "--full".equals(args[opti])) { 16944 fullPreferred = true; 16945 opti++; 16946 } 16947 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16948 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16949 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16950 dumpState.setDump(DumpState.DUMP_PACKAGES); 16951 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16952 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16953 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16954 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16955 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16956 dumpState.setDump(DumpState.DUMP_MESSAGES); 16957 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16958 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16959 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16960 || "intent-filter-verifiers".equals(cmd)) { 16961 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16962 } else if ("version".equals(cmd)) { 16963 dumpState.setDump(DumpState.DUMP_VERSION); 16964 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16965 dumpState.setDump(DumpState.DUMP_KEYSETS); 16966 } else if ("installs".equals(cmd)) { 16967 dumpState.setDump(DumpState.DUMP_INSTALLS); 16968 } else if ("write".equals(cmd)) { 16969 synchronized (mPackages) { 16970 mSettings.writeLPr(); 16971 pw.println("Settings written."); 16972 return; 16973 } 16974 } 16975 } 16976 16977 if (checkin) { 16978 pw.println("vers,1"); 16979 } 16980 16981 // reader 16982 synchronized (mPackages) { 16983 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16984 if (!checkin) { 16985 if (dumpState.onTitlePrinted()) 16986 pw.println(); 16987 pw.println("Database versions:"); 16988 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16989 } 16990 } 16991 16992 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16993 if (!checkin) { 16994 if (dumpState.onTitlePrinted()) 16995 pw.println(); 16996 pw.println("Verifiers:"); 16997 pw.print(" Required: "); 16998 pw.print(mRequiredVerifierPackage); 16999 pw.print(" (uid="); 17000 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17001 UserHandle.USER_SYSTEM)); 17002 pw.println(")"); 17003 } else if (mRequiredVerifierPackage != null) { 17004 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17005 pw.print(","); 17006 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17007 UserHandle.USER_SYSTEM)); 17008 } 17009 } 17010 17011 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17012 packageName == null) { 17013 if (mIntentFilterVerifierComponent != null) { 17014 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17015 if (!checkin) { 17016 if (dumpState.onTitlePrinted()) 17017 pw.println(); 17018 pw.println("Intent Filter Verifier:"); 17019 pw.print(" Using: "); 17020 pw.print(verifierPackageName); 17021 pw.print(" (uid="); 17022 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17023 UserHandle.USER_SYSTEM)); 17024 pw.println(")"); 17025 } else if (verifierPackageName != null) { 17026 pw.print("ifv,"); pw.print(verifierPackageName); 17027 pw.print(","); 17028 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17029 UserHandle.USER_SYSTEM)); 17030 } 17031 } else { 17032 pw.println(); 17033 pw.println("No Intent Filter Verifier available!"); 17034 } 17035 } 17036 17037 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17038 boolean printedHeader = false; 17039 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17040 while (it.hasNext()) { 17041 String name = it.next(); 17042 SharedLibraryEntry ent = mSharedLibraries.get(name); 17043 if (!checkin) { 17044 if (!printedHeader) { 17045 if (dumpState.onTitlePrinted()) 17046 pw.println(); 17047 pw.println("Libraries:"); 17048 printedHeader = true; 17049 } 17050 pw.print(" "); 17051 } else { 17052 pw.print("lib,"); 17053 } 17054 pw.print(name); 17055 if (!checkin) { 17056 pw.print(" -> "); 17057 } 17058 if (ent.path != null) { 17059 if (!checkin) { 17060 pw.print("(jar) "); 17061 pw.print(ent.path); 17062 } else { 17063 pw.print(",jar,"); 17064 pw.print(ent.path); 17065 } 17066 } else { 17067 if (!checkin) { 17068 pw.print("(apk) "); 17069 pw.print(ent.apk); 17070 } else { 17071 pw.print(",apk,"); 17072 pw.print(ent.apk); 17073 } 17074 } 17075 pw.println(); 17076 } 17077 } 17078 17079 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17080 if (dumpState.onTitlePrinted()) 17081 pw.println(); 17082 if (!checkin) { 17083 pw.println("Features:"); 17084 } 17085 17086 for (FeatureInfo feat : mAvailableFeatures.values()) { 17087 if (checkin) { 17088 pw.print("feat,"); 17089 pw.print(feat.name); 17090 pw.print(","); 17091 pw.println(feat.version); 17092 } else { 17093 pw.print(" "); 17094 pw.print(feat.name); 17095 if (feat.version > 0) { 17096 pw.print(" version="); 17097 pw.print(feat.version); 17098 } 17099 pw.println(); 17100 } 17101 } 17102 } 17103 17104 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17105 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17106 : "Activity Resolver Table:", " ", packageName, 17107 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17108 dumpState.setTitlePrinted(true); 17109 } 17110 } 17111 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17112 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17113 : "Receiver Resolver Table:", " ", packageName, 17114 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17115 dumpState.setTitlePrinted(true); 17116 } 17117 } 17118 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17119 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17120 : "Service Resolver Table:", " ", packageName, 17121 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17122 dumpState.setTitlePrinted(true); 17123 } 17124 } 17125 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17126 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17127 : "Provider Resolver Table:", " ", packageName, 17128 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17129 dumpState.setTitlePrinted(true); 17130 } 17131 } 17132 17133 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17134 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17135 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17136 int user = mSettings.mPreferredActivities.keyAt(i); 17137 if (pir.dump(pw, 17138 dumpState.getTitlePrinted() 17139 ? "\nPreferred Activities User " + user + ":" 17140 : "Preferred Activities User " + user + ":", " ", 17141 packageName, true, false)) { 17142 dumpState.setTitlePrinted(true); 17143 } 17144 } 17145 } 17146 17147 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17148 pw.flush(); 17149 FileOutputStream fout = new FileOutputStream(fd); 17150 BufferedOutputStream str = new BufferedOutputStream(fout); 17151 XmlSerializer serializer = new FastXmlSerializer(); 17152 try { 17153 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17154 serializer.startDocument(null, true); 17155 serializer.setFeature( 17156 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17157 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17158 serializer.endDocument(); 17159 serializer.flush(); 17160 } catch (IllegalArgumentException e) { 17161 pw.println("Failed writing: " + e); 17162 } catch (IllegalStateException e) { 17163 pw.println("Failed writing: " + e); 17164 } catch (IOException e) { 17165 pw.println("Failed writing: " + e); 17166 } 17167 } 17168 17169 if (!checkin 17170 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17171 && packageName == null) { 17172 pw.println(); 17173 int count = mSettings.mPackages.size(); 17174 if (count == 0) { 17175 pw.println("No applications!"); 17176 pw.println(); 17177 } else { 17178 final String prefix = " "; 17179 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17180 if (allPackageSettings.size() == 0) { 17181 pw.println("No domain preferred apps!"); 17182 pw.println(); 17183 } else { 17184 pw.println("App verification status:"); 17185 pw.println(); 17186 count = 0; 17187 for (PackageSetting ps : allPackageSettings) { 17188 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17189 if (ivi == null || ivi.getPackageName() == null) continue; 17190 pw.println(prefix + "Package: " + ivi.getPackageName()); 17191 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17192 pw.println(prefix + "Status: " + ivi.getStatusString()); 17193 pw.println(); 17194 count++; 17195 } 17196 if (count == 0) { 17197 pw.println(prefix + "No app verification established."); 17198 pw.println(); 17199 } 17200 for (int userId : sUserManager.getUserIds()) { 17201 pw.println("App linkages for user " + userId + ":"); 17202 pw.println(); 17203 count = 0; 17204 for (PackageSetting ps : allPackageSettings) { 17205 final long status = ps.getDomainVerificationStatusForUser(userId); 17206 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17207 continue; 17208 } 17209 pw.println(prefix + "Package: " + ps.name); 17210 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17211 String statusStr = IntentFilterVerificationInfo. 17212 getStatusStringFromValue(status); 17213 pw.println(prefix + "Status: " + statusStr); 17214 pw.println(); 17215 count++; 17216 } 17217 if (count == 0) { 17218 pw.println(prefix + "No configured app linkages."); 17219 pw.println(); 17220 } 17221 } 17222 } 17223 } 17224 } 17225 17226 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17227 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17228 if (packageName == null && permissionNames == null) { 17229 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17230 if (iperm == 0) { 17231 if (dumpState.onTitlePrinted()) 17232 pw.println(); 17233 pw.println("AppOp Permissions:"); 17234 } 17235 pw.print(" AppOp Permission "); 17236 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17237 pw.println(":"); 17238 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17239 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17240 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17241 } 17242 } 17243 } 17244 } 17245 17246 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17247 boolean printedSomething = false; 17248 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17249 if (packageName != null && !packageName.equals(p.info.packageName)) { 17250 continue; 17251 } 17252 if (!printedSomething) { 17253 if (dumpState.onTitlePrinted()) 17254 pw.println(); 17255 pw.println("Registered ContentProviders:"); 17256 printedSomething = true; 17257 } 17258 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17259 pw.print(" "); pw.println(p.toString()); 17260 } 17261 printedSomething = false; 17262 for (Map.Entry<String, PackageParser.Provider> entry : 17263 mProvidersByAuthority.entrySet()) { 17264 PackageParser.Provider p = entry.getValue(); 17265 if (packageName != null && !packageName.equals(p.info.packageName)) { 17266 continue; 17267 } 17268 if (!printedSomething) { 17269 if (dumpState.onTitlePrinted()) 17270 pw.println(); 17271 pw.println("ContentProvider Authorities:"); 17272 printedSomething = true; 17273 } 17274 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17275 pw.print(" "); pw.println(p.toString()); 17276 if (p.info != null && p.info.applicationInfo != null) { 17277 final String appInfo = p.info.applicationInfo.toString(); 17278 pw.print(" applicationInfo="); pw.println(appInfo); 17279 } 17280 } 17281 } 17282 17283 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17284 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17285 } 17286 17287 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17288 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17289 } 17290 17291 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17292 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17293 } 17294 17295 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17296 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17297 } 17298 17299 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17300 // XXX should handle packageName != null by dumping only install data that 17301 // the given package is involved with. 17302 if (dumpState.onTitlePrinted()) pw.println(); 17303 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17304 } 17305 17306 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17307 if (dumpState.onTitlePrinted()) pw.println(); 17308 mSettings.dumpReadMessagesLPr(pw, dumpState); 17309 17310 pw.println(); 17311 pw.println("Package warning messages:"); 17312 BufferedReader in = null; 17313 String line = null; 17314 try { 17315 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17316 while ((line = in.readLine()) != null) { 17317 if (line.contains("ignored: updated version")) continue; 17318 pw.println(line); 17319 } 17320 } catch (IOException ignored) { 17321 } finally { 17322 IoUtils.closeQuietly(in); 17323 } 17324 } 17325 17326 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17327 BufferedReader in = null; 17328 String line = null; 17329 try { 17330 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17331 while ((line = in.readLine()) != null) { 17332 if (line.contains("ignored: updated version")) continue; 17333 pw.print("msg,"); 17334 pw.println(line); 17335 } 17336 } catch (IOException ignored) { 17337 } finally { 17338 IoUtils.closeQuietly(in); 17339 } 17340 } 17341 } 17342 } 17343 17344 private String dumpDomainString(String packageName) { 17345 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17346 List<IntentFilter> filters = getAllIntentFilters(packageName); 17347 17348 ArraySet<String> result = new ArraySet<>(); 17349 if (iviList.size() > 0) { 17350 for (IntentFilterVerificationInfo ivi : iviList) { 17351 for (String host : ivi.getDomains()) { 17352 result.add(host); 17353 } 17354 } 17355 } 17356 if (filters != null && filters.size() > 0) { 17357 for (IntentFilter filter : filters) { 17358 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17359 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17360 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17361 result.addAll(filter.getHostsList()); 17362 } 17363 } 17364 } 17365 17366 StringBuilder sb = new StringBuilder(result.size() * 16); 17367 for (String domain : result) { 17368 if (sb.length() > 0) sb.append(" "); 17369 sb.append(domain); 17370 } 17371 return sb.toString(); 17372 } 17373 17374 // ------- apps on sdcard specific code ------- 17375 static final boolean DEBUG_SD_INSTALL = false; 17376 17377 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17378 17379 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17380 17381 private boolean mMediaMounted = false; 17382 17383 static String getEncryptKey() { 17384 try { 17385 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17386 SD_ENCRYPTION_KEYSTORE_NAME); 17387 if (sdEncKey == null) { 17388 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17389 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17390 if (sdEncKey == null) { 17391 Slog.e(TAG, "Failed to create encryption keys"); 17392 return null; 17393 } 17394 } 17395 return sdEncKey; 17396 } catch (NoSuchAlgorithmException nsae) { 17397 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17398 return null; 17399 } catch (IOException ioe) { 17400 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17401 return null; 17402 } 17403 } 17404 17405 /* 17406 * Update media status on PackageManager. 17407 */ 17408 @Override 17409 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17410 int callingUid = Binder.getCallingUid(); 17411 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17412 throw new SecurityException("Media status can only be updated by the system"); 17413 } 17414 // reader; this apparently protects mMediaMounted, but should probably 17415 // be a different lock in that case. 17416 synchronized (mPackages) { 17417 Log.i(TAG, "Updating external media status from " 17418 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17419 + (mediaStatus ? "mounted" : "unmounted")); 17420 if (DEBUG_SD_INSTALL) 17421 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17422 + ", mMediaMounted=" + mMediaMounted); 17423 if (mediaStatus == mMediaMounted) { 17424 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17425 : 0, -1); 17426 mHandler.sendMessage(msg); 17427 return; 17428 } 17429 mMediaMounted = mediaStatus; 17430 } 17431 // Queue up an async operation since the package installation may take a 17432 // little while. 17433 mHandler.post(new Runnable() { 17434 public void run() { 17435 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17436 } 17437 }); 17438 } 17439 17440 /** 17441 * Called by MountService when the initial ASECs to scan are available. 17442 * Should block until all the ASEC containers are finished being scanned. 17443 */ 17444 public void scanAvailableAsecs() { 17445 updateExternalMediaStatusInner(true, false, false); 17446 } 17447 17448 /* 17449 * Collect information of applications on external media, map them against 17450 * existing containers and update information based on current mount status. 17451 * Please note that we always have to report status if reportStatus has been 17452 * set to true especially when unloading packages. 17453 */ 17454 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17455 boolean externalStorage) { 17456 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17457 int[] uidArr = EmptyArray.INT; 17458 17459 final String[] list = PackageHelper.getSecureContainerList(); 17460 if (ArrayUtils.isEmpty(list)) { 17461 Log.i(TAG, "No secure containers found"); 17462 } else { 17463 // Process list of secure containers and categorize them 17464 // as active or stale based on their package internal state. 17465 17466 // reader 17467 synchronized (mPackages) { 17468 for (String cid : list) { 17469 // Leave stages untouched for now; installer service owns them 17470 if (PackageInstallerService.isStageName(cid)) continue; 17471 17472 if (DEBUG_SD_INSTALL) 17473 Log.i(TAG, "Processing container " + cid); 17474 String pkgName = getAsecPackageName(cid); 17475 if (pkgName == null) { 17476 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17477 continue; 17478 } 17479 if (DEBUG_SD_INSTALL) 17480 Log.i(TAG, "Looking for pkg : " + pkgName); 17481 17482 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17483 if (ps == null) { 17484 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17485 continue; 17486 } 17487 17488 /* 17489 * Skip packages that are not external if we're unmounting 17490 * external storage. 17491 */ 17492 if (externalStorage && !isMounted && !isExternal(ps)) { 17493 continue; 17494 } 17495 17496 final AsecInstallArgs args = new AsecInstallArgs(cid, 17497 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17498 // The package status is changed only if the code path 17499 // matches between settings and the container id. 17500 if (ps.codePathString != null 17501 && ps.codePathString.startsWith(args.getCodePath())) { 17502 if (DEBUG_SD_INSTALL) { 17503 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17504 + " at code path: " + ps.codePathString); 17505 } 17506 17507 // We do have a valid package installed on sdcard 17508 processCids.put(args, ps.codePathString); 17509 final int uid = ps.appId; 17510 if (uid != -1) { 17511 uidArr = ArrayUtils.appendInt(uidArr, uid); 17512 } 17513 } else { 17514 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17515 + ps.codePathString); 17516 } 17517 } 17518 } 17519 17520 Arrays.sort(uidArr); 17521 } 17522 17523 // Process packages with valid entries. 17524 if (isMounted) { 17525 if (DEBUG_SD_INSTALL) 17526 Log.i(TAG, "Loading packages"); 17527 loadMediaPackages(processCids, uidArr, externalStorage); 17528 startCleaningPackages(); 17529 mInstallerService.onSecureContainersAvailable(); 17530 } else { 17531 if (DEBUG_SD_INSTALL) 17532 Log.i(TAG, "Unloading packages"); 17533 unloadMediaPackages(processCids, uidArr, reportStatus); 17534 } 17535 } 17536 17537 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17538 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17539 final int size = infos.size(); 17540 final String[] packageNames = new String[size]; 17541 final int[] packageUids = new int[size]; 17542 for (int i = 0; i < size; i++) { 17543 final ApplicationInfo info = infos.get(i); 17544 packageNames[i] = info.packageName; 17545 packageUids[i] = info.uid; 17546 } 17547 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17548 finishedReceiver); 17549 } 17550 17551 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17552 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17553 sendResourcesChangedBroadcast(mediaStatus, replacing, 17554 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17555 } 17556 17557 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17558 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17559 int size = pkgList.length; 17560 if (size > 0) { 17561 // Send broadcasts here 17562 Bundle extras = new Bundle(); 17563 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17564 if (uidArr != null) { 17565 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17566 } 17567 if (replacing) { 17568 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17569 } 17570 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17571 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17572 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17573 } 17574 } 17575 17576 /* 17577 * Look at potentially valid container ids from processCids If package 17578 * information doesn't match the one on record or package scanning fails, 17579 * the cid is added to list of removeCids. We currently don't delete stale 17580 * containers. 17581 */ 17582 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17583 boolean externalStorage) { 17584 ArrayList<String> pkgList = new ArrayList<String>(); 17585 Set<AsecInstallArgs> keys = processCids.keySet(); 17586 17587 for (AsecInstallArgs args : keys) { 17588 String codePath = processCids.get(args); 17589 if (DEBUG_SD_INSTALL) 17590 Log.i(TAG, "Loading container : " + args.cid); 17591 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17592 try { 17593 // Make sure there are no container errors first. 17594 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17595 Slog.e(TAG, "Failed to mount cid : " + args.cid 17596 + " when installing from sdcard"); 17597 continue; 17598 } 17599 // Check code path here. 17600 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17601 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17602 + " does not match one in settings " + codePath); 17603 continue; 17604 } 17605 // Parse package 17606 int parseFlags = mDefParseFlags; 17607 if (args.isExternalAsec()) { 17608 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17609 } 17610 if (args.isFwdLocked()) { 17611 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17612 } 17613 17614 synchronized (mInstallLock) { 17615 PackageParser.Package pkg = null; 17616 try { 17617 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17618 } catch (PackageManagerException e) { 17619 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17620 } 17621 // Scan the package 17622 if (pkg != null) { 17623 /* 17624 * TODO why is the lock being held? doPostInstall is 17625 * called in other places without the lock. This needs 17626 * to be straightened out. 17627 */ 17628 // writer 17629 synchronized (mPackages) { 17630 retCode = PackageManager.INSTALL_SUCCEEDED; 17631 pkgList.add(pkg.packageName); 17632 // Post process args 17633 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17634 pkg.applicationInfo.uid); 17635 } 17636 } else { 17637 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17638 } 17639 } 17640 17641 } finally { 17642 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17643 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17644 } 17645 } 17646 } 17647 // writer 17648 synchronized (mPackages) { 17649 // If the platform SDK has changed since the last time we booted, 17650 // we need to re-grant app permission to catch any new ones that 17651 // appear. This is really a hack, and means that apps can in some 17652 // cases get permissions that the user didn't initially explicitly 17653 // allow... it would be nice to have some better way to handle 17654 // this situation. 17655 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17656 : mSettings.getInternalVersion(); 17657 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17658 : StorageManager.UUID_PRIVATE_INTERNAL; 17659 17660 int updateFlags = UPDATE_PERMISSIONS_ALL; 17661 if (ver.sdkVersion != mSdkVersion) { 17662 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17663 + mSdkVersion + "; regranting permissions for external"); 17664 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17665 } 17666 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17667 17668 // Yay, everything is now upgraded 17669 ver.forceCurrent(); 17670 17671 // can downgrade to reader 17672 // Persist settings 17673 mSettings.writeLPr(); 17674 } 17675 // Send a broadcast to let everyone know we are done processing 17676 if (pkgList.size() > 0) { 17677 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17678 } 17679 } 17680 17681 /* 17682 * Utility method to unload a list of specified containers 17683 */ 17684 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17685 // Just unmount all valid containers. 17686 for (AsecInstallArgs arg : cidArgs) { 17687 synchronized (mInstallLock) { 17688 arg.doPostDeleteLI(false); 17689 } 17690 } 17691 } 17692 17693 /* 17694 * Unload packages mounted on external media. This involves deleting package 17695 * data from internal structures, sending broadcasts about disabled packages, 17696 * gc'ing to free up references, unmounting all secure containers 17697 * corresponding to packages on external media, and posting a 17698 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17699 * that we always have to post this message if status has been requested no 17700 * matter what. 17701 */ 17702 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17703 final boolean reportStatus) { 17704 if (DEBUG_SD_INSTALL) 17705 Log.i(TAG, "unloading media packages"); 17706 ArrayList<String> pkgList = new ArrayList<String>(); 17707 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17708 final Set<AsecInstallArgs> keys = processCids.keySet(); 17709 for (AsecInstallArgs args : keys) { 17710 String pkgName = args.getPackageName(); 17711 if (DEBUG_SD_INSTALL) 17712 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17713 // Delete package internally 17714 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17715 synchronized (mInstallLock) { 17716 boolean res = deletePackageLI(pkgName, null, false, null, 17717 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17718 if (res) { 17719 pkgList.add(pkgName); 17720 } else { 17721 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17722 failedList.add(args); 17723 } 17724 } 17725 } 17726 17727 // reader 17728 synchronized (mPackages) { 17729 // We didn't update the settings after removing each package; 17730 // write them now for all packages. 17731 mSettings.writeLPr(); 17732 } 17733 17734 // We have to absolutely send UPDATED_MEDIA_STATUS only 17735 // after confirming that all the receivers processed the ordered 17736 // broadcast when packages get disabled, force a gc to clean things up. 17737 // and unload all the containers. 17738 if (pkgList.size() > 0) { 17739 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17740 new IIntentReceiver.Stub() { 17741 public void performReceive(Intent intent, int resultCode, String data, 17742 Bundle extras, boolean ordered, boolean sticky, 17743 int sendingUser) throws RemoteException { 17744 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17745 reportStatus ? 1 : 0, 1, keys); 17746 mHandler.sendMessage(msg); 17747 } 17748 }); 17749 } else { 17750 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17751 keys); 17752 mHandler.sendMessage(msg); 17753 } 17754 } 17755 17756 private void loadPrivatePackages(final VolumeInfo vol) { 17757 mHandler.post(new Runnable() { 17758 @Override 17759 public void run() { 17760 loadPrivatePackagesInner(vol); 17761 } 17762 }); 17763 } 17764 17765 private void loadPrivatePackagesInner(VolumeInfo vol) { 17766 final String volumeUuid = vol.fsUuid; 17767 if (TextUtils.isEmpty(volumeUuid)) { 17768 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17769 return; 17770 } 17771 17772 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17773 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17774 17775 final VersionInfo ver; 17776 final List<PackageSetting> packages; 17777 synchronized (mPackages) { 17778 ver = mSettings.findOrCreateVersion(volumeUuid); 17779 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17780 } 17781 17782 // TODO: introduce a new concept similar to "frozen" to prevent these 17783 // apps from being launched until after data has been fully reconciled 17784 for (PackageSetting ps : packages) { 17785 synchronized (mInstallLock) { 17786 final PackageParser.Package pkg; 17787 try { 17788 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17789 loaded.add(pkg.applicationInfo); 17790 17791 } catch (PackageManagerException e) { 17792 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17793 } 17794 17795 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17796 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17797 } 17798 } 17799 } 17800 17801 // Reconcile app data for all started/unlocked users 17802 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17803 final UserManager um = mContext.getSystemService(UserManager.class); 17804 for (UserInfo user : um.getUsers()) { 17805 final int flags; 17806 if (um.isUserUnlocked(user.id)) { 17807 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17808 } else if (um.isUserRunning(user.id)) { 17809 flags = StorageManager.FLAG_STORAGE_DE; 17810 } else { 17811 continue; 17812 } 17813 17814 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17815 reconcileAppsData(volumeUuid, user.id, flags); 17816 } 17817 17818 synchronized (mPackages) { 17819 int updateFlags = UPDATE_PERMISSIONS_ALL; 17820 if (ver.sdkVersion != mSdkVersion) { 17821 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17822 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17823 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17824 } 17825 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17826 17827 // Yay, everything is now upgraded 17828 ver.forceCurrent(); 17829 17830 mSettings.writeLPr(); 17831 } 17832 17833 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17834 sendResourcesChangedBroadcast(true, false, loaded, null); 17835 } 17836 17837 private void unloadPrivatePackages(final VolumeInfo vol) { 17838 mHandler.post(new Runnable() { 17839 @Override 17840 public void run() { 17841 unloadPrivatePackagesInner(vol); 17842 } 17843 }); 17844 } 17845 17846 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17847 final String volumeUuid = vol.fsUuid; 17848 if (TextUtils.isEmpty(volumeUuid)) { 17849 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17850 return; 17851 } 17852 17853 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17854 synchronized (mInstallLock) { 17855 synchronized (mPackages) { 17856 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17857 for (PackageSetting ps : packages) { 17858 if (ps.pkg == null) continue; 17859 17860 final ApplicationInfo info = ps.pkg.applicationInfo; 17861 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17862 if (deletePackageLI(ps.name, null, false, null, 17863 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17864 unloaded.add(info); 17865 } else { 17866 Slog.w(TAG, "Failed to unload " + ps.codePath); 17867 } 17868 } 17869 17870 mSettings.writeLPr(); 17871 } 17872 } 17873 17874 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17875 sendResourcesChangedBroadcast(false, false, unloaded, null); 17876 } 17877 17878 /** 17879 * Examine all users present on given mounted volume, and destroy data 17880 * belonging to users that are no longer valid, or whose user ID has been 17881 * recycled. 17882 */ 17883 private void reconcileUsers(String volumeUuid) { 17884 // TODO: also reconcile DE directories 17885 final File[] files = FileUtils 17886 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17887 for (File file : files) { 17888 if (!file.isDirectory()) continue; 17889 17890 final int userId; 17891 final UserInfo info; 17892 try { 17893 userId = Integer.parseInt(file.getName()); 17894 info = sUserManager.getUserInfo(userId); 17895 } catch (NumberFormatException e) { 17896 Slog.w(TAG, "Invalid user directory " + file); 17897 continue; 17898 } 17899 17900 boolean destroyUser = false; 17901 if (info == null) { 17902 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17903 + " because no matching user was found"); 17904 destroyUser = true; 17905 } else { 17906 try { 17907 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17908 } catch (IOException e) { 17909 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17910 + " because we failed to enforce serial number: " + e); 17911 destroyUser = true; 17912 } 17913 } 17914 17915 if (destroyUser) { 17916 synchronized (mInstallLock) { 17917 try { 17918 mInstaller.removeUserDataDirs(volumeUuid, userId); 17919 } catch (InstallerException e) { 17920 Slog.w(TAG, "Failed to clean up user dirs", e); 17921 } 17922 } 17923 } 17924 } 17925 } 17926 17927 private void assertPackageKnown(String volumeUuid, String packageName) 17928 throws PackageManagerException { 17929 synchronized (mPackages) { 17930 final PackageSetting ps = mSettings.mPackages.get(packageName); 17931 if (ps == null) { 17932 throw new PackageManagerException("Package " + packageName + " is unknown"); 17933 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17934 throw new PackageManagerException( 17935 "Package " + packageName + " found on unknown volume " + volumeUuid 17936 + "; expected volume " + ps.volumeUuid); 17937 } 17938 } 17939 } 17940 17941 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17942 throws PackageManagerException { 17943 synchronized (mPackages) { 17944 final PackageSetting ps = mSettings.mPackages.get(packageName); 17945 if (ps == null) { 17946 throw new PackageManagerException("Package " + packageName + " is unknown"); 17947 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17948 throw new PackageManagerException( 17949 "Package " + packageName + " found on unknown volume " + volumeUuid 17950 + "; expected volume " + ps.volumeUuid); 17951 } else if (!ps.getInstalled(userId)) { 17952 throw new PackageManagerException( 17953 "Package " + packageName + " not installed for user " + userId); 17954 } 17955 } 17956 } 17957 17958 /** 17959 * Examine all apps present on given mounted volume, and destroy apps that 17960 * aren't expected, either due to uninstallation or reinstallation on 17961 * another volume. 17962 */ 17963 private void reconcileApps(String volumeUuid) { 17964 final File[] files = FileUtils 17965 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17966 for (File file : files) { 17967 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17968 && !PackageInstallerService.isStageName(file.getName()); 17969 if (!isPackage) { 17970 // Ignore entries which are not packages 17971 continue; 17972 } 17973 17974 try { 17975 final PackageLite pkg = PackageParser.parsePackageLite(file, 17976 PackageParser.PARSE_MUST_BE_APK); 17977 assertPackageKnown(volumeUuid, pkg.packageName); 17978 17979 } catch (PackageParserException | PackageManagerException e) { 17980 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17981 synchronized (mInstallLock) { 17982 removeCodePathLI(file); 17983 } 17984 } 17985 } 17986 } 17987 17988 /** 17989 * Reconcile all app data for the given user. 17990 * <p> 17991 * Verifies that directories exist and that ownership and labeling is 17992 * correct for all installed apps on all mounted volumes. 17993 */ 17994 void reconcileAppsData(int userId, int flags) { 17995 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17996 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17997 final String volumeUuid = vol.getFsUuid(); 17998 reconcileAppsData(volumeUuid, userId, flags); 17999 } 18000 } 18001 18002 /** 18003 * Reconcile all app data on given mounted volume. 18004 * <p> 18005 * Destroys app data that isn't expected, either due to uninstallation or 18006 * reinstallation on another volume. 18007 * <p> 18008 * Verifies that directories exist and that ownership and labeling is 18009 * correct for all installed apps. 18010 */ 18011 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18012 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18013 + Integer.toHexString(flags)); 18014 18015 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18016 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18017 18018 boolean restoreconNeeded = false; 18019 18020 // First look for stale data that doesn't belong, and check if things 18021 // have changed since we did our last restorecon 18022 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18023 if (!isUserKeyUnlocked(userId)) { 18024 throw new RuntimeException( 18025 "Yikes, someone asked us to reconcile CE storage while " + userId 18026 + " was still locked; this would have caused massive data loss!"); 18027 } 18028 18029 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18030 18031 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18032 for (File file : files) { 18033 final String packageName = file.getName(); 18034 try { 18035 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18036 } catch (PackageManagerException e) { 18037 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18038 synchronized (mInstallLock) { 18039 destroyAppDataLI(volumeUuid, packageName, userId, 18040 StorageManager.FLAG_STORAGE_CE); 18041 } 18042 } 18043 } 18044 } 18045 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18046 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18047 18048 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18049 for (File file : files) { 18050 final String packageName = file.getName(); 18051 try { 18052 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18053 } catch (PackageManagerException e) { 18054 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18055 synchronized (mInstallLock) { 18056 destroyAppDataLI(volumeUuid, packageName, userId, 18057 StorageManager.FLAG_STORAGE_DE); 18058 } 18059 } 18060 } 18061 } 18062 18063 // Ensure that data directories are ready to roll for all packages 18064 // installed for this volume and user 18065 final List<PackageSetting> packages; 18066 synchronized (mPackages) { 18067 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18068 } 18069 int preparedCount = 0; 18070 for (PackageSetting ps : packages) { 18071 final String packageName = ps.name; 18072 if (ps.pkg == null) { 18073 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18074 // TODO: might be due to legacy ASEC apps; we should circle back 18075 // and reconcile again once they're scanned 18076 continue; 18077 } 18078 18079 if (ps.getInstalled(userId)) { 18080 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18081 18082 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18083 // We may have just shuffled around app data directories, so 18084 // prepare them one more time 18085 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18086 } 18087 18088 preparedCount++; 18089 } 18090 } 18091 18092 if (restoreconNeeded) { 18093 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18094 SELinuxMMAC.setRestoreconDone(ceDir); 18095 } 18096 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18097 SELinuxMMAC.setRestoreconDone(deDir); 18098 } 18099 } 18100 18101 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18102 + " packages; restoreconNeeded was " + restoreconNeeded); 18103 } 18104 18105 /** 18106 * Prepare app data for the given app just after it was installed or 18107 * upgraded. This method carefully only touches users that it's installed 18108 * for, and it forces a restorecon to handle any seinfo changes. 18109 * <p> 18110 * Verifies that directories exist and that ownership and labeling is 18111 * correct for all installed apps. If there is an ownership mismatch, it 18112 * will try recovering system apps by wiping data; third-party app data is 18113 * left intact. 18114 * <p> 18115 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18116 */ 18117 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18118 prepareAppDataAfterInstallInternal(pkg); 18119 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18120 for (int i = 0; i < childCount; i++) { 18121 PackageParser.Package childPackage = pkg.childPackages.get(i); 18122 prepareAppDataAfterInstallInternal(childPackage); 18123 } 18124 } 18125 18126 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18127 final PackageSetting ps; 18128 synchronized (mPackages) { 18129 ps = mSettings.mPackages.get(pkg.packageName); 18130 mSettings.writeKernelMappingLPr(ps); 18131 } 18132 18133 final UserManager um = mContext.getSystemService(UserManager.class); 18134 for (UserInfo user : um.getUsers()) { 18135 final int flags; 18136 if (um.isUserUnlocked(user.id)) { 18137 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18138 } else if (um.isUserRunning(user.id)) { 18139 flags = StorageManager.FLAG_STORAGE_DE; 18140 } else { 18141 continue; 18142 } 18143 18144 if (ps.getInstalled(user.id)) { 18145 // Whenever an app changes, force a restorecon of its data 18146 // TODO: when user data is locked, mark that we're still dirty 18147 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18148 } 18149 } 18150 } 18151 18152 /** 18153 * Prepare app data for the given app. 18154 * <p> 18155 * Verifies that directories exist and that ownership and labeling is 18156 * correct for all installed apps. If there is an ownership mismatch, this 18157 * will try recovering system apps by wiping data; third-party app data is 18158 * left intact. 18159 */ 18160 private void prepareAppData(String volumeUuid, int userId, int flags, 18161 PackageParser.Package pkg, boolean restoreconNeeded) { 18162 if (DEBUG_APP_DATA) { 18163 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18164 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18165 } 18166 18167 final String packageName = pkg.packageName; 18168 final ApplicationInfo app = pkg.applicationInfo; 18169 final int appId = UserHandle.getAppId(app.uid); 18170 18171 Preconditions.checkNotNull(app.seinfo); 18172 18173 synchronized (mInstallLock) { 18174 try { 18175 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18176 appId, app.seinfo, app.targetSdkVersion); 18177 } catch (InstallerException e) { 18178 if (app.isSystemApp()) { 18179 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18180 + ", but trying to recover: " + e); 18181 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18182 try { 18183 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18184 appId, app.seinfo, app.targetSdkVersion); 18185 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18186 } catch (InstallerException e2) { 18187 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18188 } 18189 } else { 18190 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18191 } 18192 } 18193 18194 if (restoreconNeeded) { 18195 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18196 } 18197 18198 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18199 // Create a native library symlink only if we have native libraries 18200 // and if the native libraries are 32 bit libraries. We do not provide 18201 // this symlink for 64 bit libraries. 18202 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18203 final String nativeLibPath = app.nativeLibraryDir; 18204 try { 18205 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18206 nativeLibPath, userId); 18207 } catch (InstallerException e) { 18208 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18209 } 18210 } 18211 } 18212 } 18213 } 18214 18215 /** 18216 * For system apps on non-FBE devices, this method migrates any existing 18217 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18218 * the app. 18219 */ 18220 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18221 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18222 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18223 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18224 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18225 synchronized (mInstallLock) { 18226 try { 18227 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18228 } catch (InstallerException e) { 18229 logCriticalInfo(Log.WARN, 18230 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18231 } 18232 } 18233 return true; 18234 } else { 18235 return false; 18236 } 18237 } 18238 18239 private void unfreezePackage(String packageName) { 18240 synchronized (mPackages) { 18241 final PackageSetting ps = mSettings.mPackages.get(packageName); 18242 if (ps != null) { 18243 ps.frozen = false; 18244 } 18245 } 18246 } 18247 18248 @Override 18249 public int movePackage(final String packageName, final String volumeUuid) { 18250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18251 18252 final int moveId = mNextMoveId.getAndIncrement(); 18253 mHandler.post(new Runnable() { 18254 @Override 18255 public void run() { 18256 try { 18257 movePackageInternal(packageName, volumeUuid, moveId); 18258 } catch (PackageManagerException e) { 18259 Slog.w(TAG, "Failed to move " + packageName, e); 18260 mMoveCallbacks.notifyStatusChanged(moveId, 18261 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18262 } 18263 } 18264 }); 18265 return moveId; 18266 } 18267 18268 private void movePackageInternal(final String packageName, final String volumeUuid, 18269 final int moveId) throws PackageManagerException { 18270 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18271 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18272 final PackageManager pm = mContext.getPackageManager(); 18273 18274 final boolean currentAsec; 18275 final String currentVolumeUuid; 18276 final File codeFile; 18277 final String installerPackageName; 18278 final String packageAbiOverride; 18279 final int appId; 18280 final String seinfo; 18281 final String label; 18282 final int targetSdkVersion; 18283 18284 // reader 18285 synchronized (mPackages) { 18286 final PackageParser.Package pkg = mPackages.get(packageName); 18287 final PackageSetting ps = mSettings.mPackages.get(packageName); 18288 if (pkg == null || ps == null) { 18289 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18290 } 18291 18292 if (pkg.applicationInfo.isSystemApp()) { 18293 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18294 "Cannot move system application"); 18295 } 18296 18297 if (pkg.applicationInfo.isExternalAsec()) { 18298 currentAsec = true; 18299 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18300 } else if (pkg.applicationInfo.isForwardLocked()) { 18301 currentAsec = true; 18302 currentVolumeUuid = "forward_locked"; 18303 } else { 18304 currentAsec = false; 18305 currentVolumeUuid = ps.volumeUuid; 18306 18307 final File probe = new File(pkg.codePath); 18308 final File probeOat = new File(probe, "oat"); 18309 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18310 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18311 "Move only supported for modern cluster style installs"); 18312 } 18313 } 18314 18315 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18316 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18317 "Package already moved to " + volumeUuid); 18318 } 18319 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18320 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18321 "Device admin cannot be moved"); 18322 } 18323 18324 if (ps.frozen) { 18325 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18326 "Failed to move already frozen package"); 18327 } 18328 ps.frozen = true; 18329 18330 codeFile = new File(pkg.codePath); 18331 installerPackageName = ps.installerPackageName; 18332 packageAbiOverride = ps.cpuAbiOverrideString; 18333 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18334 seinfo = pkg.applicationInfo.seinfo; 18335 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18336 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18337 } 18338 18339 // Now that we're guarded by frozen state, kill app during move 18340 final long token = Binder.clearCallingIdentity(); 18341 try { 18342 killApplication(packageName, appId, "move pkg"); 18343 } finally { 18344 Binder.restoreCallingIdentity(token); 18345 } 18346 18347 final Bundle extras = new Bundle(); 18348 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18349 extras.putString(Intent.EXTRA_TITLE, label); 18350 mMoveCallbacks.notifyCreated(moveId, extras); 18351 18352 int installFlags; 18353 final boolean moveCompleteApp; 18354 final File measurePath; 18355 18356 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18357 installFlags = INSTALL_INTERNAL; 18358 moveCompleteApp = !currentAsec; 18359 measurePath = Environment.getDataAppDirectory(volumeUuid); 18360 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18361 installFlags = INSTALL_EXTERNAL; 18362 moveCompleteApp = false; 18363 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18364 } else { 18365 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18366 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18367 || !volume.isMountedWritable()) { 18368 unfreezePackage(packageName); 18369 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18370 "Move location not mounted private volume"); 18371 } 18372 18373 Preconditions.checkState(!currentAsec); 18374 18375 installFlags = INSTALL_INTERNAL; 18376 moveCompleteApp = true; 18377 measurePath = Environment.getDataAppDirectory(volumeUuid); 18378 } 18379 18380 final PackageStats stats = new PackageStats(null, -1); 18381 synchronized (mInstaller) { 18382 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18383 unfreezePackage(packageName); 18384 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18385 "Failed to measure package size"); 18386 } 18387 } 18388 18389 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18390 + stats.dataSize); 18391 18392 final long startFreeBytes = measurePath.getFreeSpace(); 18393 final long sizeBytes; 18394 if (moveCompleteApp) { 18395 sizeBytes = stats.codeSize + stats.dataSize; 18396 } else { 18397 sizeBytes = stats.codeSize; 18398 } 18399 18400 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18401 unfreezePackage(packageName); 18402 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18403 "Not enough free space to move"); 18404 } 18405 18406 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18407 18408 final CountDownLatch installedLatch = new CountDownLatch(1); 18409 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18410 @Override 18411 public void onUserActionRequired(Intent intent) throws RemoteException { 18412 throw new IllegalStateException(); 18413 } 18414 18415 @Override 18416 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18417 Bundle extras) throws RemoteException { 18418 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18419 + PackageManager.installStatusToString(returnCode, msg)); 18420 18421 installedLatch.countDown(); 18422 18423 // Regardless of success or failure of the move operation, 18424 // always unfreeze the package 18425 unfreezePackage(packageName); 18426 18427 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18428 switch (status) { 18429 case PackageInstaller.STATUS_SUCCESS: 18430 mMoveCallbacks.notifyStatusChanged(moveId, 18431 PackageManager.MOVE_SUCCEEDED); 18432 break; 18433 case PackageInstaller.STATUS_FAILURE_STORAGE: 18434 mMoveCallbacks.notifyStatusChanged(moveId, 18435 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18436 break; 18437 default: 18438 mMoveCallbacks.notifyStatusChanged(moveId, 18439 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18440 break; 18441 } 18442 } 18443 }; 18444 18445 final MoveInfo move; 18446 if (moveCompleteApp) { 18447 // Kick off a thread to report progress estimates 18448 new Thread() { 18449 @Override 18450 public void run() { 18451 while (true) { 18452 try { 18453 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18454 break; 18455 } 18456 } catch (InterruptedException ignored) { 18457 } 18458 18459 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18460 final int progress = 10 + (int) MathUtils.constrain( 18461 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18462 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18463 } 18464 } 18465 }.start(); 18466 18467 final String dataAppName = codeFile.getName(); 18468 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18469 dataAppName, appId, seinfo, targetSdkVersion); 18470 } else { 18471 move = null; 18472 } 18473 18474 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18475 18476 final Message msg = mHandler.obtainMessage(INIT_COPY); 18477 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18478 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18479 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18480 packageAbiOverride, null); 18481 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18482 msg.obj = params; 18483 18484 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18485 System.identityHashCode(msg.obj)); 18486 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18487 System.identityHashCode(msg.obj)); 18488 18489 mHandler.sendMessage(msg); 18490 } 18491 18492 @Override 18493 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18494 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18495 18496 final int realMoveId = mNextMoveId.getAndIncrement(); 18497 final Bundle extras = new Bundle(); 18498 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18499 mMoveCallbacks.notifyCreated(realMoveId, extras); 18500 18501 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18502 @Override 18503 public void onCreated(int moveId, Bundle extras) { 18504 // Ignored 18505 } 18506 18507 @Override 18508 public void onStatusChanged(int moveId, int status, long estMillis) { 18509 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18510 } 18511 }; 18512 18513 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18514 storage.setPrimaryStorageUuid(volumeUuid, callback); 18515 return realMoveId; 18516 } 18517 18518 @Override 18519 public int getMoveStatus(int moveId) { 18520 mContext.enforceCallingOrSelfPermission( 18521 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18522 return mMoveCallbacks.mLastStatus.get(moveId); 18523 } 18524 18525 @Override 18526 public void registerMoveCallback(IPackageMoveObserver callback) { 18527 mContext.enforceCallingOrSelfPermission( 18528 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18529 mMoveCallbacks.register(callback); 18530 } 18531 18532 @Override 18533 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18534 mContext.enforceCallingOrSelfPermission( 18535 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18536 mMoveCallbacks.unregister(callback); 18537 } 18538 18539 @Override 18540 public boolean setInstallLocation(int loc) { 18541 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18542 null); 18543 if (getInstallLocation() == loc) { 18544 return true; 18545 } 18546 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18547 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18548 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18549 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18550 return true; 18551 } 18552 return false; 18553 } 18554 18555 @Override 18556 public int getInstallLocation() { 18557 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18558 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18559 PackageHelper.APP_INSTALL_AUTO); 18560 } 18561 18562 /** Called by UserManagerService */ 18563 void cleanUpUser(UserManagerService userManager, int userHandle) { 18564 synchronized (mPackages) { 18565 mDirtyUsers.remove(userHandle); 18566 mUserNeedsBadging.delete(userHandle); 18567 mSettings.removeUserLPw(userHandle); 18568 mPendingBroadcasts.remove(userHandle); 18569 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18570 } 18571 synchronized (mInstallLock) { 18572 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18573 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18574 final String volumeUuid = vol.getFsUuid(); 18575 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18576 try { 18577 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18578 } catch (InstallerException e) { 18579 Slog.w(TAG, "Failed to remove user data", e); 18580 } 18581 } 18582 synchronized (mPackages) { 18583 removeUnusedPackagesLILPw(userManager, userHandle); 18584 } 18585 } 18586 } 18587 18588 /** 18589 * We're removing userHandle and would like to remove any downloaded packages 18590 * that are no longer in use by any other user. 18591 * @param userHandle the user being removed 18592 */ 18593 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18594 final boolean DEBUG_CLEAN_APKS = false; 18595 int [] users = userManager.getUserIds(); 18596 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18597 while (psit.hasNext()) { 18598 PackageSetting ps = psit.next(); 18599 if (ps.pkg == null) { 18600 continue; 18601 } 18602 final String packageName = ps.pkg.packageName; 18603 // Skip over if system app 18604 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18605 continue; 18606 } 18607 if (DEBUG_CLEAN_APKS) { 18608 Slog.i(TAG, "Checking package " + packageName); 18609 } 18610 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18611 if (keep) { 18612 if (DEBUG_CLEAN_APKS) { 18613 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18614 } 18615 } else { 18616 for (int i = 0; i < users.length; i++) { 18617 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18618 keep = true; 18619 if (DEBUG_CLEAN_APKS) { 18620 Slog.i(TAG, " Keeping package " + packageName + " for user " 18621 + users[i]); 18622 } 18623 break; 18624 } 18625 } 18626 } 18627 if (!keep) { 18628 if (DEBUG_CLEAN_APKS) { 18629 Slog.i(TAG, " Removing package " + packageName); 18630 } 18631 mHandler.post(new Runnable() { 18632 public void run() { 18633 deletePackageX(packageName, userHandle, 0); 18634 } //end run 18635 }); 18636 } 18637 } 18638 } 18639 18640 /** Called by UserManagerService */ 18641 void createNewUser(int userHandle) { 18642 synchronized (mInstallLock) { 18643 try { 18644 mInstaller.createUserConfig(userHandle); 18645 } catch (InstallerException e) { 18646 Slog.w(TAG, "Failed to create user config", e); 18647 } 18648 mSettings.createNewUserLI(this, mInstaller, userHandle); 18649 } 18650 synchronized (mPackages) { 18651 applyFactoryDefaultBrowserLPw(userHandle); 18652 primeDomainVerificationsLPw(userHandle); 18653 } 18654 } 18655 18656 void newUserCreated(final int userHandle) { 18657 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18658 // If permission review for legacy apps is required, we represent 18659 // dagerous permissions for such apps as always granted runtime 18660 // permissions to keep per user flag state whether review is needed. 18661 // Hence, if a new user is added we have to propagate dangerous 18662 // permission grants for these legacy apps. 18663 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18664 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18665 | UPDATE_PERMISSIONS_REPLACE_ALL); 18666 } 18667 } 18668 18669 @Override 18670 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18671 mContext.enforceCallingOrSelfPermission( 18672 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18673 "Only package verification agents can read the verifier device identity"); 18674 18675 synchronized (mPackages) { 18676 return mSettings.getVerifierDeviceIdentityLPw(); 18677 } 18678 } 18679 18680 @Override 18681 public void setPermissionEnforced(String permission, boolean enforced) { 18682 // TODO: Now that we no longer change GID for storage, this should to away. 18683 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18684 "setPermissionEnforced"); 18685 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18686 synchronized (mPackages) { 18687 if (mSettings.mReadExternalStorageEnforced == null 18688 || mSettings.mReadExternalStorageEnforced != enforced) { 18689 mSettings.mReadExternalStorageEnforced = enforced; 18690 mSettings.writeLPr(); 18691 } 18692 } 18693 // kill any non-foreground processes so we restart them and 18694 // grant/revoke the GID. 18695 final IActivityManager am = ActivityManagerNative.getDefault(); 18696 if (am != null) { 18697 final long token = Binder.clearCallingIdentity(); 18698 try { 18699 am.killProcessesBelowForeground("setPermissionEnforcement"); 18700 } catch (RemoteException e) { 18701 } finally { 18702 Binder.restoreCallingIdentity(token); 18703 } 18704 } 18705 } else { 18706 throw new IllegalArgumentException("No selective enforcement for " + permission); 18707 } 18708 } 18709 18710 @Override 18711 @Deprecated 18712 public boolean isPermissionEnforced(String permission) { 18713 return true; 18714 } 18715 18716 @Override 18717 public boolean isStorageLow() { 18718 final long token = Binder.clearCallingIdentity(); 18719 try { 18720 final DeviceStorageMonitorInternal 18721 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18722 if (dsm != null) { 18723 return dsm.isMemoryLow(); 18724 } else { 18725 return false; 18726 } 18727 } finally { 18728 Binder.restoreCallingIdentity(token); 18729 } 18730 } 18731 18732 @Override 18733 public IPackageInstaller getPackageInstaller() { 18734 return mInstallerService; 18735 } 18736 18737 private boolean userNeedsBadging(int userId) { 18738 int index = mUserNeedsBadging.indexOfKey(userId); 18739 if (index < 0) { 18740 final UserInfo userInfo; 18741 final long token = Binder.clearCallingIdentity(); 18742 try { 18743 userInfo = sUserManager.getUserInfo(userId); 18744 } finally { 18745 Binder.restoreCallingIdentity(token); 18746 } 18747 final boolean b; 18748 if (userInfo != null && userInfo.isManagedProfile()) { 18749 b = true; 18750 } else { 18751 b = false; 18752 } 18753 mUserNeedsBadging.put(userId, b); 18754 return b; 18755 } 18756 return mUserNeedsBadging.valueAt(index); 18757 } 18758 18759 @Override 18760 public KeySet getKeySetByAlias(String packageName, String alias) { 18761 if (packageName == null || alias == null) { 18762 return null; 18763 } 18764 synchronized(mPackages) { 18765 final PackageParser.Package pkg = mPackages.get(packageName); 18766 if (pkg == null) { 18767 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18768 throw new IllegalArgumentException("Unknown package: " + packageName); 18769 } 18770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18771 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18772 } 18773 } 18774 18775 @Override 18776 public KeySet getSigningKeySet(String packageName) { 18777 if (packageName == null) { 18778 return null; 18779 } 18780 synchronized(mPackages) { 18781 final PackageParser.Package pkg = mPackages.get(packageName); 18782 if (pkg == null) { 18783 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18784 throw new IllegalArgumentException("Unknown package: " + packageName); 18785 } 18786 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18787 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18788 throw new SecurityException("May not access signing KeySet of other apps."); 18789 } 18790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18791 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18792 } 18793 } 18794 18795 @Override 18796 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18797 if (packageName == null || ks == null) { 18798 return false; 18799 } 18800 synchronized(mPackages) { 18801 final PackageParser.Package pkg = mPackages.get(packageName); 18802 if (pkg == null) { 18803 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18804 throw new IllegalArgumentException("Unknown package: " + packageName); 18805 } 18806 IBinder ksh = ks.getToken(); 18807 if (ksh instanceof KeySetHandle) { 18808 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18809 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18810 } 18811 return false; 18812 } 18813 } 18814 18815 @Override 18816 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18817 if (packageName == null || ks == null) { 18818 return false; 18819 } 18820 synchronized(mPackages) { 18821 final PackageParser.Package pkg = mPackages.get(packageName); 18822 if (pkg == null) { 18823 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18824 throw new IllegalArgumentException("Unknown package: " + packageName); 18825 } 18826 IBinder ksh = ks.getToken(); 18827 if (ksh instanceof KeySetHandle) { 18828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18829 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18830 } 18831 return false; 18832 } 18833 } 18834 18835 private void deletePackageIfUnusedLPr(final String packageName) { 18836 PackageSetting ps = mSettings.mPackages.get(packageName); 18837 if (ps == null) { 18838 return; 18839 } 18840 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18841 // TODO Implement atomic delete if package is unused 18842 // It is currently possible that the package will be deleted even if it is installed 18843 // after this method returns. 18844 mHandler.post(new Runnable() { 18845 public void run() { 18846 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18847 } 18848 }); 18849 } 18850 } 18851 18852 /** 18853 * Check and throw if the given before/after packages would be considered a 18854 * downgrade. 18855 */ 18856 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18857 throws PackageManagerException { 18858 if (after.versionCode < before.mVersionCode) { 18859 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18860 "Update version code " + after.versionCode + " is older than current " 18861 + before.mVersionCode); 18862 } else if (after.versionCode == before.mVersionCode) { 18863 if (after.baseRevisionCode < before.baseRevisionCode) { 18864 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18865 "Update base revision code " + after.baseRevisionCode 18866 + " is older than current " + before.baseRevisionCode); 18867 } 18868 18869 if (!ArrayUtils.isEmpty(after.splitNames)) { 18870 for (int i = 0; i < after.splitNames.length; i++) { 18871 final String splitName = after.splitNames[i]; 18872 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18873 if (j != -1) { 18874 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18875 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18876 "Update split " + splitName + " revision code " 18877 + after.splitRevisionCodes[i] + " is older than current " 18878 + before.splitRevisionCodes[j]); 18879 } 18880 } 18881 } 18882 } 18883 } 18884 } 18885 18886 private static class MoveCallbacks extends Handler { 18887 private static final int MSG_CREATED = 1; 18888 private static final int MSG_STATUS_CHANGED = 2; 18889 18890 private final RemoteCallbackList<IPackageMoveObserver> 18891 mCallbacks = new RemoteCallbackList<>(); 18892 18893 private final SparseIntArray mLastStatus = new SparseIntArray(); 18894 18895 public MoveCallbacks(Looper looper) { 18896 super(looper); 18897 } 18898 18899 public void register(IPackageMoveObserver callback) { 18900 mCallbacks.register(callback); 18901 } 18902 18903 public void unregister(IPackageMoveObserver callback) { 18904 mCallbacks.unregister(callback); 18905 } 18906 18907 @Override 18908 public void handleMessage(Message msg) { 18909 final SomeArgs args = (SomeArgs) msg.obj; 18910 final int n = mCallbacks.beginBroadcast(); 18911 for (int i = 0; i < n; i++) { 18912 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18913 try { 18914 invokeCallback(callback, msg.what, args); 18915 } catch (RemoteException ignored) { 18916 } 18917 } 18918 mCallbacks.finishBroadcast(); 18919 args.recycle(); 18920 } 18921 18922 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18923 throws RemoteException { 18924 switch (what) { 18925 case MSG_CREATED: { 18926 callback.onCreated(args.argi1, (Bundle) args.arg2); 18927 break; 18928 } 18929 case MSG_STATUS_CHANGED: { 18930 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18931 break; 18932 } 18933 } 18934 } 18935 18936 private void notifyCreated(int moveId, Bundle extras) { 18937 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18938 18939 final SomeArgs args = SomeArgs.obtain(); 18940 args.argi1 = moveId; 18941 args.arg2 = extras; 18942 obtainMessage(MSG_CREATED, args).sendToTarget(); 18943 } 18944 18945 private void notifyStatusChanged(int moveId, int status) { 18946 notifyStatusChanged(moveId, status, -1); 18947 } 18948 18949 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18950 Slog.v(TAG, "Move " + moveId + " status " + status); 18951 18952 final SomeArgs args = SomeArgs.obtain(); 18953 args.argi1 = moveId; 18954 args.argi2 = status; 18955 args.arg3 = estMillis; 18956 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18957 18958 synchronized (mLastStatus) { 18959 mLastStatus.put(moveId, status); 18960 } 18961 } 18962 } 18963 18964 private final static class OnPermissionChangeListeners extends Handler { 18965 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18966 18967 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18968 new RemoteCallbackList<>(); 18969 18970 public OnPermissionChangeListeners(Looper looper) { 18971 super(looper); 18972 } 18973 18974 @Override 18975 public void handleMessage(Message msg) { 18976 switch (msg.what) { 18977 case MSG_ON_PERMISSIONS_CHANGED: { 18978 final int uid = msg.arg1; 18979 handleOnPermissionsChanged(uid); 18980 } break; 18981 } 18982 } 18983 18984 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18985 mPermissionListeners.register(listener); 18986 18987 } 18988 18989 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18990 mPermissionListeners.unregister(listener); 18991 } 18992 18993 public void onPermissionsChanged(int uid) { 18994 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18995 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18996 } 18997 } 18998 18999 private void handleOnPermissionsChanged(int uid) { 19000 final int count = mPermissionListeners.beginBroadcast(); 19001 try { 19002 for (int i = 0; i < count; i++) { 19003 IOnPermissionsChangeListener callback = mPermissionListeners 19004 .getBroadcastItem(i); 19005 try { 19006 callback.onPermissionsChanged(uid); 19007 } catch (RemoteException e) { 19008 Log.e(TAG, "Permission listener is dead", e); 19009 } 19010 } 19011 } finally { 19012 mPermissionListeners.finishBroadcast(); 19013 } 19014 } 19015 } 19016 19017 private class PackageManagerInternalImpl extends PackageManagerInternal { 19018 @Override 19019 public void setLocationPackagesProvider(PackagesProvider provider) { 19020 synchronized (mPackages) { 19021 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19022 } 19023 } 19024 19025 @Override 19026 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19027 synchronized (mPackages) { 19028 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19029 } 19030 } 19031 19032 @Override 19033 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19034 synchronized (mPackages) { 19035 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19036 } 19037 } 19038 19039 @Override 19040 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19041 synchronized (mPackages) { 19042 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19043 } 19044 } 19045 19046 @Override 19047 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19048 synchronized (mPackages) { 19049 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19050 } 19051 } 19052 19053 @Override 19054 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19055 synchronized (mPackages) { 19056 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19057 } 19058 } 19059 19060 @Override 19061 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19062 synchronized (mPackages) { 19063 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19064 packageName, userId); 19065 } 19066 } 19067 19068 @Override 19069 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19070 synchronized (mPackages) { 19071 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19072 packageName, userId); 19073 } 19074 } 19075 19076 @Override 19077 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19078 synchronized (mPackages) { 19079 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19080 packageName, userId); 19081 } 19082 } 19083 19084 @Override 19085 public void setKeepUninstalledPackages(final List<String> packageList) { 19086 Preconditions.checkNotNull(packageList); 19087 List<String> removedFromList = null; 19088 synchronized (mPackages) { 19089 if (mKeepUninstalledPackages != null) { 19090 final int packagesCount = mKeepUninstalledPackages.size(); 19091 for (int i = 0; i < packagesCount; i++) { 19092 String oldPackage = mKeepUninstalledPackages.get(i); 19093 if (packageList != null && packageList.contains(oldPackage)) { 19094 continue; 19095 } 19096 if (removedFromList == null) { 19097 removedFromList = new ArrayList<>(); 19098 } 19099 removedFromList.add(oldPackage); 19100 } 19101 } 19102 mKeepUninstalledPackages = new ArrayList<>(packageList); 19103 if (removedFromList != null) { 19104 final int removedCount = removedFromList.size(); 19105 for (int i = 0; i < removedCount; i++) { 19106 deletePackageIfUnusedLPr(removedFromList.get(i)); 19107 } 19108 } 19109 } 19110 } 19111 19112 @Override 19113 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19114 synchronized (mPackages) { 19115 // If we do not support permission review, done. 19116 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19117 return false; 19118 } 19119 19120 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19121 if (packageSetting == null) { 19122 return false; 19123 } 19124 19125 // Permission review applies only to apps not supporting the new permission model. 19126 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19127 return false; 19128 } 19129 19130 // Legacy apps have the permission and get user consent on launch. 19131 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19132 return permissionsState.isPermissionReviewRequired(userId); 19133 } 19134 } 19135 } 19136 19137 @Override 19138 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19139 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19140 synchronized (mPackages) { 19141 final long identity = Binder.clearCallingIdentity(); 19142 try { 19143 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19144 packageNames, userId); 19145 } finally { 19146 Binder.restoreCallingIdentity(identity); 19147 } 19148 } 19149 } 19150 19151 private static void enforceSystemOrPhoneCaller(String tag) { 19152 int callingUid = Binder.getCallingUid(); 19153 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19154 throw new SecurityException( 19155 "Cannot call " + tag + " from UID " + callingUid); 19156 } 19157 } 19158 19159 boolean isHistoricalPackageUsageAvailable() { 19160 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19161 } 19162} 19163