PackageManagerService.java revision 925cc2a066889bb8b02493fafd5344bf8b2e9136
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 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4239 return true; 4240 } 4241 } 4242 } 4243 return false; 4244 } 4245 4246 @Override 4247 public int checkSignatures(String pkg1, String pkg2) { 4248 synchronized (mPackages) { 4249 final PackageParser.Package p1 = mPackages.get(pkg1); 4250 final PackageParser.Package p2 = mPackages.get(pkg2); 4251 if (p1 == null || p1.mExtras == null 4252 || p2 == null || p2.mExtras == null) { 4253 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4254 } 4255 return compareSignatures(p1.mSignatures, p2.mSignatures); 4256 } 4257 } 4258 4259 @Override 4260 public int checkUidSignatures(int uid1, int uid2) { 4261 // Map to base uids. 4262 uid1 = UserHandle.getAppId(uid1); 4263 uid2 = UserHandle.getAppId(uid2); 4264 // reader 4265 synchronized (mPackages) { 4266 Signature[] s1; 4267 Signature[] s2; 4268 Object obj = mSettings.getUserIdLPr(uid1); 4269 if (obj != null) { 4270 if (obj instanceof SharedUserSetting) { 4271 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4272 } else if (obj instanceof PackageSetting) { 4273 s1 = ((PackageSetting)obj).signatures.mSignatures; 4274 } else { 4275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4276 } 4277 } else { 4278 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4279 } 4280 obj = mSettings.getUserIdLPr(uid2); 4281 if (obj != null) { 4282 if (obj instanceof SharedUserSetting) { 4283 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4284 } else if (obj instanceof PackageSetting) { 4285 s2 = ((PackageSetting)obj).signatures.mSignatures; 4286 } else { 4287 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4288 } 4289 } else { 4290 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4291 } 4292 return compareSignatures(s1, s2); 4293 } 4294 } 4295 4296 private void killUid(int appId, int userId, String reason) { 4297 final long identity = Binder.clearCallingIdentity(); 4298 try { 4299 IActivityManager am = ActivityManagerNative.getDefault(); 4300 if (am != null) { 4301 try { 4302 am.killUid(appId, userId, reason); 4303 } catch (RemoteException e) { 4304 /* ignore - same process */ 4305 } 4306 } 4307 } finally { 4308 Binder.restoreCallingIdentity(identity); 4309 } 4310 } 4311 4312 /** 4313 * Compares two sets of signatures. Returns: 4314 * <br /> 4315 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4316 * <br /> 4317 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4318 * <br /> 4319 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4320 * <br /> 4321 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4322 * <br /> 4323 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4324 */ 4325 static int compareSignatures(Signature[] s1, Signature[] s2) { 4326 if (s1 == null) { 4327 return s2 == null 4328 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4329 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4330 } 4331 4332 if (s2 == null) { 4333 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4334 } 4335 4336 if (s1.length != s2.length) { 4337 return PackageManager.SIGNATURE_NO_MATCH; 4338 } 4339 4340 // Since both signature sets are of size 1, we can compare without HashSets. 4341 if (s1.length == 1) { 4342 return s1[0].equals(s2[0]) ? 4343 PackageManager.SIGNATURE_MATCH : 4344 PackageManager.SIGNATURE_NO_MATCH; 4345 } 4346 4347 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4348 for (Signature sig : s1) { 4349 set1.add(sig); 4350 } 4351 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4352 for (Signature sig : s2) { 4353 set2.add(sig); 4354 } 4355 // Make sure s2 contains all signatures in s1. 4356 if (set1.equals(set2)) { 4357 return PackageManager.SIGNATURE_MATCH; 4358 } 4359 return PackageManager.SIGNATURE_NO_MATCH; 4360 } 4361 4362 /** 4363 * If the database version for this type of package (internal storage or 4364 * external storage) is less than the version where package signatures 4365 * were updated, return true. 4366 */ 4367 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4368 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4369 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4370 } 4371 4372 /** 4373 * Used for backward compatibility to make sure any packages with 4374 * certificate chains get upgraded to the new style. {@code existingSigs} 4375 * will be in the old format (since they were stored on disk from before the 4376 * system upgrade) and {@code scannedSigs} will be in the newer format. 4377 */ 4378 private int compareSignaturesCompat(PackageSignatures existingSigs, 4379 PackageParser.Package scannedPkg) { 4380 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4381 return PackageManager.SIGNATURE_NO_MATCH; 4382 } 4383 4384 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4385 for (Signature sig : existingSigs.mSignatures) { 4386 existingSet.add(sig); 4387 } 4388 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4389 for (Signature sig : scannedPkg.mSignatures) { 4390 try { 4391 Signature[] chainSignatures = sig.getChainSignatures(); 4392 for (Signature chainSig : chainSignatures) { 4393 scannedCompatSet.add(chainSig); 4394 } 4395 } catch (CertificateEncodingException e) { 4396 scannedCompatSet.add(sig); 4397 } 4398 } 4399 /* 4400 * Make sure the expanded scanned set contains all signatures in the 4401 * existing one. 4402 */ 4403 if (scannedCompatSet.equals(existingSet)) { 4404 // Migrate the old signatures to the new scheme. 4405 existingSigs.assignSignatures(scannedPkg.mSignatures); 4406 // The new KeySets will be re-added later in the scanning process. 4407 synchronized (mPackages) { 4408 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4409 } 4410 return PackageManager.SIGNATURE_MATCH; 4411 } 4412 return PackageManager.SIGNATURE_NO_MATCH; 4413 } 4414 4415 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4416 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4417 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4418 } 4419 4420 private int compareSignaturesRecover(PackageSignatures existingSigs, 4421 PackageParser.Package scannedPkg) { 4422 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4423 return PackageManager.SIGNATURE_NO_MATCH; 4424 } 4425 4426 String msg = null; 4427 try { 4428 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4429 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4430 + scannedPkg.packageName); 4431 return PackageManager.SIGNATURE_MATCH; 4432 } 4433 } catch (CertificateException e) { 4434 msg = e.getMessage(); 4435 } 4436 4437 logCriticalInfo(Log.INFO, 4438 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4439 return PackageManager.SIGNATURE_NO_MATCH; 4440 } 4441 4442 @Override 4443 public String[] getPackagesForUid(int uid) { 4444 uid = UserHandle.getAppId(uid); 4445 // reader 4446 synchronized (mPackages) { 4447 Object obj = mSettings.getUserIdLPr(uid); 4448 if (obj instanceof SharedUserSetting) { 4449 final SharedUserSetting sus = (SharedUserSetting) obj; 4450 final int N = sus.packages.size(); 4451 final String[] res = new String[N]; 4452 final Iterator<PackageSetting> it = sus.packages.iterator(); 4453 int i = 0; 4454 while (it.hasNext()) { 4455 res[i++] = it.next().name; 4456 } 4457 return res; 4458 } else if (obj instanceof PackageSetting) { 4459 final PackageSetting ps = (PackageSetting) obj; 4460 return new String[] { ps.name }; 4461 } 4462 } 4463 return null; 4464 } 4465 4466 @Override 4467 public String getNameForUid(int uid) { 4468 // reader 4469 synchronized (mPackages) { 4470 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4471 if (obj instanceof SharedUserSetting) { 4472 final SharedUserSetting sus = (SharedUserSetting) obj; 4473 return sus.name + ":" + sus.userId; 4474 } else if (obj instanceof PackageSetting) { 4475 final PackageSetting ps = (PackageSetting) obj; 4476 return ps.name; 4477 } 4478 } 4479 return null; 4480 } 4481 4482 @Override 4483 public int getUidForSharedUser(String sharedUserName) { 4484 if(sharedUserName == null) { 4485 return -1; 4486 } 4487 // reader 4488 synchronized (mPackages) { 4489 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4490 if (suid == null) { 4491 return -1; 4492 } 4493 return suid.userId; 4494 } 4495 } 4496 4497 @Override 4498 public int getFlagsForUid(int uid) { 4499 synchronized (mPackages) { 4500 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4501 if (obj instanceof SharedUserSetting) { 4502 final SharedUserSetting sus = (SharedUserSetting) obj; 4503 return sus.pkgFlags; 4504 } else if (obj instanceof PackageSetting) { 4505 final PackageSetting ps = (PackageSetting) obj; 4506 return ps.pkgFlags; 4507 } 4508 } 4509 return 0; 4510 } 4511 4512 @Override 4513 public int getPrivateFlagsForUid(int uid) { 4514 synchronized (mPackages) { 4515 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4516 if (obj instanceof SharedUserSetting) { 4517 final SharedUserSetting sus = (SharedUserSetting) obj; 4518 return sus.pkgPrivateFlags; 4519 } else if (obj instanceof PackageSetting) { 4520 final PackageSetting ps = (PackageSetting) obj; 4521 return ps.pkgPrivateFlags; 4522 } 4523 } 4524 return 0; 4525 } 4526 4527 @Override 4528 public boolean isUidPrivileged(int uid) { 4529 uid = UserHandle.getAppId(uid); 4530 // reader 4531 synchronized (mPackages) { 4532 Object obj = mSettings.getUserIdLPr(uid); 4533 if (obj instanceof SharedUserSetting) { 4534 final SharedUserSetting sus = (SharedUserSetting) obj; 4535 final Iterator<PackageSetting> it = sus.packages.iterator(); 4536 while (it.hasNext()) { 4537 if (it.next().isPrivileged()) { 4538 return true; 4539 } 4540 } 4541 } else if (obj instanceof PackageSetting) { 4542 final PackageSetting ps = (PackageSetting) obj; 4543 return ps.isPrivileged(); 4544 } 4545 } 4546 return false; 4547 } 4548 4549 @Override 4550 public String[] getAppOpPermissionPackages(String permissionName) { 4551 synchronized (mPackages) { 4552 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4553 if (pkgs == null) { 4554 return null; 4555 } 4556 return pkgs.toArray(new String[pkgs.size()]); 4557 } 4558 } 4559 4560 @Override 4561 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4562 int flags, int userId) { 4563 if (!sUserManager.exists(userId)) return null; 4564 flags = updateFlagsForResolve(flags, userId, intent); 4565 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4566 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4567 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4568 final ResolveInfo bestChoice = 4569 chooseBestActivity(intent, resolvedType, flags, query, userId); 4570 4571 if (isEphemeralAllowed(intent, query, userId)) { 4572 final EphemeralResolveInfo ai = 4573 getEphemeralResolveInfo(intent, resolvedType, userId); 4574 if (ai != null) { 4575 if (DEBUG_EPHEMERAL) { 4576 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4577 } 4578 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4579 bestChoice.ephemeralResolveInfo = ai; 4580 } 4581 } 4582 return bestChoice; 4583 } 4584 4585 @Override 4586 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4587 IntentFilter filter, int match, ComponentName activity) { 4588 final int userId = UserHandle.getCallingUserId(); 4589 if (DEBUG_PREFERRED) { 4590 Log.v(TAG, "setLastChosenActivity intent=" + intent 4591 + " resolvedType=" + resolvedType 4592 + " flags=" + flags 4593 + " filter=" + filter 4594 + " match=" + match 4595 + " activity=" + activity); 4596 filter.dump(new PrintStreamPrinter(System.out), " "); 4597 } 4598 intent.setComponent(null); 4599 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4600 // Find any earlier preferred or last chosen entries and nuke them 4601 findPreferredActivity(intent, resolvedType, 4602 flags, query, 0, false, true, false, userId); 4603 // Add the new activity as the last chosen for this filter 4604 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4605 "Setting last chosen"); 4606 } 4607 4608 @Override 4609 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4610 final int userId = UserHandle.getCallingUserId(); 4611 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4612 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4613 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4614 false, false, false, userId); 4615 } 4616 4617 4618 private boolean isEphemeralAllowed( 4619 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4620 // Short circuit and return early if possible. 4621 if (DISABLE_EPHEMERAL_APPS) { 4622 return false; 4623 } 4624 final int callingUser = UserHandle.getCallingUserId(); 4625 if (callingUser != UserHandle.USER_SYSTEM) { 4626 return false; 4627 } 4628 if (mEphemeralResolverConnection == null) { 4629 return false; 4630 } 4631 if (intent.getComponent() != null) { 4632 return false; 4633 } 4634 if (intent.getPackage() != null) { 4635 return false; 4636 } 4637 final boolean isWebUri = hasWebURI(intent); 4638 if (!isWebUri) { 4639 return false; 4640 } 4641 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4642 synchronized (mPackages) { 4643 final int count = resolvedActivites.size(); 4644 for (int n = 0; n < count; n++) { 4645 ResolveInfo info = resolvedActivites.get(n); 4646 String packageName = info.activityInfo.packageName; 4647 PackageSetting ps = mSettings.mPackages.get(packageName); 4648 if (ps != null) { 4649 // Try to get the status from User settings first 4650 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4651 int status = (int) (packedStatus >> 32); 4652 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4653 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4654 if (DEBUG_EPHEMERAL) { 4655 Slog.v(TAG, "DENY ephemeral apps;" 4656 + " pkg: " + packageName + ", status: " + status); 4657 } 4658 return false; 4659 } 4660 } 4661 } 4662 } 4663 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4664 return true; 4665 } 4666 4667 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4668 int userId) { 4669 MessageDigest digest = null; 4670 try { 4671 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4672 } catch (NoSuchAlgorithmException e) { 4673 // If we can't create a digest, ignore ephemeral apps. 4674 return null; 4675 } 4676 4677 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4678 final byte[] digestBytes = digest.digest(hostBytes); 4679 int shaPrefix = 4680 digestBytes[0] << 24 4681 | digestBytes[1] << 16 4682 | digestBytes[2] << 8 4683 | digestBytes[3] << 0; 4684 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4685 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4686 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4687 // No hash prefix match; there are no ephemeral apps for this domain. 4688 return null; 4689 } 4690 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4691 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4692 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4693 continue; 4694 } 4695 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4696 // No filters; this should never happen. 4697 if (filters.isEmpty()) { 4698 continue; 4699 } 4700 // We have a domain match; resolve the filters to see if anything matches. 4701 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4702 for (int j = filters.size() - 1; j >= 0; --j) { 4703 final EphemeralResolveIntentInfo intentInfo = 4704 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4705 ephemeralResolver.addFilter(intentInfo); 4706 } 4707 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4708 intent, resolvedType, false /*defaultOnly*/, userId); 4709 if (!matchedResolveInfoList.isEmpty()) { 4710 return matchedResolveInfoList.get(0); 4711 } 4712 } 4713 // Hash or filter mis-match; no ephemeral apps for this domain. 4714 return null; 4715 } 4716 4717 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4718 int flags, List<ResolveInfo> query, int userId) { 4719 if (query != null) { 4720 final int N = query.size(); 4721 if (N == 1) { 4722 return query.get(0); 4723 } else if (N > 1) { 4724 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4725 // If there is more than one activity with the same priority, 4726 // then let the user decide between them. 4727 ResolveInfo r0 = query.get(0); 4728 ResolveInfo r1 = query.get(1); 4729 if (DEBUG_INTENT_MATCHING || debug) { 4730 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4731 + r1.activityInfo.name + "=" + r1.priority); 4732 } 4733 // If the first activity has a higher priority, or a different 4734 // default, then it is always desirable to pick it. 4735 if (r0.priority != r1.priority 4736 || r0.preferredOrder != r1.preferredOrder 4737 || r0.isDefault != r1.isDefault) { 4738 return query.get(0); 4739 } 4740 // If we have saved a preference for a preferred activity for 4741 // this Intent, use that. 4742 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4743 flags, query, r0.priority, true, false, debug, userId); 4744 if (ri != null) { 4745 return ri; 4746 } 4747 ri = new ResolveInfo(mResolveInfo); 4748 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4749 ri.activityInfo.applicationInfo = new ApplicationInfo( 4750 ri.activityInfo.applicationInfo); 4751 if (userId != 0) { 4752 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4753 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4754 } 4755 // Make sure that the resolver is displayable in car mode 4756 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4757 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4758 return ri; 4759 } 4760 } 4761 return null; 4762 } 4763 4764 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4765 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4766 final int N = query.size(); 4767 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4768 .get(userId); 4769 // Get the list of persistent preferred activities that handle the intent 4770 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4771 List<PersistentPreferredActivity> pprefs = ppir != null 4772 ? ppir.queryIntent(intent, resolvedType, 4773 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4774 : null; 4775 if (pprefs != null && pprefs.size() > 0) { 4776 final int M = pprefs.size(); 4777 for (int i=0; i<M; i++) { 4778 final PersistentPreferredActivity ppa = pprefs.get(i); 4779 if (DEBUG_PREFERRED || debug) { 4780 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4781 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4782 + "\n component=" + ppa.mComponent); 4783 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4784 } 4785 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4786 flags | MATCH_DISABLED_COMPONENTS, userId); 4787 if (DEBUG_PREFERRED || debug) { 4788 Slog.v(TAG, "Found persistent preferred activity:"); 4789 if (ai != null) { 4790 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4791 } else { 4792 Slog.v(TAG, " null"); 4793 } 4794 } 4795 if (ai == null) { 4796 // This previously registered persistent preferred activity 4797 // component is no longer known. Ignore it and do NOT remove it. 4798 continue; 4799 } 4800 for (int j=0; j<N; j++) { 4801 final ResolveInfo ri = query.get(j); 4802 if (!ri.activityInfo.applicationInfo.packageName 4803 .equals(ai.applicationInfo.packageName)) { 4804 continue; 4805 } 4806 if (!ri.activityInfo.name.equals(ai.name)) { 4807 continue; 4808 } 4809 // Found a persistent preference that can handle the intent. 4810 if (DEBUG_PREFERRED || debug) { 4811 Slog.v(TAG, "Returning persistent preferred activity: " + 4812 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4813 } 4814 return ri; 4815 } 4816 } 4817 } 4818 return null; 4819 } 4820 4821 // TODO: handle preferred activities missing while user has amnesia 4822 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4823 List<ResolveInfo> query, int priority, boolean always, 4824 boolean removeMatches, boolean debug, int userId) { 4825 if (!sUserManager.exists(userId)) return null; 4826 flags = updateFlagsForResolve(flags, userId, intent); 4827 // writer 4828 synchronized (mPackages) { 4829 if (intent.getSelector() != null) { 4830 intent = intent.getSelector(); 4831 } 4832 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4833 4834 // Try to find a matching persistent preferred activity. 4835 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4836 debug, userId); 4837 4838 // If a persistent preferred activity matched, use it. 4839 if (pri != null) { 4840 return pri; 4841 } 4842 4843 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4844 // Get the list of preferred activities that handle the intent 4845 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4846 List<PreferredActivity> prefs = pir != null 4847 ? pir.queryIntent(intent, resolvedType, 4848 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4849 : null; 4850 if (prefs != null && prefs.size() > 0) { 4851 boolean changed = false; 4852 try { 4853 // First figure out how good the original match set is. 4854 // We will only allow preferred activities that came 4855 // from the same match quality. 4856 int match = 0; 4857 4858 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4859 4860 final int N = query.size(); 4861 for (int j=0; j<N; j++) { 4862 final ResolveInfo ri = query.get(j); 4863 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4864 + ": 0x" + Integer.toHexString(match)); 4865 if (ri.match > match) { 4866 match = ri.match; 4867 } 4868 } 4869 4870 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4871 + Integer.toHexString(match)); 4872 4873 match &= IntentFilter.MATCH_CATEGORY_MASK; 4874 final int M = prefs.size(); 4875 for (int i=0; i<M; i++) { 4876 final PreferredActivity pa = prefs.get(i); 4877 if (DEBUG_PREFERRED || debug) { 4878 Slog.v(TAG, "Checking PreferredActivity ds=" 4879 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4880 + "\n component=" + pa.mPref.mComponent); 4881 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4882 } 4883 if (pa.mPref.mMatch != match) { 4884 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4885 + Integer.toHexString(pa.mPref.mMatch)); 4886 continue; 4887 } 4888 // If it's not an "always" type preferred activity and that's what we're 4889 // looking for, skip it. 4890 if (always && !pa.mPref.mAlways) { 4891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4892 continue; 4893 } 4894 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4895 flags | MATCH_DISABLED_COMPONENTS, userId); 4896 if (DEBUG_PREFERRED || debug) { 4897 Slog.v(TAG, "Found preferred activity:"); 4898 if (ai != null) { 4899 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4900 } else { 4901 Slog.v(TAG, " null"); 4902 } 4903 } 4904 if (ai == null) { 4905 // This previously registered preferred activity 4906 // component is no longer known. Most likely an update 4907 // to the app was installed and in the new version this 4908 // component no longer exists. Clean it up by removing 4909 // it from the preferred activities list, and skip it. 4910 Slog.w(TAG, "Removing dangling preferred activity: " 4911 + pa.mPref.mComponent); 4912 pir.removeFilter(pa); 4913 changed = true; 4914 continue; 4915 } 4916 for (int j=0; j<N; j++) { 4917 final ResolveInfo ri = query.get(j); 4918 if (!ri.activityInfo.applicationInfo.packageName 4919 .equals(ai.applicationInfo.packageName)) { 4920 continue; 4921 } 4922 if (!ri.activityInfo.name.equals(ai.name)) { 4923 continue; 4924 } 4925 4926 if (removeMatches) { 4927 pir.removeFilter(pa); 4928 changed = true; 4929 if (DEBUG_PREFERRED) { 4930 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4931 } 4932 break; 4933 } 4934 4935 // Okay we found a previously set preferred or last chosen app. 4936 // If the result set is different from when this 4937 // was created, we need to clear it and re-ask the 4938 // user their preference, if we're looking for an "always" type entry. 4939 if (always && !pa.mPref.sameSet(query)) { 4940 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4941 + intent + " type " + resolvedType); 4942 if (DEBUG_PREFERRED) { 4943 Slog.v(TAG, "Removing preferred activity since set changed " 4944 + pa.mPref.mComponent); 4945 } 4946 pir.removeFilter(pa); 4947 // Re-add the filter as a "last chosen" entry (!always) 4948 PreferredActivity lastChosen = new PreferredActivity( 4949 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4950 pir.addFilter(lastChosen); 4951 changed = true; 4952 return null; 4953 } 4954 4955 // Yay! Either the set matched or we're looking for the last chosen 4956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4957 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4958 return ri; 4959 } 4960 } 4961 } finally { 4962 if (changed) { 4963 if (DEBUG_PREFERRED) { 4964 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4965 } 4966 scheduleWritePackageRestrictionsLocked(userId); 4967 } 4968 } 4969 } 4970 } 4971 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4972 return null; 4973 } 4974 4975 /* 4976 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4977 */ 4978 @Override 4979 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4980 int targetUserId) { 4981 mContext.enforceCallingOrSelfPermission( 4982 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4983 List<CrossProfileIntentFilter> matches = 4984 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4985 if (matches != null) { 4986 int size = matches.size(); 4987 for (int i = 0; i < size; i++) { 4988 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4989 } 4990 } 4991 if (hasWebURI(intent)) { 4992 // cross-profile app linking works only towards the parent. 4993 final UserInfo parent = getProfileParent(sourceUserId); 4994 synchronized(mPackages) { 4995 int flags = updateFlagsForResolve(0, parent.id, intent); 4996 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4997 intent, resolvedType, flags, sourceUserId, parent.id); 4998 return xpDomainInfo != null; 4999 } 5000 } 5001 return false; 5002 } 5003 5004 private UserInfo getProfileParent(int userId) { 5005 final long identity = Binder.clearCallingIdentity(); 5006 try { 5007 return sUserManager.getProfileParent(userId); 5008 } finally { 5009 Binder.restoreCallingIdentity(identity); 5010 } 5011 } 5012 5013 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5014 String resolvedType, int userId) { 5015 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5016 if (resolver != null) { 5017 return resolver.queryIntent(intent, resolvedType, false, userId); 5018 } 5019 return null; 5020 } 5021 5022 @Override 5023 public List<ResolveInfo> queryIntentActivities(Intent intent, 5024 String resolvedType, int flags, int userId) { 5025 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5026 flags = updateFlagsForResolve(flags, userId, intent); 5027 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5028 false /* requireFullPermission */, false /* checkShell */, 5029 "query intent activities"); 5030 ComponentName comp = intent.getComponent(); 5031 if (comp == null) { 5032 if (intent.getSelector() != null) { 5033 intent = intent.getSelector(); 5034 comp = intent.getComponent(); 5035 } 5036 } 5037 5038 if (comp != null) { 5039 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5040 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5041 if (ai != null) { 5042 final ResolveInfo ri = new ResolveInfo(); 5043 ri.activityInfo = ai; 5044 list.add(ri); 5045 } 5046 return list; 5047 } 5048 5049 // reader 5050 synchronized (mPackages) { 5051 final String pkgName = intent.getPackage(); 5052 if (pkgName == null) { 5053 List<CrossProfileIntentFilter> matchingFilters = 5054 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5055 // Check for results that need to skip the current profile. 5056 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5057 resolvedType, flags, userId); 5058 if (xpResolveInfo != null) { 5059 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5060 result.add(xpResolveInfo); 5061 return filterIfNotSystemUser(result, userId); 5062 } 5063 5064 // Check for results in the current profile. 5065 List<ResolveInfo> result = mActivities.queryIntent( 5066 intent, resolvedType, flags, userId); 5067 result = filterIfNotSystemUser(result, userId); 5068 5069 // Check for cross profile results. 5070 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5071 xpResolveInfo = queryCrossProfileIntents( 5072 matchingFilters, intent, resolvedType, flags, userId, 5073 hasNonNegativePriorityResult); 5074 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5075 boolean isVisibleToUser = filterIfNotSystemUser( 5076 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5077 if (isVisibleToUser) { 5078 result.add(xpResolveInfo); 5079 Collections.sort(result, mResolvePrioritySorter); 5080 } 5081 } 5082 if (hasWebURI(intent)) { 5083 CrossProfileDomainInfo xpDomainInfo = null; 5084 final UserInfo parent = getProfileParent(userId); 5085 if (parent != null) { 5086 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5087 flags, userId, parent.id); 5088 } 5089 if (xpDomainInfo != null) { 5090 if (xpResolveInfo != null) { 5091 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5092 // in the result. 5093 result.remove(xpResolveInfo); 5094 } 5095 if (result.size() == 0) { 5096 result.add(xpDomainInfo.resolveInfo); 5097 return result; 5098 } 5099 } else if (result.size() <= 1) { 5100 return result; 5101 } 5102 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5103 xpDomainInfo, userId); 5104 Collections.sort(result, mResolvePrioritySorter); 5105 } 5106 return result; 5107 } 5108 final PackageParser.Package pkg = mPackages.get(pkgName); 5109 if (pkg != null) { 5110 return filterIfNotSystemUser( 5111 mActivities.queryIntentForPackage( 5112 intent, resolvedType, flags, pkg.activities, userId), 5113 userId); 5114 } 5115 return new ArrayList<ResolveInfo>(); 5116 } 5117 } 5118 5119 private static class CrossProfileDomainInfo { 5120 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5121 ResolveInfo resolveInfo; 5122 /* Best domain verification status of the activities found in the other profile */ 5123 int bestDomainVerificationStatus; 5124 } 5125 5126 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5127 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5128 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5129 sourceUserId)) { 5130 return null; 5131 } 5132 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5133 resolvedType, flags, parentUserId); 5134 5135 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5136 return null; 5137 } 5138 CrossProfileDomainInfo result = null; 5139 int size = resultTargetUser.size(); 5140 for (int i = 0; i < size; i++) { 5141 ResolveInfo riTargetUser = resultTargetUser.get(i); 5142 // Intent filter verification is only for filters that specify a host. So don't return 5143 // those that handle all web uris. 5144 if (riTargetUser.handleAllWebDataURI) { 5145 continue; 5146 } 5147 String packageName = riTargetUser.activityInfo.packageName; 5148 PackageSetting ps = mSettings.mPackages.get(packageName); 5149 if (ps == null) { 5150 continue; 5151 } 5152 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5153 int status = (int)(verificationState >> 32); 5154 if (result == null) { 5155 result = new CrossProfileDomainInfo(); 5156 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5157 sourceUserId, parentUserId); 5158 result.bestDomainVerificationStatus = status; 5159 } else { 5160 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5161 result.bestDomainVerificationStatus); 5162 } 5163 } 5164 // Don't consider matches with status NEVER across profiles. 5165 if (result != null && result.bestDomainVerificationStatus 5166 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5167 return null; 5168 } 5169 return result; 5170 } 5171 5172 /** 5173 * Verification statuses are ordered from the worse to the best, except for 5174 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5175 */ 5176 private int bestDomainVerificationStatus(int status1, int status2) { 5177 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5178 return status2; 5179 } 5180 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5181 return status1; 5182 } 5183 return (int) MathUtils.max(status1, status2); 5184 } 5185 5186 private boolean isUserEnabled(int userId) { 5187 long callingId = Binder.clearCallingIdentity(); 5188 try { 5189 UserInfo userInfo = sUserManager.getUserInfo(userId); 5190 return userInfo != null && userInfo.isEnabled(); 5191 } finally { 5192 Binder.restoreCallingIdentity(callingId); 5193 } 5194 } 5195 5196 /** 5197 * Filter out activities with systemUserOnly flag set, when current user is not System. 5198 * 5199 * @return filtered list 5200 */ 5201 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5202 if (userId == UserHandle.USER_SYSTEM) { 5203 return resolveInfos; 5204 } 5205 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5206 ResolveInfo info = resolveInfos.get(i); 5207 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5208 resolveInfos.remove(i); 5209 } 5210 } 5211 return resolveInfos; 5212 } 5213 5214 /** 5215 * @param resolveInfos list of resolve infos in descending priority order 5216 * @return if the list contains a resolve info with non-negative priority 5217 */ 5218 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5219 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5220 } 5221 5222 private static boolean hasWebURI(Intent intent) { 5223 if (intent.getData() == null) { 5224 return false; 5225 } 5226 final String scheme = intent.getScheme(); 5227 if (TextUtils.isEmpty(scheme)) { 5228 return false; 5229 } 5230 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5231 } 5232 5233 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5234 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5235 int userId) { 5236 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5237 5238 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5239 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5240 candidates.size()); 5241 } 5242 5243 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5244 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5245 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5246 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5247 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5248 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5249 5250 synchronized (mPackages) { 5251 final int count = candidates.size(); 5252 // First, try to use linked apps. Partition the candidates into four lists: 5253 // one for the final results, one for the "do not use ever", one for "undefined status" 5254 // and finally one for "browser app type". 5255 for (int n=0; n<count; n++) { 5256 ResolveInfo info = candidates.get(n); 5257 String packageName = info.activityInfo.packageName; 5258 PackageSetting ps = mSettings.mPackages.get(packageName); 5259 if (ps != null) { 5260 // Add to the special match all list (Browser use case) 5261 if (info.handleAllWebDataURI) { 5262 matchAllList.add(info); 5263 continue; 5264 } 5265 // Try to get the status from User settings first 5266 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5267 int status = (int)(packedStatus >> 32); 5268 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5269 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5270 if (DEBUG_DOMAIN_VERIFICATION) { 5271 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5272 + " : linkgen=" + linkGeneration); 5273 } 5274 // Use link-enabled generation as preferredOrder, i.e. 5275 // prefer newly-enabled over earlier-enabled. 5276 info.preferredOrder = linkGeneration; 5277 alwaysList.add(info); 5278 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5279 if (DEBUG_DOMAIN_VERIFICATION) { 5280 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5281 } 5282 neverList.add(info); 5283 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5284 if (DEBUG_DOMAIN_VERIFICATION) { 5285 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5286 } 5287 alwaysAskList.add(info); 5288 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5289 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5290 if (DEBUG_DOMAIN_VERIFICATION) { 5291 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5292 } 5293 undefinedList.add(info); 5294 } 5295 } 5296 } 5297 5298 // We'll want to include browser possibilities in a few cases 5299 boolean includeBrowser = false; 5300 5301 // First try to add the "always" resolution(s) for the current user, if any 5302 if (alwaysList.size() > 0) { 5303 result.addAll(alwaysList); 5304 } else { 5305 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5306 result.addAll(undefinedList); 5307 // Maybe add one for the other profile. 5308 if (xpDomainInfo != null && ( 5309 xpDomainInfo.bestDomainVerificationStatus 5310 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5311 result.add(xpDomainInfo.resolveInfo); 5312 } 5313 includeBrowser = true; 5314 } 5315 5316 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5317 // If there were 'always' entries their preferred order has been set, so we also 5318 // back that off to make the alternatives equivalent 5319 if (alwaysAskList.size() > 0) { 5320 for (ResolveInfo i : result) { 5321 i.preferredOrder = 0; 5322 } 5323 result.addAll(alwaysAskList); 5324 includeBrowser = true; 5325 } 5326 5327 if (includeBrowser) { 5328 // Also add browsers (all of them or only the default one) 5329 if (DEBUG_DOMAIN_VERIFICATION) { 5330 Slog.v(TAG, " ...including browsers in candidate set"); 5331 } 5332 if ((matchFlags & MATCH_ALL) != 0) { 5333 result.addAll(matchAllList); 5334 } else { 5335 // Browser/generic handling case. If there's a default browser, go straight 5336 // to that (but only if there is no other higher-priority match). 5337 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5338 int maxMatchPrio = 0; 5339 ResolveInfo defaultBrowserMatch = null; 5340 final int numCandidates = matchAllList.size(); 5341 for (int n = 0; n < numCandidates; n++) { 5342 ResolveInfo info = matchAllList.get(n); 5343 // track the highest overall match priority... 5344 if (info.priority > maxMatchPrio) { 5345 maxMatchPrio = info.priority; 5346 } 5347 // ...and the highest-priority default browser match 5348 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5349 if (defaultBrowserMatch == null 5350 || (defaultBrowserMatch.priority < info.priority)) { 5351 if (debug) { 5352 Slog.v(TAG, "Considering default browser match " + info); 5353 } 5354 defaultBrowserMatch = info; 5355 } 5356 } 5357 } 5358 if (defaultBrowserMatch != null 5359 && defaultBrowserMatch.priority >= maxMatchPrio 5360 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5361 { 5362 if (debug) { 5363 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5364 } 5365 result.add(defaultBrowserMatch); 5366 } else { 5367 result.addAll(matchAllList); 5368 } 5369 } 5370 5371 // If there is nothing selected, add all candidates and remove the ones that the user 5372 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5373 if (result.size() == 0) { 5374 result.addAll(candidates); 5375 result.removeAll(neverList); 5376 } 5377 } 5378 } 5379 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5380 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5381 result.size()); 5382 for (ResolveInfo info : result) { 5383 Slog.v(TAG, " + " + info.activityInfo); 5384 } 5385 } 5386 return result; 5387 } 5388 5389 // Returns a packed value as a long: 5390 // 5391 // high 'int'-sized word: link status: undefined/ask/never/always. 5392 // low 'int'-sized word: relative priority among 'always' results. 5393 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5394 long result = ps.getDomainVerificationStatusForUser(userId); 5395 // if none available, get the master status 5396 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5397 if (ps.getIntentFilterVerificationInfo() != null) { 5398 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5399 } 5400 } 5401 return result; 5402 } 5403 5404 private ResolveInfo querySkipCurrentProfileIntents( 5405 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5406 int flags, int sourceUserId) { 5407 if (matchingFilters != null) { 5408 int size = matchingFilters.size(); 5409 for (int i = 0; i < size; i ++) { 5410 CrossProfileIntentFilter filter = matchingFilters.get(i); 5411 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5412 // Checking if there are activities in the target user that can handle the 5413 // intent. 5414 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5415 resolvedType, flags, sourceUserId); 5416 if (resolveInfo != null) { 5417 return resolveInfo; 5418 } 5419 } 5420 } 5421 } 5422 return null; 5423 } 5424 5425 // Return matching ResolveInfo in target user if any. 5426 private ResolveInfo queryCrossProfileIntents( 5427 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5428 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5429 if (matchingFilters != null) { 5430 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5431 // match the same intent. For performance reasons, it is better not to 5432 // run queryIntent twice for the same userId 5433 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5434 int size = matchingFilters.size(); 5435 for (int i = 0; i < size; i++) { 5436 CrossProfileIntentFilter filter = matchingFilters.get(i); 5437 int targetUserId = filter.getTargetUserId(); 5438 boolean skipCurrentProfile = 5439 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5440 boolean skipCurrentProfileIfNoMatchFound = 5441 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5442 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5443 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5444 // Checking if there are activities in the target user that can handle the 5445 // intent. 5446 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5447 resolvedType, flags, sourceUserId); 5448 if (resolveInfo != null) return resolveInfo; 5449 alreadyTriedUserIds.put(targetUserId, true); 5450 } 5451 } 5452 } 5453 return null; 5454 } 5455 5456 /** 5457 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5458 * will forward the intent to the filter's target user. 5459 * Otherwise, returns null. 5460 */ 5461 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5462 String resolvedType, int flags, int sourceUserId) { 5463 int targetUserId = filter.getTargetUserId(); 5464 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5465 resolvedType, flags, targetUserId); 5466 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5467 // If all the matches in the target profile are suspended, return null. 5468 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5469 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5470 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5471 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5472 targetUserId); 5473 } 5474 } 5475 } 5476 return null; 5477 } 5478 5479 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5480 int sourceUserId, int targetUserId) { 5481 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5482 long ident = Binder.clearCallingIdentity(); 5483 boolean targetIsProfile; 5484 try { 5485 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5486 } finally { 5487 Binder.restoreCallingIdentity(ident); 5488 } 5489 String className; 5490 if (targetIsProfile) { 5491 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5492 } else { 5493 className = FORWARD_INTENT_TO_PARENT; 5494 } 5495 ComponentName forwardingActivityComponentName = new ComponentName( 5496 mAndroidApplication.packageName, className); 5497 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5498 sourceUserId); 5499 if (!targetIsProfile) { 5500 forwardingActivityInfo.showUserIcon = targetUserId; 5501 forwardingResolveInfo.noResourceId = true; 5502 } 5503 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5504 forwardingResolveInfo.priority = 0; 5505 forwardingResolveInfo.preferredOrder = 0; 5506 forwardingResolveInfo.match = 0; 5507 forwardingResolveInfo.isDefault = true; 5508 forwardingResolveInfo.filter = filter; 5509 forwardingResolveInfo.targetUserId = targetUserId; 5510 return forwardingResolveInfo; 5511 } 5512 5513 @Override 5514 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5515 Intent[] specifics, String[] specificTypes, Intent intent, 5516 String resolvedType, int flags, int userId) { 5517 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5518 flags = updateFlagsForResolve(flags, userId, intent); 5519 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5520 false /* requireFullPermission */, false /* checkShell */, 5521 "query intent activity options"); 5522 final String resultsAction = intent.getAction(); 5523 5524 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5525 | PackageManager.GET_RESOLVED_FILTER, userId); 5526 5527 if (DEBUG_INTENT_MATCHING) { 5528 Log.v(TAG, "Query " + intent + ": " + results); 5529 } 5530 5531 int specificsPos = 0; 5532 int N; 5533 5534 // todo: note that the algorithm used here is O(N^2). This 5535 // isn't a problem in our current environment, but if we start running 5536 // into situations where we have more than 5 or 10 matches then this 5537 // should probably be changed to something smarter... 5538 5539 // First we go through and resolve each of the specific items 5540 // that were supplied, taking care of removing any corresponding 5541 // duplicate items in the generic resolve list. 5542 if (specifics != null) { 5543 for (int i=0; i<specifics.length; i++) { 5544 final Intent sintent = specifics[i]; 5545 if (sintent == null) { 5546 continue; 5547 } 5548 5549 if (DEBUG_INTENT_MATCHING) { 5550 Log.v(TAG, "Specific #" + i + ": " + sintent); 5551 } 5552 5553 String action = sintent.getAction(); 5554 if (resultsAction != null && resultsAction.equals(action)) { 5555 // If this action was explicitly requested, then don't 5556 // remove things that have it. 5557 action = null; 5558 } 5559 5560 ResolveInfo ri = null; 5561 ActivityInfo ai = null; 5562 5563 ComponentName comp = sintent.getComponent(); 5564 if (comp == null) { 5565 ri = resolveIntent( 5566 sintent, 5567 specificTypes != null ? specificTypes[i] : null, 5568 flags, userId); 5569 if (ri == null) { 5570 continue; 5571 } 5572 if (ri == mResolveInfo) { 5573 // ACK! Must do something better with this. 5574 } 5575 ai = ri.activityInfo; 5576 comp = new ComponentName(ai.applicationInfo.packageName, 5577 ai.name); 5578 } else { 5579 ai = getActivityInfo(comp, flags, userId); 5580 if (ai == null) { 5581 continue; 5582 } 5583 } 5584 5585 // Look for any generic query activities that are duplicates 5586 // of this specific one, and remove them from the results. 5587 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5588 N = results.size(); 5589 int j; 5590 for (j=specificsPos; j<N; j++) { 5591 ResolveInfo sri = results.get(j); 5592 if ((sri.activityInfo.name.equals(comp.getClassName()) 5593 && sri.activityInfo.applicationInfo.packageName.equals( 5594 comp.getPackageName())) 5595 || (action != null && sri.filter.matchAction(action))) { 5596 results.remove(j); 5597 if (DEBUG_INTENT_MATCHING) Log.v( 5598 TAG, "Removing duplicate item from " + j 5599 + " due to specific " + specificsPos); 5600 if (ri == null) { 5601 ri = sri; 5602 } 5603 j--; 5604 N--; 5605 } 5606 } 5607 5608 // Add this specific item to its proper place. 5609 if (ri == null) { 5610 ri = new ResolveInfo(); 5611 ri.activityInfo = ai; 5612 } 5613 results.add(specificsPos, ri); 5614 ri.specificIndex = i; 5615 specificsPos++; 5616 } 5617 } 5618 5619 // Now we go through the remaining generic results and remove any 5620 // duplicate actions that are found here. 5621 N = results.size(); 5622 for (int i=specificsPos; i<N-1; i++) { 5623 final ResolveInfo rii = results.get(i); 5624 if (rii.filter == null) { 5625 continue; 5626 } 5627 5628 // Iterate over all of the actions of this result's intent 5629 // filter... typically this should be just one. 5630 final Iterator<String> it = rii.filter.actionsIterator(); 5631 if (it == null) { 5632 continue; 5633 } 5634 while (it.hasNext()) { 5635 final String action = it.next(); 5636 if (resultsAction != null && resultsAction.equals(action)) { 5637 // If this action was explicitly requested, then don't 5638 // remove things that have it. 5639 continue; 5640 } 5641 for (int j=i+1; j<N; j++) { 5642 final ResolveInfo rij = results.get(j); 5643 if (rij.filter != null && rij.filter.hasAction(action)) { 5644 results.remove(j); 5645 if (DEBUG_INTENT_MATCHING) Log.v( 5646 TAG, "Removing duplicate item from " + j 5647 + " due to action " + action + " at " + i); 5648 j--; 5649 N--; 5650 } 5651 } 5652 } 5653 5654 // If the caller didn't request filter information, drop it now 5655 // so we don't have to marshall/unmarshall it. 5656 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5657 rii.filter = null; 5658 } 5659 } 5660 5661 // Filter out the caller activity if so requested. 5662 if (caller != null) { 5663 N = results.size(); 5664 for (int i=0; i<N; i++) { 5665 ActivityInfo ainfo = results.get(i).activityInfo; 5666 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5667 && caller.getClassName().equals(ainfo.name)) { 5668 results.remove(i); 5669 break; 5670 } 5671 } 5672 } 5673 5674 // If the caller didn't request filter information, 5675 // drop them now so we don't have to 5676 // marshall/unmarshall it. 5677 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5678 N = results.size(); 5679 for (int i=0; i<N; i++) { 5680 results.get(i).filter = null; 5681 } 5682 } 5683 5684 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5685 return results; 5686 } 5687 5688 @Override 5689 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5690 int userId) { 5691 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5692 flags = updateFlagsForResolve(flags, userId, intent); 5693 ComponentName comp = intent.getComponent(); 5694 if (comp == null) { 5695 if (intent.getSelector() != null) { 5696 intent = intent.getSelector(); 5697 comp = intent.getComponent(); 5698 } 5699 } 5700 if (comp != null) { 5701 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5702 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5703 if (ai != null) { 5704 ResolveInfo ri = new ResolveInfo(); 5705 ri.activityInfo = ai; 5706 list.add(ri); 5707 } 5708 return list; 5709 } 5710 5711 // reader 5712 synchronized (mPackages) { 5713 String pkgName = intent.getPackage(); 5714 if (pkgName == null) { 5715 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5716 } 5717 final PackageParser.Package pkg = mPackages.get(pkgName); 5718 if (pkg != null) { 5719 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5720 userId); 5721 } 5722 return null; 5723 } 5724 } 5725 5726 @Override 5727 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5728 if (!sUserManager.exists(userId)) return null; 5729 flags = updateFlagsForResolve(flags, userId, intent); 5730 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5731 if (query != null) { 5732 if (query.size() >= 1) { 5733 // If there is more than one service with the same priority, 5734 // just arbitrarily pick the first one. 5735 return query.get(0); 5736 } 5737 } 5738 return null; 5739 } 5740 5741 @Override 5742 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5743 int userId) { 5744 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5745 flags = updateFlagsForResolve(flags, userId, intent); 5746 ComponentName comp = intent.getComponent(); 5747 if (comp == null) { 5748 if (intent.getSelector() != null) { 5749 intent = intent.getSelector(); 5750 comp = intent.getComponent(); 5751 } 5752 } 5753 if (comp != null) { 5754 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5755 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5756 if (si != null) { 5757 final ResolveInfo ri = new ResolveInfo(); 5758 ri.serviceInfo = si; 5759 list.add(ri); 5760 } 5761 return list; 5762 } 5763 5764 // reader 5765 synchronized (mPackages) { 5766 String pkgName = intent.getPackage(); 5767 if (pkgName == null) { 5768 return mServices.queryIntent(intent, resolvedType, flags, userId); 5769 } 5770 final PackageParser.Package pkg = mPackages.get(pkgName); 5771 if (pkg != null) { 5772 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5773 userId); 5774 } 5775 return null; 5776 } 5777 } 5778 5779 @Override 5780 public List<ResolveInfo> queryIntentContentProviders( 5781 Intent intent, String resolvedType, int flags, int userId) { 5782 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5783 flags = updateFlagsForResolve(flags, userId, intent); 5784 ComponentName comp = intent.getComponent(); 5785 if (comp == null) { 5786 if (intent.getSelector() != null) { 5787 intent = intent.getSelector(); 5788 comp = intent.getComponent(); 5789 } 5790 } 5791 if (comp != null) { 5792 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5793 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5794 if (pi != null) { 5795 final ResolveInfo ri = new ResolveInfo(); 5796 ri.providerInfo = pi; 5797 list.add(ri); 5798 } 5799 return list; 5800 } 5801 5802 // reader 5803 synchronized (mPackages) { 5804 String pkgName = intent.getPackage(); 5805 if (pkgName == null) { 5806 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5807 } 5808 final PackageParser.Package pkg = mPackages.get(pkgName); 5809 if (pkg != null) { 5810 return mProviders.queryIntentForPackage( 5811 intent, resolvedType, flags, pkg.providers, userId); 5812 } 5813 return null; 5814 } 5815 } 5816 5817 @Override 5818 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5819 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5820 flags = updateFlagsForPackage(flags, userId, null); 5821 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5822 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5823 true /* requireFullPermission */, false /* checkShell */, 5824 "get installed packages"); 5825 5826 // writer 5827 synchronized (mPackages) { 5828 ArrayList<PackageInfo> list; 5829 if (listUninstalled) { 5830 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5831 for (PackageSetting ps : mSettings.mPackages.values()) { 5832 PackageInfo pi; 5833 if (ps.pkg != null) { 5834 pi = generatePackageInfo(ps.pkg, flags, userId); 5835 } else { 5836 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5837 } 5838 if (pi != null) { 5839 list.add(pi); 5840 } 5841 } 5842 } else { 5843 list = new ArrayList<PackageInfo>(mPackages.size()); 5844 for (PackageParser.Package p : mPackages.values()) { 5845 PackageInfo pi = generatePackageInfo(p, flags, userId); 5846 if (pi != null) { 5847 list.add(pi); 5848 } 5849 } 5850 } 5851 5852 return new ParceledListSlice<PackageInfo>(list); 5853 } 5854 } 5855 5856 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5857 String[] permissions, boolean[] tmp, int flags, int userId) { 5858 int numMatch = 0; 5859 final PermissionsState permissionsState = ps.getPermissionsState(); 5860 for (int i=0; i<permissions.length; i++) { 5861 final String permission = permissions[i]; 5862 if (permissionsState.hasPermission(permission, userId)) { 5863 tmp[i] = true; 5864 numMatch++; 5865 } else { 5866 tmp[i] = false; 5867 } 5868 } 5869 if (numMatch == 0) { 5870 return; 5871 } 5872 PackageInfo pi; 5873 if (ps.pkg != null) { 5874 pi = generatePackageInfo(ps.pkg, flags, userId); 5875 } else { 5876 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5877 } 5878 // The above might return null in cases of uninstalled apps or install-state 5879 // skew across users/profiles. 5880 if (pi != null) { 5881 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5882 if (numMatch == permissions.length) { 5883 pi.requestedPermissions = permissions; 5884 } else { 5885 pi.requestedPermissions = new String[numMatch]; 5886 numMatch = 0; 5887 for (int i=0; i<permissions.length; i++) { 5888 if (tmp[i]) { 5889 pi.requestedPermissions[numMatch] = permissions[i]; 5890 numMatch++; 5891 } 5892 } 5893 } 5894 } 5895 list.add(pi); 5896 } 5897 } 5898 5899 @Override 5900 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5901 String[] permissions, int flags, int userId) { 5902 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5903 flags = updateFlagsForPackage(flags, userId, permissions); 5904 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5905 5906 // writer 5907 synchronized (mPackages) { 5908 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5909 boolean[] tmpBools = new boolean[permissions.length]; 5910 if (listUninstalled) { 5911 for (PackageSetting ps : mSettings.mPackages.values()) { 5912 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5913 } 5914 } else { 5915 for (PackageParser.Package pkg : mPackages.values()) { 5916 PackageSetting ps = (PackageSetting)pkg.mExtras; 5917 if (ps != null) { 5918 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5919 userId); 5920 } 5921 } 5922 } 5923 5924 return new ParceledListSlice<PackageInfo>(list); 5925 } 5926 } 5927 5928 @Override 5929 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5930 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5931 flags = updateFlagsForApplication(flags, userId, null); 5932 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5933 5934 // writer 5935 synchronized (mPackages) { 5936 ArrayList<ApplicationInfo> list; 5937 if (listUninstalled) { 5938 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5939 for (PackageSetting ps : mSettings.mPackages.values()) { 5940 ApplicationInfo ai; 5941 if (ps.pkg != null) { 5942 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5943 ps.readUserState(userId), userId); 5944 } else { 5945 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5946 } 5947 if (ai != null) { 5948 list.add(ai); 5949 } 5950 } 5951 } else { 5952 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5953 for (PackageParser.Package p : mPackages.values()) { 5954 if (p.mExtras != null) { 5955 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5956 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5957 if (ai != null) { 5958 list.add(ai); 5959 } 5960 } 5961 } 5962 } 5963 5964 return new ParceledListSlice<ApplicationInfo>(list); 5965 } 5966 } 5967 5968 @Override 5969 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5970 if (DISABLE_EPHEMERAL_APPS) { 5971 return null; 5972 } 5973 5974 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5975 "getEphemeralApplications"); 5976 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5977 true /* requireFullPermission */, false /* checkShell */, 5978 "getEphemeralApplications"); 5979 synchronized (mPackages) { 5980 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5981 .getEphemeralApplicationsLPw(userId); 5982 if (ephemeralApps != null) { 5983 return new ParceledListSlice<>(ephemeralApps); 5984 } 5985 } 5986 return null; 5987 } 5988 5989 @Override 5990 public boolean isEphemeralApplication(String packageName, int userId) { 5991 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5992 true /* requireFullPermission */, false /* checkShell */, 5993 "isEphemeral"); 5994 if (DISABLE_EPHEMERAL_APPS) { 5995 return false; 5996 } 5997 5998 if (!isCallerSameApp(packageName)) { 5999 return false; 6000 } 6001 synchronized (mPackages) { 6002 PackageParser.Package pkg = mPackages.get(packageName); 6003 if (pkg != null) { 6004 return pkg.applicationInfo.isEphemeralApp(); 6005 } 6006 } 6007 return false; 6008 } 6009 6010 @Override 6011 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6012 if (DISABLE_EPHEMERAL_APPS) { 6013 return null; 6014 } 6015 6016 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6017 true /* requireFullPermission */, false /* checkShell */, 6018 "getCookie"); 6019 if (!isCallerSameApp(packageName)) { 6020 return null; 6021 } 6022 synchronized (mPackages) { 6023 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6024 packageName, userId); 6025 } 6026 } 6027 6028 @Override 6029 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6030 if (DISABLE_EPHEMERAL_APPS) { 6031 return true; 6032 } 6033 6034 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6035 true /* requireFullPermission */, true /* checkShell */, 6036 "setCookie"); 6037 if (!isCallerSameApp(packageName)) { 6038 return false; 6039 } 6040 synchronized (mPackages) { 6041 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6042 packageName, cookie, userId); 6043 } 6044 } 6045 6046 @Override 6047 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6048 if (DISABLE_EPHEMERAL_APPS) { 6049 return null; 6050 } 6051 6052 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6053 "getEphemeralApplicationIcon"); 6054 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6055 true /* requireFullPermission */, false /* checkShell */, 6056 "getEphemeralApplicationIcon"); 6057 synchronized (mPackages) { 6058 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6059 packageName, userId); 6060 } 6061 } 6062 6063 private boolean isCallerSameApp(String packageName) { 6064 PackageParser.Package pkg = mPackages.get(packageName); 6065 return pkg != null 6066 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6067 } 6068 6069 public List<ApplicationInfo> getPersistentApplications(int flags) { 6070 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6071 6072 // reader 6073 synchronized (mPackages) { 6074 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6075 final int userId = UserHandle.getCallingUserId(); 6076 while (i.hasNext()) { 6077 final PackageParser.Package p = i.next(); 6078 if (p.applicationInfo == null) continue; 6079 6080 final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0) 6081 && !p.applicationInfo.isEncryptionAware(); 6082 final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0) 6083 && p.applicationInfo.isEncryptionAware(); 6084 6085 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6086 && (!mSafeMode || isSystemApp(p)) 6087 && (matchesUnaware || matchesAware)) { 6088 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6089 if (ps != null) { 6090 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6091 ps.readUserState(userId), userId); 6092 if (ai != null) { 6093 finalList.add(ai); 6094 } 6095 } 6096 } 6097 } 6098 } 6099 6100 return finalList; 6101 } 6102 6103 @Override 6104 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6105 if (!sUserManager.exists(userId)) return null; 6106 flags = updateFlagsForComponent(flags, userId, name); 6107 // reader 6108 synchronized (mPackages) { 6109 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6110 PackageSetting ps = provider != null 6111 ? mSettings.mPackages.get(provider.owner.packageName) 6112 : null; 6113 return ps != null 6114 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6115 ? PackageParser.generateProviderInfo(provider, flags, 6116 ps.readUserState(userId), userId) 6117 : null; 6118 } 6119 } 6120 6121 /** 6122 * @deprecated 6123 */ 6124 @Deprecated 6125 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6126 // reader 6127 synchronized (mPackages) { 6128 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6129 .entrySet().iterator(); 6130 final int userId = UserHandle.getCallingUserId(); 6131 while (i.hasNext()) { 6132 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6133 PackageParser.Provider p = entry.getValue(); 6134 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6135 6136 if (ps != null && p.syncable 6137 && (!mSafeMode || (p.info.applicationInfo.flags 6138 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6139 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6140 ps.readUserState(userId), userId); 6141 if (info != null) { 6142 outNames.add(entry.getKey()); 6143 outInfo.add(info); 6144 } 6145 } 6146 } 6147 } 6148 } 6149 6150 @Override 6151 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6152 int uid, int flags) { 6153 final int userId = processName != null ? UserHandle.getUserId(uid) 6154 : UserHandle.getCallingUserId(); 6155 if (!sUserManager.exists(userId)) return null; 6156 flags = updateFlagsForComponent(flags, userId, processName); 6157 6158 ArrayList<ProviderInfo> finalList = null; 6159 // reader 6160 synchronized (mPackages) { 6161 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6162 while (i.hasNext()) { 6163 final PackageParser.Provider p = i.next(); 6164 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6165 if (ps != null && p.info.authority != null 6166 && (processName == null 6167 || (p.info.processName.equals(processName) 6168 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6169 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6170 if (finalList == null) { 6171 finalList = new ArrayList<ProviderInfo>(3); 6172 } 6173 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6174 ps.readUserState(userId), userId); 6175 if (info != null) { 6176 finalList.add(info); 6177 } 6178 } 6179 } 6180 } 6181 6182 if (finalList != null) { 6183 Collections.sort(finalList, mProviderInitOrderSorter); 6184 return new ParceledListSlice<ProviderInfo>(finalList); 6185 } 6186 6187 return null; 6188 } 6189 6190 @Override 6191 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6192 // reader 6193 synchronized (mPackages) { 6194 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6195 return PackageParser.generateInstrumentationInfo(i, flags); 6196 } 6197 } 6198 6199 @Override 6200 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6201 int flags) { 6202 ArrayList<InstrumentationInfo> finalList = 6203 new ArrayList<InstrumentationInfo>(); 6204 6205 // reader 6206 synchronized (mPackages) { 6207 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6208 while (i.hasNext()) { 6209 final PackageParser.Instrumentation p = i.next(); 6210 if (targetPackage == null 6211 || targetPackage.equals(p.info.targetPackage)) { 6212 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6213 flags); 6214 if (ii != null) { 6215 finalList.add(ii); 6216 } 6217 } 6218 } 6219 } 6220 6221 return finalList; 6222 } 6223 6224 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6225 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6226 if (overlays == null) { 6227 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6228 return; 6229 } 6230 for (PackageParser.Package opkg : overlays.values()) { 6231 // Not much to do if idmap fails: we already logged the error 6232 // and we certainly don't want to abort installation of pkg simply 6233 // because an overlay didn't fit properly. For these reasons, 6234 // ignore the return value of createIdmapForPackagePairLI. 6235 createIdmapForPackagePairLI(pkg, opkg); 6236 } 6237 } 6238 6239 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6240 PackageParser.Package opkg) { 6241 if (!opkg.mTrustedOverlay) { 6242 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6243 opkg.baseCodePath + ": overlay not trusted"); 6244 return false; 6245 } 6246 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6247 if (overlaySet == null) { 6248 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6249 opkg.baseCodePath + " but target package has no known overlays"); 6250 return false; 6251 } 6252 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6253 // TODO: generate idmap for split APKs 6254 try { 6255 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6256 } catch (InstallerException e) { 6257 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6258 + opkg.baseCodePath); 6259 return false; 6260 } 6261 PackageParser.Package[] overlayArray = 6262 overlaySet.values().toArray(new PackageParser.Package[0]); 6263 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6264 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6265 return p1.mOverlayPriority - p2.mOverlayPriority; 6266 } 6267 }; 6268 Arrays.sort(overlayArray, cmp); 6269 6270 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6271 int i = 0; 6272 for (PackageParser.Package p : overlayArray) { 6273 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6274 } 6275 return true; 6276 } 6277 6278 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6280 try { 6281 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6282 } finally { 6283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6284 } 6285 } 6286 6287 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6288 final File[] files = dir.listFiles(); 6289 if (ArrayUtils.isEmpty(files)) { 6290 Log.d(TAG, "No files in app dir " + dir); 6291 return; 6292 } 6293 6294 if (DEBUG_PACKAGE_SCANNING) { 6295 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6296 + " flags=0x" + Integer.toHexString(parseFlags)); 6297 } 6298 6299 for (File file : files) { 6300 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6301 && !PackageInstallerService.isStageName(file.getName()); 6302 if (!isPackage) { 6303 // Ignore entries which are not packages 6304 continue; 6305 } 6306 try { 6307 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6308 scanFlags, currentTime, null); 6309 } catch (PackageManagerException e) { 6310 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6311 6312 // Delete invalid userdata apps 6313 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6314 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6315 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6316 removeCodePathLI(file); 6317 } 6318 } 6319 } 6320 } 6321 6322 private static File getSettingsProblemFile() { 6323 File dataDir = Environment.getDataDirectory(); 6324 File systemDir = new File(dataDir, "system"); 6325 File fname = new File(systemDir, "uiderrors.txt"); 6326 return fname; 6327 } 6328 6329 static void reportSettingsProblem(int priority, String msg) { 6330 logCriticalInfo(priority, msg); 6331 } 6332 6333 static void logCriticalInfo(int priority, String msg) { 6334 Slog.println(priority, TAG, msg); 6335 EventLogTags.writePmCriticalInfo(msg); 6336 try { 6337 File fname = getSettingsProblemFile(); 6338 FileOutputStream out = new FileOutputStream(fname, true); 6339 PrintWriter pw = new FastPrintWriter(out); 6340 SimpleDateFormat formatter = new SimpleDateFormat(); 6341 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6342 pw.println(dateString + ": " + msg); 6343 pw.close(); 6344 FileUtils.setPermissions( 6345 fname.toString(), 6346 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6347 -1, -1); 6348 } catch (java.io.IOException e) { 6349 } 6350 } 6351 6352 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6353 int parseFlags) throws PackageManagerException { 6354 if (ps != null 6355 && ps.codePath.equals(srcFile) 6356 && ps.timeStamp == srcFile.lastModified() 6357 && !isCompatSignatureUpdateNeeded(pkg) 6358 && !isRecoverSignatureUpdateNeeded(pkg)) { 6359 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6360 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6361 ArraySet<PublicKey> signingKs; 6362 synchronized (mPackages) { 6363 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6364 } 6365 if (ps.signatures.mSignatures != null 6366 && ps.signatures.mSignatures.length != 0 6367 && signingKs != null) { 6368 // Optimization: reuse the existing cached certificates 6369 // if the package appears to be unchanged. 6370 pkg.mSignatures = ps.signatures.mSignatures; 6371 pkg.mSigningKeys = signingKs; 6372 return; 6373 } 6374 6375 Slog.w(TAG, "PackageSetting for " + ps.name 6376 + " is missing signatures. Collecting certs again to recover them."); 6377 } else { 6378 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6379 } 6380 6381 try { 6382 PackageParser.collectCertificates(pkg, parseFlags); 6383 } catch (PackageParserException e) { 6384 throw PackageManagerException.from(e); 6385 } 6386 } 6387 6388 /** 6389 * Traces a package scan. 6390 * @see #scanPackageLI(File, int, int, long, UserHandle) 6391 */ 6392 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6393 long currentTime, UserHandle user) throws PackageManagerException { 6394 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6395 try { 6396 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6397 } finally { 6398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6399 } 6400 } 6401 6402 /** 6403 * Scans a package and returns the newly parsed package. 6404 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6405 */ 6406 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6407 long currentTime, UserHandle user) throws PackageManagerException { 6408 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6409 parseFlags |= mDefParseFlags; 6410 PackageParser pp = new PackageParser(); 6411 pp.setSeparateProcesses(mSeparateProcesses); 6412 pp.setOnlyCoreApps(mOnlyCore); 6413 pp.setDisplayMetrics(mMetrics); 6414 6415 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6416 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6417 } 6418 6419 final PackageParser.Package pkg; 6420 try { 6421 pkg = pp.parsePackage(scanFile, parseFlags); 6422 } catch (PackageParserException e) { 6423 throw PackageManagerException.from(e); 6424 } 6425 6426 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6427 } 6428 6429 /** 6430 * Scans a package and returns the newly parsed package. 6431 * @throws PackageManagerException on a parse error. 6432 */ 6433 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6434 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6435 throws PackageManagerException { 6436 // If the package has children and this is the first dive in the function 6437 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6438 // packages (parent and children) would be successfully scanned before the 6439 // actual scan since scanning mutates internal state and we want to atomically 6440 // install the package and its children. 6441 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6442 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6443 scanFlags |= SCAN_CHECK_ONLY; 6444 } 6445 } else { 6446 scanFlags &= ~SCAN_CHECK_ONLY; 6447 } 6448 6449 // Scan the parent 6450 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6451 scanFlags, currentTime, user); 6452 6453 // Scan the children 6454 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6455 for (int i = 0; i < childCount; i++) { 6456 PackageParser.Package childPackage = pkg.childPackages.get(i); 6457 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6458 currentTime, user); 6459 } 6460 6461 6462 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6463 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6464 } 6465 6466 return scannedPkg; 6467 } 6468 6469 /** 6470 * Scans a package and returns the newly parsed package. 6471 * @throws PackageManagerException on a parse error. 6472 */ 6473 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6474 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6475 throws PackageManagerException { 6476 PackageSetting ps = null; 6477 PackageSetting updatedPkg; 6478 // reader 6479 synchronized (mPackages) { 6480 // Look to see if we already know about this package. 6481 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6482 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6483 // This package has been renamed to its original name. Let's 6484 // use that. 6485 ps = mSettings.peekPackageLPr(oldName); 6486 } 6487 // If there was no original package, see one for the real package name. 6488 if (ps == null) { 6489 ps = mSettings.peekPackageLPr(pkg.packageName); 6490 } 6491 // Check to see if this package could be hiding/updating a system 6492 // package. Must look for it either under the original or real 6493 // package name depending on our state. 6494 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6495 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6496 6497 // If this is a package we don't know about on the system partition, we 6498 // may need to remove disabled child packages on the system partition 6499 // or may need to not add child packages if the parent apk is updated 6500 // on the data partition and no longer defines this child package. 6501 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6502 // If this is a parent package for an updated system app and this system 6503 // app got an OTA update which no longer defines some of the child packages 6504 // we have to prune them from the disabled system packages. 6505 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6506 if (disabledPs != null) { 6507 final int scannedChildCount = (pkg.childPackages != null) 6508 ? pkg.childPackages.size() : 0; 6509 final int disabledChildCount = disabledPs.childPackageNames != null 6510 ? disabledPs.childPackageNames.size() : 0; 6511 for (int i = 0; i < disabledChildCount; i++) { 6512 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6513 boolean disabledPackageAvailable = false; 6514 for (int j = 0; j < scannedChildCount; j++) { 6515 PackageParser.Package childPkg = pkg.childPackages.get(j); 6516 if (childPkg.packageName.equals(disabledChildPackageName)) { 6517 disabledPackageAvailable = true; 6518 break; 6519 } 6520 } 6521 if (!disabledPackageAvailable) { 6522 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6523 } 6524 } 6525 } 6526 } 6527 } 6528 6529 boolean updatedPkgBetter = false; 6530 // First check if this is a system package that may involve an update 6531 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6532 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6533 // it needs to drop FLAG_PRIVILEGED. 6534 if (locationIsPrivileged(scanFile)) { 6535 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6536 } else { 6537 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6538 } 6539 6540 if (ps != null && !ps.codePath.equals(scanFile)) { 6541 // The path has changed from what was last scanned... check the 6542 // version of the new path against what we have stored to determine 6543 // what to do. 6544 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6545 if (pkg.mVersionCode <= ps.versionCode) { 6546 // The system package has been updated and the code path does not match 6547 // Ignore entry. Skip it. 6548 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6549 + " ignored: updated version " + ps.versionCode 6550 + " better than this " + pkg.mVersionCode); 6551 if (!updatedPkg.codePath.equals(scanFile)) { 6552 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6553 + ps.name + " changing from " + updatedPkg.codePathString 6554 + " to " + scanFile); 6555 updatedPkg.codePath = scanFile; 6556 updatedPkg.codePathString = scanFile.toString(); 6557 updatedPkg.resourcePath = scanFile; 6558 updatedPkg.resourcePathString = scanFile.toString(); 6559 } 6560 updatedPkg.pkg = pkg; 6561 updatedPkg.versionCode = pkg.mVersionCode; 6562 6563 // Update the disabled system child packages to point to the package too. 6564 final int childCount = updatedPkg.childPackageNames != null 6565 ? updatedPkg.childPackageNames.size() : 0; 6566 for (int i = 0; i < childCount; i++) { 6567 String childPackageName = updatedPkg.childPackageNames.get(i); 6568 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6569 childPackageName); 6570 if (updatedChildPkg != null) { 6571 updatedChildPkg.pkg = pkg; 6572 updatedChildPkg.versionCode = pkg.mVersionCode; 6573 } 6574 } 6575 6576 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6577 + scanFile + " ignored: updated version " + ps.versionCode 6578 + " better than this " + pkg.mVersionCode); 6579 } else { 6580 // The current app on the system partition is better than 6581 // what we have updated to on the data partition; switch 6582 // back to the system partition version. 6583 // At this point, its safely assumed that package installation for 6584 // apps in system partition will go through. If not there won't be a working 6585 // version of the app 6586 // writer 6587 synchronized (mPackages) { 6588 // Just remove the loaded entries from package lists. 6589 mPackages.remove(ps.name); 6590 } 6591 6592 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6593 + " reverting from " + ps.codePathString 6594 + ": new version " + pkg.mVersionCode 6595 + " better than installed " + ps.versionCode); 6596 6597 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6598 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6599 synchronized (mInstallLock) { 6600 args.cleanUpResourcesLI(); 6601 } 6602 synchronized (mPackages) { 6603 mSettings.enableSystemPackageLPw(ps.name); 6604 } 6605 updatedPkgBetter = true; 6606 } 6607 } 6608 } 6609 6610 if (updatedPkg != null) { 6611 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6612 // initially 6613 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6614 6615 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6616 // flag set initially 6617 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6618 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6619 } 6620 } 6621 6622 // Verify certificates against what was last scanned 6623 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6624 6625 /* 6626 * A new system app appeared, but we already had a non-system one of the 6627 * same name installed earlier. 6628 */ 6629 boolean shouldHideSystemApp = false; 6630 if (updatedPkg == null && ps != null 6631 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6632 /* 6633 * Check to make sure the signatures match first. If they don't, 6634 * wipe the installed application and its data. 6635 */ 6636 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6637 != PackageManager.SIGNATURE_MATCH) { 6638 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6639 + " signatures don't match existing userdata copy; removing"); 6640 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6641 ps = null; 6642 } else { 6643 /* 6644 * If the newly-added system app is an older version than the 6645 * already installed version, hide it. It will be scanned later 6646 * and re-added like an update. 6647 */ 6648 if (pkg.mVersionCode <= ps.versionCode) { 6649 shouldHideSystemApp = true; 6650 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6651 + " but new version " + pkg.mVersionCode + " better than installed " 6652 + ps.versionCode + "; hiding system"); 6653 } else { 6654 /* 6655 * The newly found system app is a newer version that the 6656 * one previously installed. Simply remove the 6657 * already-installed application and replace it with our own 6658 * while keeping the application data. 6659 */ 6660 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6661 + " reverting from " + ps.codePathString + ": new version " 6662 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6663 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6664 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6665 synchronized (mInstallLock) { 6666 args.cleanUpResourcesLI(); 6667 } 6668 } 6669 } 6670 } 6671 6672 // The apk is forward locked (not public) if its code and resources 6673 // are kept in different files. (except for app in either system or 6674 // vendor path). 6675 // TODO grab this value from PackageSettings 6676 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6677 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6678 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6679 } 6680 } 6681 6682 // TODO: extend to support forward-locked splits 6683 String resourcePath = null; 6684 String baseResourcePath = null; 6685 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6686 if (ps != null && ps.resourcePathString != null) { 6687 resourcePath = ps.resourcePathString; 6688 baseResourcePath = ps.resourcePathString; 6689 } else { 6690 // Should not happen at all. Just log an error. 6691 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6692 } 6693 } else { 6694 resourcePath = pkg.codePath; 6695 baseResourcePath = pkg.baseCodePath; 6696 } 6697 6698 // Set application objects path explicitly. 6699 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6700 pkg.setApplicationInfoCodePath(pkg.codePath); 6701 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6702 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6703 pkg.setApplicationInfoResourcePath(resourcePath); 6704 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6705 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6706 6707 // Note that we invoke the following method only if we are about to unpack an application 6708 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6709 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6710 6711 /* 6712 * If the system app should be overridden by a previously installed 6713 * data, hide the system app now and let the /data/app scan pick it up 6714 * again. 6715 */ 6716 if (shouldHideSystemApp) { 6717 synchronized (mPackages) { 6718 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6719 } 6720 } 6721 6722 return scannedPkg; 6723 } 6724 6725 private static String fixProcessName(String defProcessName, 6726 String processName, int uid) { 6727 if (processName == null) { 6728 return defProcessName; 6729 } 6730 return processName; 6731 } 6732 6733 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6734 throws PackageManagerException { 6735 if (pkgSetting.signatures.mSignatures != null) { 6736 // Already existing package. Make sure signatures match 6737 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6738 == PackageManager.SIGNATURE_MATCH; 6739 if (!match) { 6740 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6741 == PackageManager.SIGNATURE_MATCH; 6742 } 6743 if (!match) { 6744 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6745 == PackageManager.SIGNATURE_MATCH; 6746 } 6747 if (!match) { 6748 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6749 + pkg.packageName + " signatures do not match the " 6750 + "previously installed version; ignoring!"); 6751 } 6752 } 6753 6754 // Check for shared user signatures 6755 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6756 // Already existing package. Make sure signatures match 6757 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6758 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6759 if (!match) { 6760 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6761 == PackageManager.SIGNATURE_MATCH; 6762 } 6763 if (!match) { 6764 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6765 == PackageManager.SIGNATURE_MATCH; 6766 } 6767 if (!match) { 6768 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6769 "Package " + pkg.packageName 6770 + " has no signatures that match those in shared user " 6771 + pkgSetting.sharedUser.name + "; ignoring!"); 6772 } 6773 } 6774 } 6775 6776 /** 6777 * Enforces that only the system UID or root's UID can call a method exposed 6778 * via Binder. 6779 * 6780 * @param message used as message if SecurityException is thrown 6781 * @throws SecurityException if the caller is not system or root 6782 */ 6783 private static final void enforceSystemOrRoot(String message) { 6784 final int uid = Binder.getCallingUid(); 6785 if (uid != Process.SYSTEM_UID && uid != 0) { 6786 throw new SecurityException(message); 6787 } 6788 } 6789 6790 @Override 6791 public void performFstrimIfNeeded() { 6792 enforceSystemOrRoot("Only the system can request fstrim"); 6793 6794 // Before everything else, see whether we need to fstrim. 6795 try { 6796 IMountService ms = PackageHelper.getMountService(); 6797 if (ms != null) { 6798 final boolean isUpgrade = isUpgrade(); 6799 boolean doTrim = isUpgrade; 6800 if (doTrim) { 6801 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6802 } else { 6803 final long interval = android.provider.Settings.Global.getLong( 6804 mContext.getContentResolver(), 6805 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6806 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6807 if (interval > 0) { 6808 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6809 if (timeSinceLast > interval) { 6810 doTrim = true; 6811 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6812 + "; running immediately"); 6813 } 6814 } 6815 } 6816 if (doTrim) { 6817 if (!isFirstBoot()) { 6818 try { 6819 ActivityManagerNative.getDefault().showBootMessage( 6820 mContext.getResources().getString( 6821 R.string.android_upgrading_fstrim), true); 6822 } catch (RemoteException e) { 6823 } 6824 } 6825 ms.runMaintenance(); 6826 } 6827 } else { 6828 Slog.e(TAG, "Mount service unavailable!"); 6829 } 6830 } catch (RemoteException e) { 6831 // Can't happen; MountService is local 6832 } 6833 } 6834 6835 @Override 6836 public void extractPackagesIfNeeded() { 6837 enforceSystemOrRoot("Only the system can request package extraction"); 6838 6839 // Extract pacakges only if profile-guided compilation is enabled because 6840 // otherwise BackgroundDexOptService will not dexopt them later. 6841 if (!mUseJitProfiles || !isUpgrade()) { 6842 return; 6843 } 6844 6845 List<PackageParser.Package> pkgs; 6846 synchronized (mPackages) { 6847 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6848 } 6849 6850 int curr = 0; 6851 int total = pkgs.size(); 6852 for (PackageParser.Package pkg : pkgs) { 6853 curr++; 6854 6855 if (DEBUG_DEXOPT) { 6856 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6857 } 6858 6859 if (!isFirstBoot()) { 6860 try { 6861 ActivityManagerNative.getDefault().showBootMessage( 6862 mContext.getResources().getString(R.string.android_upgrading_apk, 6863 curr, total), true); 6864 } catch (RemoteException e) { 6865 } 6866 } 6867 6868 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6869 performDexOpt(pkg.packageName, null /* instructionSet */, 6870 false /* useProfiles */, true /* extractOnly */, false /* force */); 6871 } 6872 } 6873 } 6874 6875 @Override 6876 public void notifyPackageUse(String packageName) { 6877 synchronized (mPackages) { 6878 PackageParser.Package p = mPackages.get(packageName); 6879 if (p == null) { 6880 return; 6881 } 6882 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6883 } 6884 } 6885 6886 // TODO: this is not used nor needed. Delete it. 6887 @Override 6888 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6889 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6890 false /* extractOnly */, false /* force */); 6891 } 6892 6893 @Override 6894 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6895 boolean extractOnly, boolean force) { 6896 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6897 } 6898 6899 private boolean performDexOptTraced(String packageName, String instructionSet, 6900 boolean useProfiles, boolean extractOnly, boolean force) { 6901 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6902 try { 6903 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6904 force); 6905 } finally { 6906 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6907 } 6908 } 6909 6910 private boolean performDexOptInternal(String packageName, String instructionSet, 6911 boolean useProfiles, boolean extractOnly, boolean force) { 6912 PackageParser.Package p; 6913 final String targetInstructionSet; 6914 synchronized (mPackages) { 6915 p = mPackages.get(packageName); 6916 if (p == null) { 6917 return false; 6918 } 6919 mPackageUsage.write(false); 6920 6921 targetInstructionSet = instructionSet != null ? instructionSet : 6922 getPrimaryInstructionSet(p.applicationInfo); 6923 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6924 // Skip only if we do not use profiles since they might trigger a recompilation. 6925 return false; 6926 } 6927 } 6928 long callingId = Binder.clearCallingIdentity(); 6929 try { 6930 synchronized (mInstallLock) { 6931 final String[] instructionSets = new String[] { targetInstructionSet }; 6932 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6933 useProfiles, extractOnly, force); 6934 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6935 } 6936 } finally { 6937 Binder.restoreCallingIdentity(callingId); 6938 } 6939 } 6940 6941 public ArraySet<String> getOptimizablePackages() { 6942 ArraySet<String> pkgs = new ArraySet<String>(); 6943 synchronized (mPackages) { 6944 for (PackageParser.Package p : mPackages.values()) { 6945 if (PackageDexOptimizer.canOptimizePackage(p)) { 6946 pkgs.add(p.packageName); 6947 } 6948 } 6949 } 6950 return pkgs; 6951 } 6952 6953 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6954 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6955 // Select the dex optimizer based on the force parameter. 6956 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6957 // allocate an object here. 6958 PackageDexOptimizer pdo = force 6959 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6960 : mPackageDexOptimizer; 6961 6962 // Optimize all dependencies first. Note: we ignore the return value and march on 6963 // on errors. 6964 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6965 if (!deps.isEmpty()) { 6966 for (PackageParser.Package depPackage : deps) { 6967 // TODO: Analyze and investigate if we (should) profile libraries. 6968 // Currently this will do a full compilation of the library. 6969 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6970 false /* extractOnly */); 6971 } 6972 } 6973 6974 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6975 } 6976 6977 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6978 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6979 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6980 Set<String> collectedNames = new HashSet<>(); 6981 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6982 6983 retValue.remove(p); 6984 6985 return retValue; 6986 } else { 6987 return Collections.emptyList(); 6988 } 6989 } 6990 6991 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6992 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6993 if (!collectedNames.contains(p.packageName)) { 6994 collectedNames.add(p.packageName); 6995 collected.add(p); 6996 6997 if (p.usesLibraries != null) { 6998 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6999 } 7000 if (p.usesOptionalLibraries != null) { 7001 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7002 collectedNames); 7003 } 7004 } 7005 } 7006 7007 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7008 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7009 for (String libName : libs) { 7010 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7011 if (libPkg != null) { 7012 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7013 } 7014 } 7015 } 7016 7017 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7018 synchronized (mPackages) { 7019 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7020 if (lib != null && lib.apk != null) { 7021 return mPackages.get(lib.apk); 7022 } 7023 } 7024 return null; 7025 } 7026 7027 public void shutdown() { 7028 mPackageUsage.write(true); 7029 } 7030 7031 @Override 7032 public void forceDexOpt(String packageName) { 7033 enforceSystemOrRoot("forceDexOpt"); 7034 7035 PackageParser.Package pkg; 7036 synchronized (mPackages) { 7037 pkg = mPackages.get(packageName); 7038 if (pkg == null) { 7039 throw new IllegalArgumentException("Unknown package: " + packageName); 7040 } 7041 } 7042 7043 synchronized (mInstallLock) { 7044 final String[] instructionSets = new String[] { 7045 getPrimaryInstructionSet(pkg.applicationInfo) }; 7046 7047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7048 7049 // Whoever is calling forceDexOpt wants a fully compiled package. 7050 // Don't use profiles since that may cause compilation to be skipped. 7051 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7052 false /* useProfiles */, false /* extractOnly */, true /* force */); 7053 7054 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7055 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7056 throw new IllegalStateException("Failed to dexopt: " + res); 7057 } 7058 } 7059 } 7060 7061 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7062 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7063 Slog.w(TAG, "Unable to update from " + oldPkg.name 7064 + " to " + newPkg.packageName 7065 + ": old package not in system partition"); 7066 return false; 7067 } else if (mPackages.get(oldPkg.name) != null) { 7068 Slog.w(TAG, "Unable to update from " + oldPkg.name 7069 + " to " + newPkg.packageName 7070 + ": old package still exists"); 7071 return false; 7072 } 7073 return true; 7074 } 7075 7076 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7077 // TODO: triage flags as part of 26466827 7078 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7079 7080 boolean res = true; 7081 final int[] users = sUserManager.getUserIds(); 7082 for (int user : users) { 7083 try { 7084 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7085 } catch (InstallerException e) { 7086 Slog.w(TAG, "Failed to delete data directory", e); 7087 res = false; 7088 } 7089 } 7090 return res; 7091 } 7092 7093 void removeCodePathLI(File codePath) { 7094 if (codePath.isDirectory()) { 7095 try { 7096 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7097 } catch (InstallerException e) { 7098 Slog.w(TAG, "Failed to remove code path", e); 7099 } 7100 } else { 7101 codePath.delete(); 7102 } 7103 } 7104 7105 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7106 try { 7107 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7108 } catch (InstallerException e) { 7109 Slog.w(TAG, "Failed to destroy app data", e); 7110 } 7111 } 7112 7113 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7114 int appId, String seinfo) { 7115 try { 7116 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7117 } catch (InstallerException e) { 7118 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7119 } 7120 } 7121 7122 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7123 final PackageParser.Package pkg; 7124 synchronized (mPackages) { 7125 pkg = mPackages.get(packageName); 7126 } 7127 if (pkg == null) { 7128 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7129 return; 7130 } 7131 deleteCodeCacheDirsLI(pkg); 7132 } 7133 7134 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7135 // TODO: triage flags as part of 26466827 7136 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7137 7138 int[] users = sUserManager.getUserIds(); 7139 int res = 0; 7140 for (int user : users) { 7141 // Remove the parent code cache 7142 try { 7143 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7144 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7145 } catch (InstallerException e) { 7146 Slog.w(TAG, "Failed to delete code cache directory", e); 7147 } 7148 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7149 for (int i = 0; i < childCount; i++) { 7150 PackageParser.Package childPkg = pkg.childPackages.get(i); 7151 // Remove the child code cache 7152 try { 7153 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7154 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7155 } catch (InstallerException e) { 7156 Slog.w(TAG, "Failed to delete code cache directory", e); 7157 } 7158 } 7159 } 7160 } 7161 7162 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7163 long lastUpdateTime) { 7164 // Set parent install/update time 7165 PackageSetting ps = (PackageSetting) pkg.mExtras; 7166 if (ps != null) { 7167 ps.firstInstallTime = firstInstallTime; 7168 ps.lastUpdateTime = lastUpdateTime; 7169 } 7170 // Set children install/update time 7171 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7172 for (int i = 0; i < childCount; i++) { 7173 PackageParser.Package childPkg = pkg.childPackages.get(i); 7174 ps = (PackageSetting) childPkg.mExtras; 7175 if (ps != null) { 7176 ps.firstInstallTime = firstInstallTime; 7177 ps.lastUpdateTime = lastUpdateTime; 7178 } 7179 } 7180 } 7181 7182 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7183 PackageParser.Package changingLib) { 7184 if (file.path != null) { 7185 usesLibraryFiles.add(file.path); 7186 return; 7187 } 7188 PackageParser.Package p = mPackages.get(file.apk); 7189 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7190 // If we are doing this while in the middle of updating a library apk, 7191 // then we need to make sure to use that new apk for determining the 7192 // dependencies here. (We haven't yet finished committing the new apk 7193 // to the package manager state.) 7194 if (p == null || p.packageName.equals(changingLib.packageName)) { 7195 p = changingLib; 7196 } 7197 } 7198 if (p != null) { 7199 usesLibraryFiles.addAll(p.getAllCodePaths()); 7200 } 7201 } 7202 7203 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7204 PackageParser.Package changingLib) throws PackageManagerException { 7205 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7206 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7207 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7208 for (int i=0; i<N; i++) { 7209 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7210 if (file == null) { 7211 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7212 "Package " + pkg.packageName + " requires unavailable shared library " 7213 + pkg.usesLibraries.get(i) + "; failing!"); 7214 } 7215 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7216 } 7217 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7218 for (int i=0; i<N; i++) { 7219 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7220 if (file == null) { 7221 Slog.w(TAG, "Package " + pkg.packageName 7222 + " desires unavailable shared library " 7223 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7224 } else { 7225 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7226 } 7227 } 7228 N = usesLibraryFiles.size(); 7229 if (N > 0) { 7230 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7231 } else { 7232 pkg.usesLibraryFiles = null; 7233 } 7234 } 7235 } 7236 7237 private static boolean hasString(List<String> list, List<String> which) { 7238 if (list == null) { 7239 return false; 7240 } 7241 for (int i=list.size()-1; i>=0; i--) { 7242 for (int j=which.size()-1; j>=0; j--) { 7243 if (which.get(j).equals(list.get(i))) { 7244 return true; 7245 } 7246 } 7247 } 7248 return false; 7249 } 7250 7251 private void updateAllSharedLibrariesLPw() { 7252 for (PackageParser.Package pkg : mPackages.values()) { 7253 try { 7254 updateSharedLibrariesLPw(pkg, null); 7255 } catch (PackageManagerException e) { 7256 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7257 } 7258 } 7259 } 7260 7261 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7262 PackageParser.Package changingPkg) { 7263 ArrayList<PackageParser.Package> res = null; 7264 for (PackageParser.Package pkg : mPackages.values()) { 7265 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7266 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7267 if (res == null) { 7268 res = new ArrayList<PackageParser.Package>(); 7269 } 7270 res.add(pkg); 7271 try { 7272 updateSharedLibrariesLPw(pkg, changingPkg); 7273 } catch (PackageManagerException e) { 7274 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7275 } 7276 } 7277 } 7278 return res; 7279 } 7280 7281 /** 7282 * Derive the value of the {@code cpuAbiOverride} based on the provided 7283 * value and an optional stored value from the package settings. 7284 */ 7285 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7286 String cpuAbiOverride = null; 7287 7288 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7289 cpuAbiOverride = null; 7290 } else if (abiOverride != null) { 7291 cpuAbiOverride = abiOverride; 7292 } else if (settings != null) { 7293 cpuAbiOverride = settings.cpuAbiOverrideString; 7294 } 7295 7296 return cpuAbiOverride; 7297 } 7298 7299 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7300 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7302 // If the package has children and this is the first dive in the function 7303 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7304 // whether all packages (parent and children) would be successfully scanned 7305 // before the actual scan since scanning mutates internal state and we want 7306 // to atomically install the package and its children. 7307 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7308 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7309 scanFlags |= SCAN_CHECK_ONLY; 7310 } 7311 } else { 7312 scanFlags &= ~SCAN_CHECK_ONLY; 7313 } 7314 7315 final PackageParser.Package scannedPkg; 7316 try { 7317 // Scan the parent 7318 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7319 // Scan the children 7320 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7321 for (int i = 0; i < childCount; i++) { 7322 PackageParser.Package childPkg = pkg.childPackages.get(i); 7323 scanPackageLI(childPkg, parseFlags, 7324 scanFlags, currentTime, user); 7325 } 7326 } finally { 7327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7328 } 7329 7330 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7331 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7332 } 7333 7334 return scannedPkg; 7335 } 7336 7337 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7338 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7339 boolean success = false; 7340 try { 7341 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7342 currentTime, user); 7343 success = true; 7344 return res; 7345 } finally { 7346 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7347 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7348 } 7349 } 7350 } 7351 7352 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7353 int scanFlags, long currentTime, UserHandle user) 7354 throws PackageManagerException { 7355 final File scanFile = new File(pkg.codePath); 7356 if (pkg.applicationInfo.getCodePath() == null || 7357 pkg.applicationInfo.getResourcePath() == null) { 7358 // Bail out. The resource and code paths haven't been set. 7359 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7360 "Code and resource paths haven't been set correctly"); 7361 } 7362 7363 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7364 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7365 } else { 7366 // Only allow system apps to be flagged as core apps. 7367 pkg.coreApp = false; 7368 } 7369 7370 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7371 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7372 } 7373 7374 if (mCustomResolverComponentName != null && 7375 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7376 setUpCustomResolverActivity(pkg); 7377 } 7378 7379 if (pkg.packageName.equals("android")) { 7380 synchronized (mPackages) { 7381 if (mAndroidApplication != null) { 7382 Slog.w(TAG, "*************************************************"); 7383 Slog.w(TAG, "Core android package being redefined. Skipping."); 7384 Slog.w(TAG, " file=" + scanFile); 7385 Slog.w(TAG, "*************************************************"); 7386 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7387 "Core android package being redefined. Skipping."); 7388 } 7389 7390 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7391 // Set up information for our fall-back user intent resolution activity. 7392 mPlatformPackage = pkg; 7393 pkg.mVersionCode = mSdkVersion; 7394 mAndroidApplication = pkg.applicationInfo; 7395 7396 if (!mResolverReplaced) { 7397 mResolveActivity.applicationInfo = mAndroidApplication; 7398 mResolveActivity.name = ResolverActivity.class.getName(); 7399 mResolveActivity.packageName = mAndroidApplication.packageName; 7400 mResolveActivity.processName = "system:ui"; 7401 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7402 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7403 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7404 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7405 mResolveActivity.exported = true; 7406 mResolveActivity.enabled = true; 7407 mResolveInfo.activityInfo = mResolveActivity; 7408 mResolveInfo.priority = 0; 7409 mResolveInfo.preferredOrder = 0; 7410 mResolveInfo.match = 0; 7411 mResolveComponentName = new ComponentName( 7412 mAndroidApplication.packageName, mResolveActivity.name); 7413 } 7414 } 7415 } 7416 } 7417 7418 if (DEBUG_PACKAGE_SCANNING) { 7419 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7420 Log.d(TAG, "Scanning package " + pkg.packageName); 7421 } 7422 7423 synchronized (mPackages) { 7424 if (mPackages.containsKey(pkg.packageName) 7425 || mSharedLibraries.containsKey(pkg.packageName)) { 7426 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7427 "Application package " + pkg.packageName 7428 + " already installed. Skipping duplicate."); 7429 } 7430 7431 // If we're only installing presumed-existing packages, require that the 7432 // scanned APK is both already known and at the path previously established 7433 // for it. Previously unknown packages we pick up normally, but if we have an 7434 // a priori expectation about this package's install presence, enforce it. 7435 // With a singular exception for new system packages. When an OTA contains 7436 // a new system package, we allow the codepath to change from a system location 7437 // to the user-installed location. If we don't allow this change, any newer, 7438 // user-installed version of the application will be ignored. 7439 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7440 if (mExpectingBetter.containsKey(pkg.packageName)) { 7441 logCriticalInfo(Log.WARN, 7442 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7443 } else { 7444 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7445 if (known != null) { 7446 if (DEBUG_PACKAGE_SCANNING) { 7447 Log.d(TAG, "Examining " + pkg.codePath 7448 + " and requiring known paths " + known.codePathString 7449 + " & " + known.resourcePathString); 7450 } 7451 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7452 || !pkg.applicationInfo.getResourcePath().equals( 7453 known.resourcePathString)) { 7454 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7455 "Application package " + pkg.packageName 7456 + " found at " + pkg.applicationInfo.getCodePath() 7457 + " but expected at " + known.codePathString 7458 + "; ignoring."); 7459 } 7460 } 7461 } 7462 } 7463 } 7464 7465 // Initialize package source and resource directories 7466 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7467 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7468 7469 SharedUserSetting suid = null; 7470 PackageSetting pkgSetting = null; 7471 7472 if (!isSystemApp(pkg)) { 7473 // Only system apps can use these features. 7474 pkg.mOriginalPackages = null; 7475 pkg.mRealPackage = null; 7476 pkg.mAdoptPermissions = null; 7477 } 7478 7479 // Getting the package setting may have a side-effect, so if we 7480 // are only checking if scan would succeed, stash a copy of the 7481 // old setting to restore at the end. 7482 PackageSetting nonMutatedPs = null; 7483 7484 // writer 7485 synchronized (mPackages) { 7486 if (pkg.mSharedUserId != null) { 7487 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7488 if (suid == null) { 7489 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7490 "Creating application package " + pkg.packageName 7491 + " for shared user failed"); 7492 } 7493 if (DEBUG_PACKAGE_SCANNING) { 7494 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7495 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7496 + "): packages=" + suid.packages); 7497 } 7498 } 7499 7500 // Check if we are renaming from an original package name. 7501 PackageSetting origPackage = null; 7502 String realName = null; 7503 if (pkg.mOriginalPackages != null) { 7504 // This package may need to be renamed to a previously 7505 // installed name. Let's check on that... 7506 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7507 if (pkg.mOriginalPackages.contains(renamed)) { 7508 // This package had originally been installed as the 7509 // original name, and we have already taken care of 7510 // transitioning to the new one. Just update the new 7511 // one to continue using the old name. 7512 realName = pkg.mRealPackage; 7513 if (!pkg.packageName.equals(renamed)) { 7514 // Callers into this function may have already taken 7515 // care of renaming the package; only do it here if 7516 // it is not already done. 7517 pkg.setPackageName(renamed); 7518 } 7519 7520 } else { 7521 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7522 if ((origPackage = mSettings.peekPackageLPr( 7523 pkg.mOriginalPackages.get(i))) != null) { 7524 // We do have the package already installed under its 7525 // original name... should we use it? 7526 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7527 // New package is not compatible with original. 7528 origPackage = null; 7529 continue; 7530 } else if (origPackage.sharedUser != null) { 7531 // Make sure uid is compatible between packages. 7532 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7533 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7534 + " to " + pkg.packageName + ": old uid " 7535 + origPackage.sharedUser.name 7536 + " differs from " + pkg.mSharedUserId); 7537 origPackage = null; 7538 continue; 7539 } 7540 } else { 7541 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7542 + pkg.packageName + " to old name " + origPackage.name); 7543 } 7544 break; 7545 } 7546 } 7547 } 7548 } 7549 7550 if (mTransferedPackages.contains(pkg.packageName)) { 7551 Slog.w(TAG, "Package " + pkg.packageName 7552 + " was transferred to another, but its .apk remains"); 7553 } 7554 7555 // See comments in nonMutatedPs declaration 7556 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7557 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7558 if (foundPs != null) { 7559 nonMutatedPs = new PackageSetting(foundPs); 7560 } 7561 } 7562 7563 // Just create the setting, don't add it yet. For already existing packages 7564 // the PkgSetting exists already and doesn't have to be created. 7565 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7566 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7567 pkg.applicationInfo.primaryCpuAbi, 7568 pkg.applicationInfo.secondaryCpuAbi, 7569 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7570 user, false); 7571 if (pkgSetting == null) { 7572 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7573 "Creating application package " + pkg.packageName + " failed"); 7574 } 7575 7576 if (pkgSetting.origPackage != null) { 7577 // If we are first transitioning from an original package, 7578 // fix up the new package's name now. We need to do this after 7579 // looking up the package under its new name, so getPackageLP 7580 // can take care of fiddling things correctly. 7581 pkg.setPackageName(origPackage.name); 7582 7583 // File a report about this. 7584 String msg = "New package " + pkgSetting.realName 7585 + " renamed to replace old package " + pkgSetting.name; 7586 reportSettingsProblem(Log.WARN, msg); 7587 7588 // Make a note of it. 7589 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7590 mTransferedPackages.add(origPackage.name); 7591 } 7592 7593 // No longer need to retain this. 7594 pkgSetting.origPackage = null; 7595 } 7596 7597 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7598 // Make a note of it. 7599 mTransferedPackages.add(pkg.packageName); 7600 } 7601 7602 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7603 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7604 } 7605 7606 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7607 // Check all shared libraries and map to their actual file path. 7608 // We only do this here for apps not on a system dir, because those 7609 // are the only ones that can fail an install due to this. We 7610 // will take care of the system apps by updating all of their 7611 // library paths after the scan is done. 7612 updateSharedLibrariesLPw(pkg, null); 7613 } 7614 7615 if (mFoundPolicyFile) { 7616 SELinuxMMAC.assignSeinfoValue(pkg); 7617 } 7618 7619 pkg.applicationInfo.uid = pkgSetting.appId; 7620 pkg.mExtras = pkgSetting; 7621 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7622 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7623 // We just determined the app is signed correctly, so bring 7624 // over the latest parsed certs. 7625 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7626 } else { 7627 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7628 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7629 "Package " + pkg.packageName + " upgrade keys do not match the " 7630 + "previously installed version"); 7631 } else { 7632 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7633 String msg = "System package " + pkg.packageName 7634 + " signature changed; retaining data."; 7635 reportSettingsProblem(Log.WARN, msg); 7636 } 7637 } 7638 } else { 7639 try { 7640 verifySignaturesLP(pkgSetting, pkg); 7641 // We just determined the app is signed correctly, so bring 7642 // over the latest parsed certs. 7643 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7644 } catch (PackageManagerException e) { 7645 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7646 throw e; 7647 } 7648 // The signature has changed, but this package is in the system 7649 // image... let's recover! 7650 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7651 // However... if this package is part of a shared user, but it 7652 // doesn't match the signature of the shared user, let's fail. 7653 // What this means is that you can't change the signatures 7654 // associated with an overall shared user, which doesn't seem all 7655 // that unreasonable. 7656 if (pkgSetting.sharedUser != null) { 7657 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7658 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7659 throw new PackageManagerException( 7660 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7661 "Signature mismatch for shared user: " 7662 + pkgSetting.sharedUser); 7663 } 7664 } 7665 // File a report about this. 7666 String msg = "System package " + pkg.packageName 7667 + " signature changed; retaining data."; 7668 reportSettingsProblem(Log.WARN, msg); 7669 } 7670 } 7671 // Verify that this new package doesn't have any content providers 7672 // that conflict with existing packages. Only do this if the 7673 // package isn't already installed, since we don't want to break 7674 // things that are installed. 7675 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7676 final int N = pkg.providers.size(); 7677 int i; 7678 for (i=0; i<N; i++) { 7679 PackageParser.Provider p = pkg.providers.get(i); 7680 if (p.info.authority != null) { 7681 String names[] = p.info.authority.split(";"); 7682 for (int j = 0; j < names.length; j++) { 7683 if (mProvidersByAuthority.containsKey(names[j])) { 7684 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7685 final String otherPackageName = 7686 ((other != null && other.getComponentName() != null) ? 7687 other.getComponentName().getPackageName() : "?"); 7688 throw new PackageManagerException( 7689 INSTALL_FAILED_CONFLICTING_PROVIDER, 7690 "Can't install because provider name " + names[j] 7691 + " (in package " + pkg.applicationInfo.packageName 7692 + ") is already used by " + otherPackageName); 7693 } 7694 } 7695 } 7696 } 7697 } 7698 7699 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7700 // This package wants to adopt ownership of permissions from 7701 // another package. 7702 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7703 final String origName = pkg.mAdoptPermissions.get(i); 7704 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7705 if (orig != null) { 7706 if (verifyPackageUpdateLPr(orig, pkg)) { 7707 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7708 + pkg.packageName); 7709 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7710 } 7711 } 7712 } 7713 } 7714 } 7715 7716 final String pkgName = pkg.packageName; 7717 7718 final long scanFileTime = scanFile.lastModified(); 7719 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7720 pkg.applicationInfo.processName = fixProcessName( 7721 pkg.applicationInfo.packageName, 7722 pkg.applicationInfo.processName, 7723 pkg.applicationInfo.uid); 7724 7725 if (pkg != mPlatformPackage) { 7726 // Get all of our default paths setup 7727 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7728 } 7729 7730 final String path = scanFile.getPath(); 7731 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7732 7733 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7734 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7735 7736 // Some system apps still use directory structure for native libraries 7737 // in which case we might end up not detecting abi solely based on apk 7738 // structure. Try to detect abi based on directory structure. 7739 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7740 pkg.applicationInfo.primaryCpuAbi == null) { 7741 setBundledAppAbisAndRoots(pkg, pkgSetting); 7742 setNativeLibraryPaths(pkg); 7743 } 7744 7745 } else { 7746 if ((scanFlags & SCAN_MOVE) != 0) { 7747 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7748 // but we already have this packages package info in the PackageSetting. We just 7749 // use that and derive the native library path based on the new codepath. 7750 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7751 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7752 } 7753 7754 // Set native library paths again. For moves, the path will be updated based on the 7755 // ABIs we've determined above. For non-moves, the path will be updated based on the 7756 // ABIs we determined during compilation, but the path will depend on the final 7757 // package path (after the rename away from the stage path). 7758 setNativeLibraryPaths(pkg); 7759 } 7760 7761 // This is a special case for the "system" package, where the ABI is 7762 // dictated by the zygote configuration (and init.rc). We should keep track 7763 // of this ABI so that we can deal with "normal" applications that run under 7764 // the same UID correctly. 7765 if (mPlatformPackage == pkg) { 7766 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7767 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7768 } 7769 7770 // If there's a mismatch between the abi-override in the package setting 7771 // and the abiOverride specified for the install. Warn about this because we 7772 // would've already compiled the app without taking the package setting into 7773 // account. 7774 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7775 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7776 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7777 " for package " + pkg.packageName); 7778 } 7779 } 7780 7781 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7782 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7783 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7784 7785 // Copy the derived override back to the parsed package, so that we can 7786 // update the package settings accordingly. 7787 pkg.cpuAbiOverride = cpuAbiOverride; 7788 7789 if (DEBUG_ABI_SELECTION) { 7790 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7791 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7792 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7793 } 7794 7795 // Push the derived path down into PackageSettings so we know what to 7796 // clean up at uninstall time. 7797 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7798 7799 if (DEBUG_ABI_SELECTION) { 7800 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7801 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7802 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7803 } 7804 7805 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7806 // We don't do this here during boot because we can do it all 7807 // at once after scanning all existing packages. 7808 // 7809 // We also do this *before* we perform dexopt on this package, so that 7810 // we can avoid redundant dexopts, and also to make sure we've got the 7811 // code and package path correct. 7812 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7813 pkg, true /* boot complete */); 7814 } 7815 7816 if (mFactoryTest && pkg.requestedPermissions.contains( 7817 android.Manifest.permission.FACTORY_TEST)) { 7818 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7819 } 7820 7821 ArrayList<PackageParser.Package> clientLibPkgs = null; 7822 7823 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7824 if (nonMutatedPs != null) { 7825 synchronized (mPackages) { 7826 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7827 } 7828 } 7829 return pkg; 7830 } 7831 7832 // Only privileged apps and updated privileged apps can add child packages. 7833 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7834 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7835 throw new PackageManagerException("Only privileged apps and updated " 7836 + "privileged apps can add child packages. Ignoring package " 7837 + pkg.packageName); 7838 } 7839 final int childCount = pkg.childPackages.size(); 7840 for (int i = 0; i < childCount; i++) { 7841 PackageParser.Package childPkg = pkg.childPackages.get(i); 7842 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7843 childPkg.packageName)) { 7844 throw new PackageManagerException("Cannot override a child package of " 7845 + "another disabled system app. Ignoring package " + pkg.packageName); 7846 } 7847 } 7848 } 7849 7850 // writer 7851 synchronized (mPackages) { 7852 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7853 // Only system apps can add new shared libraries. 7854 if (pkg.libraryNames != null) { 7855 for (int i=0; i<pkg.libraryNames.size(); i++) { 7856 String name = pkg.libraryNames.get(i); 7857 boolean allowed = false; 7858 if (pkg.isUpdatedSystemApp()) { 7859 // New library entries can only be added through the 7860 // system image. This is important to get rid of a lot 7861 // of nasty edge cases: for example if we allowed a non- 7862 // system update of the app to add a library, then uninstalling 7863 // the update would make the library go away, and assumptions 7864 // we made such as through app install filtering would now 7865 // have allowed apps on the device which aren't compatible 7866 // with it. Better to just have the restriction here, be 7867 // conservative, and create many fewer cases that can negatively 7868 // impact the user experience. 7869 final PackageSetting sysPs = mSettings 7870 .getDisabledSystemPkgLPr(pkg.packageName); 7871 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7872 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7873 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7874 allowed = true; 7875 break; 7876 } 7877 } 7878 } 7879 } else { 7880 allowed = true; 7881 } 7882 if (allowed) { 7883 if (!mSharedLibraries.containsKey(name)) { 7884 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7885 } else if (!name.equals(pkg.packageName)) { 7886 Slog.w(TAG, "Package " + pkg.packageName + " library " 7887 + name + " already exists; skipping"); 7888 } 7889 } else { 7890 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7891 + name + " that is not declared on system image; skipping"); 7892 } 7893 } 7894 if ((scanFlags & SCAN_BOOTING) == 0) { 7895 // If we are not booting, we need to update any applications 7896 // that are clients of our shared library. If we are booting, 7897 // this will all be done once the scan is complete. 7898 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7899 } 7900 } 7901 } 7902 } 7903 7904 // Request the ActivityManager to kill the process(only for existing packages) 7905 // so that we do not end up in a confused state while the user is still using the older 7906 // version of the application while the new one gets installed. 7907 if ((scanFlags & SCAN_REPLACING) != 0) { 7908 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7909 7910 killApplication(pkg.applicationInfo.packageName, 7911 pkg.applicationInfo.uid, "replace pkg"); 7912 7913 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7914 } 7915 7916 // Also need to kill any apps that are dependent on the library. 7917 if (clientLibPkgs != null) { 7918 for (int i=0; i<clientLibPkgs.size(); i++) { 7919 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7920 killApplication(clientPkg.applicationInfo.packageName, 7921 clientPkg.applicationInfo.uid, "update lib"); 7922 } 7923 } 7924 7925 // Make sure we're not adding any bogus keyset info 7926 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7927 ksms.assertScannedPackageValid(pkg); 7928 7929 // writer 7930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7931 7932 boolean createIdmapFailed = false; 7933 synchronized (mPackages) { 7934 // We don't expect installation to fail beyond this point 7935 7936 // Add the new setting to mSettings 7937 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7938 // Add the new setting to mPackages 7939 mPackages.put(pkg.applicationInfo.packageName, pkg); 7940 // Make sure we don't accidentally delete its data. 7941 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7942 while (iter.hasNext()) { 7943 PackageCleanItem item = iter.next(); 7944 if (pkgName.equals(item.packageName)) { 7945 iter.remove(); 7946 } 7947 } 7948 7949 // Take care of first install / last update times. 7950 if (currentTime != 0) { 7951 if (pkgSetting.firstInstallTime == 0) { 7952 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7953 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7954 pkgSetting.lastUpdateTime = currentTime; 7955 } 7956 } else if (pkgSetting.firstInstallTime == 0) { 7957 // We need *something*. Take time time stamp of the file. 7958 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7959 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7960 if (scanFileTime != pkgSetting.timeStamp) { 7961 // A package on the system image has changed; consider this 7962 // to be an update. 7963 pkgSetting.lastUpdateTime = scanFileTime; 7964 } 7965 } 7966 7967 // Add the package's KeySets to the global KeySetManagerService 7968 ksms.addScannedPackageLPw(pkg); 7969 7970 int N = pkg.providers.size(); 7971 StringBuilder r = null; 7972 int i; 7973 for (i=0; i<N; i++) { 7974 PackageParser.Provider p = pkg.providers.get(i); 7975 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7976 p.info.processName, pkg.applicationInfo.uid); 7977 mProviders.addProvider(p); 7978 p.syncable = p.info.isSyncable; 7979 if (p.info.authority != null) { 7980 String names[] = p.info.authority.split(";"); 7981 p.info.authority = null; 7982 for (int j = 0; j < names.length; j++) { 7983 if (j == 1 && p.syncable) { 7984 // We only want the first authority for a provider to possibly be 7985 // syncable, so if we already added this provider using a different 7986 // authority clear the syncable flag. We copy the provider before 7987 // changing it because the mProviders object contains a reference 7988 // to a provider that we don't want to change. 7989 // Only do this for the second authority since the resulting provider 7990 // object can be the same for all future authorities for this provider. 7991 p = new PackageParser.Provider(p); 7992 p.syncable = false; 7993 } 7994 if (!mProvidersByAuthority.containsKey(names[j])) { 7995 mProvidersByAuthority.put(names[j], p); 7996 if (p.info.authority == null) { 7997 p.info.authority = names[j]; 7998 } else { 7999 p.info.authority = p.info.authority + ";" + names[j]; 8000 } 8001 if (DEBUG_PACKAGE_SCANNING) { 8002 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8003 Log.d(TAG, "Registered content provider: " + names[j] 8004 + ", className = " + p.info.name + ", isSyncable = " 8005 + p.info.isSyncable); 8006 } 8007 } else { 8008 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8009 Slog.w(TAG, "Skipping provider name " + names[j] + 8010 " (in package " + pkg.applicationInfo.packageName + 8011 "): name already used by " 8012 + ((other != null && other.getComponentName() != null) 8013 ? other.getComponentName().getPackageName() : "?")); 8014 } 8015 } 8016 } 8017 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8018 if (r == null) { 8019 r = new StringBuilder(256); 8020 } else { 8021 r.append(' '); 8022 } 8023 r.append(p.info.name); 8024 } 8025 } 8026 if (r != null) { 8027 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8028 } 8029 8030 N = pkg.services.size(); 8031 r = null; 8032 for (i=0; i<N; i++) { 8033 PackageParser.Service s = pkg.services.get(i); 8034 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8035 s.info.processName, pkg.applicationInfo.uid); 8036 mServices.addService(s); 8037 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8038 if (r == null) { 8039 r = new StringBuilder(256); 8040 } else { 8041 r.append(' '); 8042 } 8043 r.append(s.info.name); 8044 } 8045 } 8046 if (r != null) { 8047 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8048 } 8049 8050 N = pkg.receivers.size(); 8051 r = null; 8052 for (i=0; i<N; i++) { 8053 PackageParser.Activity a = pkg.receivers.get(i); 8054 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8055 a.info.processName, pkg.applicationInfo.uid); 8056 mReceivers.addActivity(a, "receiver"); 8057 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8058 if (r == null) { 8059 r = new StringBuilder(256); 8060 } else { 8061 r.append(' '); 8062 } 8063 r.append(a.info.name); 8064 } 8065 } 8066 if (r != null) { 8067 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8068 } 8069 8070 N = pkg.activities.size(); 8071 r = null; 8072 for (i=0; i<N; i++) { 8073 PackageParser.Activity a = pkg.activities.get(i); 8074 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8075 a.info.processName, pkg.applicationInfo.uid); 8076 mActivities.addActivity(a, "activity"); 8077 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8078 if (r == null) { 8079 r = new StringBuilder(256); 8080 } else { 8081 r.append(' '); 8082 } 8083 r.append(a.info.name); 8084 } 8085 } 8086 if (r != null) { 8087 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8088 } 8089 8090 N = pkg.permissionGroups.size(); 8091 r = null; 8092 for (i=0; i<N; i++) { 8093 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8094 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8095 if (cur == null) { 8096 mPermissionGroups.put(pg.info.name, pg); 8097 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8098 if (r == null) { 8099 r = new StringBuilder(256); 8100 } else { 8101 r.append(' '); 8102 } 8103 r.append(pg.info.name); 8104 } 8105 } else { 8106 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8107 + pg.info.packageName + " ignored: original from " 8108 + cur.info.packageName); 8109 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8110 if (r == null) { 8111 r = new StringBuilder(256); 8112 } else { 8113 r.append(' '); 8114 } 8115 r.append("DUP:"); 8116 r.append(pg.info.name); 8117 } 8118 } 8119 } 8120 if (r != null) { 8121 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8122 } 8123 8124 N = pkg.permissions.size(); 8125 r = null; 8126 for (i=0; i<N; i++) { 8127 PackageParser.Permission p = pkg.permissions.get(i); 8128 8129 // Assume by default that we did not install this permission into the system. 8130 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8131 8132 // Now that permission groups have a special meaning, we ignore permission 8133 // groups for legacy apps to prevent unexpected behavior. In particular, 8134 // permissions for one app being granted to someone just becase they happen 8135 // to be in a group defined by another app (before this had no implications). 8136 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8137 p.group = mPermissionGroups.get(p.info.group); 8138 // Warn for a permission in an unknown group. 8139 if (p.info.group != null && p.group == null) { 8140 Slog.w(TAG, "Permission " + p.info.name + " from package " 8141 + p.info.packageName + " in an unknown group " + p.info.group); 8142 } 8143 } 8144 8145 ArrayMap<String, BasePermission> permissionMap = 8146 p.tree ? mSettings.mPermissionTrees 8147 : mSettings.mPermissions; 8148 BasePermission bp = permissionMap.get(p.info.name); 8149 8150 // Allow system apps to redefine non-system permissions 8151 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8152 final boolean currentOwnerIsSystem = (bp.perm != null 8153 && isSystemApp(bp.perm.owner)); 8154 if (isSystemApp(p.owner)) { 8155 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8156 // It's a built-in permission and no owner, take ownership now 8157 bp.packageSetting = pkgSetting; 8158 bp.perm = p; 8159 bp.uid = pkg.applicationInfo.uid; 8160 bp.sourcePackage = p.info.packageName; 8161 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8162 } else if (!currentOwnerIsSystem) { 8163 String msg = "New decl " + p.owner + " of permission " 8164 + p.info.name + " is system; overriding " + bp.sourcePackage; 8165 reportSettingsProblem(Log.WARN, msg); 8166 bp = null; 8167 } 8168 } 8169 } 8170 8171 if (bp == null) { 8172 bp = new BasePermission(p.info.name, p.info.packageName, 8173 BasePermission.TYPE_NORMAL); 8174 permissionMap.put(p.info.name, bp); 8175 } 8176 8177 if (bp.perm == null) { 8178 if (bp.sourcePackage == null 8179 || bp.sourcePackage.equals(p.info.packageName)) { 8180 BasePermission tree = findPermissionTreeLP(p.info.name); 8181 if (tree == null 8182 || tree.sourcePackage.equals(p.info.packageName)) { 8183 bp.packageSetting = pkgSetting; 8184 bp.perm = p; 8185 bp.uid = pkg.applicationInfo.uid; 8186 bp.sourcePackage = p.info.packageName; 8187 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8188 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8189 if (r == null) { 8190 r = new StringBuilder(256); 8191 } else { 8192 r.append(' '); 8193 } 8194 r.append(p.info.name); 8195 } 8196 } else { 8197 Slog.w(TAG, "Permission " + p.info.name + " from package " 8198 + p.info.packageName + " ignored: base tree " 8199 + tree.name + " is from package " 8200 + tree.sourcePackage); 8201 } 8202 } else { 8203 Slog.w(TAG, "Permission " + p.info.name + " from package " 8204 + p.info.packageName + " ignored: original from " 8205 + bp.sourcePackage); 8206 } 8207 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8208 if (r == null) { 8209 r = new StringBuilder(256); 8210 } else { 8211 r.append(' '); 8212 } 8213 r.append("DUP:"); 8214 r.append(p.info.name); 8215 } 8216 if (bp.perm == p) { 8217 bp.protectionLevel = p.info.protectionLevel; 8218 } 8219 } 8220 8221 if (r != null) { 8222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8223 } 8224 8225 N = pkg.instrumentation.size(); 8226 r = null; 8227 for (i=0; i<N; i++) { 8228 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8229 a.info.packageName = pkg.applicationInfo.packageName; 8230 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8231 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8232 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8233 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8234 a.info.dataDir = pkg.applicationInfo.dataDir; 8235 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8236 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8237 8238 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8239 // need other information about the application, like the ABI and what not ? 8240 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8241 mInstrumentation.put(a.getComponentName(), a); 8242 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8243 if (r == null) { 8244 r = new StringBuilder(256); 8245 } else { 8246 r.append(' '); 8247 } 8248 r.append(a.info.name); 8249 } 8250 } 8251 if (r != null) { 8252 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8253 } 8254 8255 if (pkg.protectedBroadcasts != null) { 8256 N = pkg.protectedBroadcasts.size(); 8257 for (i=0; i<N; i++) { 8258 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8259 } 8260 } 8261 8262 pkgSetting.setTimeStamp(scanFileTime); 8263 8264 // Create idmap files for pairs of (packages, overlay packages). 8265 // Note: "android", ie framework-res.apk, is handled by native layers. 8266 if (pkg.mOverlayTarget != null) { 8267 // This is an overlay package. 8268 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8269 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8270 mOverlays.put(pkg.mOverlayTarget, 8271 new ArrayMap<String, PackageParser.Package>()); 8272 } 8273 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8274 map.put(pkg.packageName, pkg); 8275 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8276 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8277 createIdmapFailed = true; 8278 } 8279 } 8280 } else if (mOverlays.containsKey(pkg.packageName) && 8281 !pkg.packageName.equals("android")) { 8282 // This is a regular package, with one or more known overlay packages. 8283 createIdmapsForPackageLI(pkg); 8284 } 8285 } 8286 8287 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8288 8289 if (createIdmapFailed) { 8290 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8291 "scanPackageLI failed to createIdmap"); 8292 } 8293 return pkg; 8294 } 8295 8296 /** 8297 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8298 * is derived purely on the basis of the contents of {@code scanFile} and 8299 * {@code cpuAbiOverride}. 8300 * 8301 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8302 */ 8303 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8304 String cpuAbiOverride, boolean extractLibs) 8305 throws PackageManagerException { 8306 // TODO: We can probably be smarter about this stuff. For installed apps, 8307 // we can calculate this information at install time once and for all. For 8308 // system apps, we can probably assume that this information doesn't change 8309 // after the first boot scan. As things stand, we do lots of unnecessary work. 8310 8311 // Give ourselves some initial paths; we'll come back for another 8312 // pass once we've determined ABI below. 8313 setNativeLibraryPaths(pkg); 8314 8315 // We would never need to extract libs for forward-locked and external packages, 8316 // since the container service will do it for us. We shouldn't attempt to 8317 // extract libs from system app when it was not updated. 8318 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8319 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8320 extractLibs = false; 8321 } 8322 8323 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8324 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8325 8326 NativeLibraryHelper.Handle handle = null; 8327 try { 8328 handle = NativeLibraryHelper.Handle.create(pkg); 8329 // TODO(multiArch): This can be null for apps that didn't go through the 8330 // usual installation process. We can calculate it again, like we 8331 // do during install time. 8332 // 8333 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8334 // unnecessary. 8335 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8336 8337 // Null out the abis so that they can be recalculated. 8338 pkg.applicationInfo.primaryCpuAbi = null; 8339 pkg.applicationInfo.secondaryCpuAbi = null; 8340 if (isMultiArch(pkg.applicationInfo)) { 8341 // Warn if we've set an abiOverride for multi-lib packages.. 8342 // By definition, we need to copy both 32 and 64 bit libraries for 8343 // such packages. 8344 if (pkg.cpuAbiOverride != null 8345 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8346 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8347 } 8348 8349 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8350 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8351 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8352 if (extractLibs) { 8353 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8354 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8355 useIsaSpecificSubdirs); 8356 } else { 8357 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8358 } 8359 } 8360 8361 maybeThrowExceptionForMultiArchCopy( 8362 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8363 8364 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8365 if (extractLibs) { 8366 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8367 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8368 useIsaSpecificSubdirs); 8369 } else { 8370 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8371 } 8372 } 8373 8374 maybeThrowExceptionForMultiArchCopy( 8375 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8376 8377 if (abi64 >= 0) { 8378 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8379 } 8380 8381 if (abi32 >= 0) { 8382 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8383 if (abi64 >= 0) { 8384 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8385 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8386 pkg.applicationInfo.primaryCpuAbi = abi; 8387 } else { 8388 pkg.applicationInfo.secondaryCpuAbi = abi; 8389 } 8390 } else { 8391 pkg.applicationInfo.primaryCpuAbi = abi; 8392 } 8393 } 8394 8395 } else { 8396 String[] abiList = (cpuAbiOverride != null) ? 8397 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8398 8399 // Enable gross and lame hacks for apps that are built with old 8400 // SDK tools. We must scan their APKs for renderscript bitcode and 8401 // not launch them if it's present. Don't bother checking on devices 8402 // that don't have 64 bit support. 8403 boolean needsRenderScriptOverride = false; 8404 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8405 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8406 abiList = Build.SUPPORTED_32_BIT_ABIS; 8407 needsRenderScriptOverride = true; 8408 } 8409 8410 final int copyRet; 8411 if (extractLibs) { 8412 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8413 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8414 } else { 8415 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8416 } 8417 8418 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8419 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8420 "Error unpackaging native libs for app, errorCode=" + copyRet); 8421 } 8422 8423 if (copyRet >= 0) { 8424 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8425 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8426 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8427 } else if (needsRenderScriptOverride) { 8428 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8429 } 8430 } 8431 } catch (IOException ioe) { 8432 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8433 } finally { 8434 IoUtils.closeQuietly(handle); 8435 } 8436 8437 // Now that we've calculated the ABIs and determined if it's an internal app, 8438 // we will go ahead and populate the nativeLibraryPath. 8439 setNativeLibraryPaths(pkg); 8440 } 8441 8442 /** 8443 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8444 * i.e, so that all packages can be run inside a single process if required. 8445 * 8446 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8447 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8448 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8449 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8450 * updating a package that belongs to a shared user. 8451 * 8452 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8453 * adds unnecessary complexity. 8454 */ 8455 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8456 PackageParser.Package scannedPackage, boolean bootComplete) { 8457 String requiredInstructionSet = null; 8458 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8459 requiredInstructionSet = VMRuntime.getInstructionSet( 8460 scannedPackage.applicationInfo.primaryCpuAbi); 8461 } 8462 8463 PackageSetting requirer = null; 8464 for (PackageSetting ps : packagesForUser) { 8465 // If packagesForUser contains scannedPackage, we skip it. This will happen 8466 // when scannedPackage is an update of an existing package. Without this check, 8467 // we will never be able to change the ABI of any package belonging to a shared 8468 // user, even if it's compatible with other packages. 8469 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8470 if (ps.primaryCpuAbiString == null) { 8471 continue; 8472 } 8473 8474 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8475 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8476 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8477 // this but there's not much we can do. 8478 String errorMessage = "Instruction set mismatch, " 8479 + ((requirer == null) ? "[caller]" : requirer) 8480 + " requires " + requiredInstructionSet + " whereas " + ps 8481 + " requires " + instructionSet; 8482 Slog.w(TAG, errorMessage); 8483 } 8484 8485 if (requiredInstructionSet == null) { 8486 requiredInstructionSet = instructionSet; 8487 requirer = ps; 8488 } 8489 } 8490 } 8491 8492 if (requiredInstructionSet != null) { 8493 String adjustedAbi; 8494 if (requirer != null) { 8495 // requirer != null implies that either scannedPackage was null or that scannedPackage 8496 // did not require an ABI, in which case we have to adjust scannedPackage to match 8497 // the ABI of the set (which is the same as requirer's ABI) 8498 adjustedAbi = requirer.primaryCpuAbiString; 8499 if (scannedPackage != null) { 8500 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8501 } 8502 } else { 8503 // requirer == null implies that we're updating all ABIs in the set to 8504 // match scannedPackage. 8505 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8506 } 8507 8508 for (PackageSetting ps : packagesForUser) { 8509 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8510 if (ps.primaryCpuAbiString != null) { 8511 continue; 8512 } 8513 8514 ps.primaryCpuAbiString = adjustedAbi; 8515 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8516 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8517 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8518 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8519 + " (requirer=" 8520 + (requirer == null ? "null" : requirer.pkg.packageName) 8521 + ", scannedPackage=" 8522 + (scannedPackage != null ? scannedPackage.packageName : "null") 8523 + ")"); 8524 try { 8525 mInstaller.rmdex(ps.codePathString, 8526 getDexCodeInstructionSet(getPreferredInstructionSet())); 8527 } catch (InstallerException ignored) { 8528 } 8529 } 8530 } 8531 } 8532 } 8533 } 8534 8535 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8536 synchronized (mPackages) { 8537 mResolverReplaced = true; 8538 // Set up information for custom user intent resolution activity. 8539 mResolveActivity.applicationInfo = pkg.applicationInfo; 8540 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8541 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8542 mResolveActivity.processName = pkg.applicationInfo.packageName; 8543 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8544 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8545 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8546 mResolveActivity.theme = 0; 8547 mResolveActivity.exported = true; 8548 mResolveActivity.enabled = true; 8549 mResolveInfo.activityInfo = mResolveActivity; 8550 mResolveInfo.priority = 0; 8551 mResolveInfo.preferredOrder = 0; 8552 mResolveInfo.match = 0; 8553 mResolveComponentName = mCustomResolverComponentName; 8554 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8555 mResolveComponentName); 8556 } 8557 } 8558 8559 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8560 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8561 8562 // Set up information for ephemeral installer activity 8563 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8564 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8565 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8566 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8567 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8568 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8569 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8570 mEphemeralInstallerActivity.theme = 0; 8571 mEphemeralInstallerActivity.exported = true; 8572 mEphemeralInstallerActivity.enabled = true; 8573 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8574 mEphemeralInstallerInfo.priority = 0; 8575 mEphemeralInstallerInfo.preferredOrder = 0; 8576 mEphemeralInstallerInfo.match = 0; 8577 8578 if (DEBUG_EPHEMERAL) { 8579 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8580 } 8581 } 8582 8583 private static String calculateBundledApkRoot(final String codePathString) { 8584 final File codePath = new File(codePathString); 8585 final File codeRoot; 8586 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8587 codeRoot = Environment.getRootDirectory(); 8588 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8589 codeRoot = Environment.getOemDirectory(); 8590 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8591 codeRoot = Environment.getVendorDirectory(); 8592 } else { 8593 // Unrecognized code path; take its top real segment as the apk root: 8594 // e.g. /something/app/blah.apk => /something 8595 try { 8596 File f = codePath.getCanonicalFile(); 8597 File parent = f.getParentFile(); // non-null because codePath is a file 8598 File tmp; 8599 while ((tmp = parent.getParentFile()) != null) { 8600 f = parent; 8601 parent = tmp; 8602 } 8603 codeRoot = f; 8604 Slog.w(TAG, "Unrecognized code path " 8605 + codePath + " - using " + codeRoot); 8606 } catch (IOException e) { 8607 // Can't canonicalize the code path -- shenanigans? 8608 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8609 return Environment.getRootDirectory().getPath(); 8610 } 8611 } 8612 return codeRoot.getPath(); 8613 } 8614 8615 /** 8616 * Derive and set the location of native libraries for the given package, 8617 * which varies depending on where and how the package was installed. 8618 */ 8619 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8620 final ApplicationInfo info = pkg.applicationInfo; 8621 final String codePath = pkg.codePath; 8622 final File codeFile = new File(codePath); 8623 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8624 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8625 8626 info.nativeLibraryRootDir = null; 8627 info.nativeLibraryRootRequiresIsa = false; 8628 info.nativeLibraryDir = null; 8629 info.secondaryNativeLibraryDir = null; 8630 8631 if (isApkFile(codeFile)) { 8632 // Monolithic install 8633 if (bundledApp) { 8634 // If "/system/lib64/apkname" exists, assume that is the per-package 8635 // native library directory to use; otherwise use "/system/lib/apkname". 8636 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8637 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8638 getPrimaryInstructionSet(info)); 8639 8640 // This is a bundled system app so choose the path based on the ABI. 8641 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8642 // is just the default path. 8643 final String apkName = deriveCodePathName(codePath); 8644 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8645 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8646 apkName).getAbsolutePath(); 8647 8648 if (info.secondaryCpuAbi != null) { 8649 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8650 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8651 secondaryLibDir, apkName).getAbsolutePath(); 8652 } 8653 } else if (asecApp) { 8654 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8655 .getAbsolutePath(); 8656 } else { 8657 final String apkName = deriveCodePathName(codePath); 8658 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8659 .getAbsolutePath(); 8660 } 8661 8662 info.nativeLibraryRootRequiresIsa = false; 8663 info.nativeLibraryDir = info.nativeLibraryRootDir; 8664 } else { 8665 // Cluster install 8666 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8667 info.nativeLibraryRootRequiresIsa = true; 8668 8669 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8670 getPrimaryInstructionSet(info)).getAbsolutePath(); 8671 8672 if (info.secondaryCpuAbi != null) { 8673 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8674 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8675 } 8676 } 8677 } 8678 8679 /** 8680 * Calculate the abis and roots for a bundled app. These can uniquely 8681 * be determined from the contents of the system partition, i.e whether 8682 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8683 * of this information, and instead assume that the system was built 8684 * sensibly. 8685 */ 8686 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8687 PackageSetting pkgSetting) { 8688 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8689 8690 // If "/system/lib64/apkname" exists, assume that is the per-package 8691 // native library directory to use; otherwise use "/system/lib/apkname". 8692 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8693 setBundledAppAbi(pkg, apkRoot, apkName); 8694 // pkgSetting might be null during rescan following uninstall of updates 8695 // to a bundled app, so accommodate that possibility. The settings in 8696 // that case will be established later from the parsed package. 8697 // 8698 // If the settings aren't null, sync them up with what we've just derived. 8699 // note that apkRoot isn't stored in the package settings. 8700 if (pkgSetting != null) { 8701 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8702 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8703 } 8704 } 8705 8706 /** 8707 * Deduces the ABI of a bundled app and sets the relevant fields on the 8708 * parsed pkg object. 8709 * 8710 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8711 * under which system libraries are installed. 8712 * @param apkName the name of the installed package. 8713 */ 8714 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8715 final File codeFile = new File(pkg.codePath); 8716 8717 final boolean has64BitLibs; 8718 final boolean has32BitLibs; 8719 if (isApkFile(codeFile)) { 8720 // Monolithic install 8721 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8722 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8723 } else { 8724 // Cluster install 8725 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8726 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8727 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8728 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8729 has64BitLibs = (new File(rootDir, isa)).exists(); 8730 } else { 8731 has64BitLibs = false; 8732 } 8733 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8734 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8735 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8736 has32BitLibs = (new File(rootDir, isa)).exists(); 8737 } else { 8738 has32BitLibs = false; 8739 } 8740 } 8741 8742 if (has64BitLibs && !has32BitLibs) { 8743 // The package has 64 bit libs, but not 32 bit libs. Its primary 8744 // ABI should be 64 bit. We can safely assume here that the bundled 8745 // native libraries correspond to the most preferred ABI in the list. 8746 8747 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8748 pkg.applicationInfo.secondaryCpuAbi = null; 8749 } else if (has32BitLibs && !has64BitLibs) { 8750 // The package has 32 bit libs but not 64 bit libs. Its primary 8751 // ABI should be 32 bit. 8752 8753 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8754 pkg.applicationInfo.secondaryCpuAbi = null; 8755 } else if (has32BitLibs && has64BitLibs) { 8756 // The application has both 64 and 32 bit bundled libraries. We check 8757 // here that the app declares multiArch support, and warn if it doesn't. 8758 // 8759 // We will be lenient here and record both ABIs. The primary will be the 8760 // ABI that's higher on the list, i.e, a device that's configured to prefer 8761 // 64 bit apps will see a 64 bit primary ABI, 8762 8763 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8764 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8765 } 8766 8767 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8768 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8769 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8770 } else { 8771 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8772 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8773 } 8774 } else { 8775 pkg.applicationInfo.primaryCpuAbi = null; 8776 pkg.applicationInfo.secondaryCpuAbi = null; 8777 } 8778 } 8779 8780 private void killPackage(PackageParser.Package pkg, String reason) { 8781 // Kill the parent package 8782 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8783 // Kill the child packages 8784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8785 for (int i = 0; i < childCount; i++) { 8786 PackageParser.Package childPkg = pkg.childPackages.get(i); 8787 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8788 } 8789 } 8790 8791 private void killApplication(String pkgName, int appId, String reason) { 8792 // Request the ActivityManager to kill the process(only for existing packages) 8793 // so that we do not end up in a confused state while the user is still using the older 8794 // version of the application while the new one gets installed. 8795 IActivityManager am = ActivityManagerNative.getDefault(); 8796 if (am != null) { 8797 try { 8798 am.killApplicationWithAppId(pkgName, appId, reason); 8799 } catch (RemoteException e) { 8800 } 8801 } 8802 } 8803 8804 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8805 // Remove the parent package setting 8806 PackageSetting ps = (PackageSetting) pkg.mExtras; 8807 if (ps != null) { 8808 removePackageLI(ps, chatty); 8809 } 8810 // Remove the child package setting 8811 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8812 for (int i = 0; i < childCount; i++) { 8813 PackageParser.Package childPkg = pkg.childPackages.get(i); 8814 ps = (PackageSetting) childPkg.mExtras; 8815 if (ps != null) { 8816 removePackageLI(ps, chatty); 8817 } 8818 } 8819 } 8820 8821 void removePackageLI(PackageSetting ps, boolean chatty) { 8822 if (DEBUG_INSTALL) { 8823 if (chatty) 8824 Log.d(TAG, "Removing package " + ps.name); 8825 } 8826 8827 // writer 8828 synchronized (mPackages) { 8829 mPackages.remove(ps.name); 8830 final PackageParser.Package pkg = ps.pkg; 8831 if (pkg != null) { 8832 cleanPackageDataStructuresLILPw(pkg, chatty); 8833 } 8834 } 8835 } 8836 8837 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8838 if (DEBUG_INSTALL) { 8839 if (chatty) 8840 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8841 } 8842 8843 // writer 8844 synchronized (mPackages) { 8845 // Remove the parent package 8846 mPackages.remove(pkg.applicationInfo.packageName); 8847 cleanPackageDataStructuresLILPw(pkg, chatty); 8848 8849 // Remove the child packages 8850 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8851 for (int i = 0; i < childCount; i++) { 8852 PackageParser.Package childPkg = pkg.childPackages.get(i); 8853 mPackages.remove(childPkg.applicationInfo.packageName); 8854 cleanPackageDataStructuresLILPw(childPkg, chatty); 8855 } 8856 } 8857 } 8858 8859 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8860 int N = pkg.providers.size(); 8861 StringBuilder r = null; 8862 int i; 8863 for (i=0; i<N; i++) { 8864 PackageParser.Provider p = pkg.providers.get(i); 8865 mProviders.removeProvider(p); 8866 if (p.info.authority == null) { 8867 8868 /* There was another ContentProvider with this authority when 8869 * this app was installed so this authority is null, 8870 * Ignore it as we don't have to unregister the provider. 8871 */ 8872 continue; 8873 } 8874 String names[] = p.info.authority.split(";"); 8875 for (int j = 0; j < names.length; j++) { 8876 if (mProvidersByAuthority.get(names[j]) == p) { 8877 mProvidersByAuthority.remove(names[j]); 8878 if (DEBUG_REMOVE) { 8879 if (chatty) 8880 Log.d(TAG, "Unregistered content provider: " + names[j] 8881 + ", className = " + p.info.name + ", isSyncable = " 8882 + p.info.isSyncable); 8883 } 8884 } 8885 } 8886 if (DEBUG_REMOVE && chatty) { 8887 if (r == null) { 8888 r = new StringBuilder(256); 8889 } else { 8890 r.append(' '); 8891 } 8892 r.append(p.info.name); 8893 } 8894 } 8895 if (r != null) { 8896 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8897 } 8898 8899 N = pkg.services.size(); 8900 r = null; 8901 for (i=0; i<N; i++) { 8902 PackageParser.Service s = pkg.services.get(i); 8903 mServices.removeService(s); 8904 if (chatty) { 8905 if (r == null) { 8906 r = new StringBuilder(256); 8907 } else { 8908 r.append(' '); 8909 } 8910 r.append(s.info.name); 8911 } 8912 } 8913 if (r != null) { 8914 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8915 } 8916 8917 N = pkg.receivers.size(); 8918 r = null; 8919 for (i=0; i<N; i++) { 8920 PackageParser.Activity a = pkg.receivers.get(i); 8921 mReceivers.removeActivity(a, "receiver"); 8922 if (DEBUG_REMOVE && chatty) { 8923 if (r == null) { 8924 r = new StringBuilder(256); 8925 } else { 8926 r.append(' '); 8927 } 8928 r.append(a.info.name); 8929 } 8930 } 8931 if (r != null) { 8932 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8933 } 8934 8935 N = pkg.activities.size(); 8936 r = null; 8937 for (i=0; i<N; i++) { 8938 PackageParser.Activity a = pkg.activities.get(i); 8939 mActivities.removeActivity(a, "activity"); 8940 if (DEBUG_REMOVE && chatty) { 8941 if (r == null) { 8942 r = new StringBuilder(256); 8943 } else { 8944 r.append(' '); 8945 } 8946 r.append(a.info.name); 8947 } 8948 } 8949 if (r != null) { 8950 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8951 } 8952 8953 N = pkg.permissions.size(); 8954 r = null; 8955 for (i=0; i<N; i++) { 8956 PackageParser.Permission p = pkg.permissions.get(i); 8957 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8958 if (bp == null) { 8959 bp = mSettings.mPermissionTrees.get(p.info.name); 8960 } 8961 if (bp != null && bp.perm == p) { 8962 bp.perm = null; 8963 if (DEBUG_REMOVE && chatty) { 8964 if (r == null) { 8965 r = new StringBuilder(256); 8966 } else { 8967 r.append(' '); 8968 } 8969 r.append(p.info.name); 8970 } 8971 } 8972 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8973 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8974 if (appOpPkgs != null) { 8975 appOpPkgs.remove(pkg.packageName); 8976 } 8977 } 8978 } 8979 if (r != null) { 8980 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8981 } 8982 8983 N = pkg.requestedPermissions.size(); 8984 r = null; 8985 for (i=0; i<N; i++) { 8986 String perm = pkg.requestedPermissions.get(i); 8987 BasePermission bp = mSettings.mPermissions.get(perm); 8988 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8989 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8990 if (appOpPkgs != null) { 8991 appOpPkgs.remove(pkg.packageName); 8992 if (appOpPkgs.isEmpty()) { 8993 mAppOpPermissionPackages.remove(perm); 8994 } 8995 } 8996 } 8997 } 8998 if (r != null) { 8999 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9000 } 9001 9002 N = pkg.instrumentation.size(); 9003 r = null; 9004 for (i=0; i<N; i++) { 9005 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9006 mInstrumentation.remove(a.getComponentName()); 9007 if (DEBUG_REMOVE && chatty) { 9008 if (r == null) { 9009 r = new StringBuilder(256); 9010 } else { 9011 r.append(' '); 9012 } 9013 r.append(a.info.name); 9014 } 9015 } 9016 if (r != null) { 9017 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9018 } 9019 9020 r = null; 9021 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9022 // Only system apps can hold shared libraries. 9023 if (pkg.libraryNames != null) { 9024 for (i=0; i<pkg.libraryNames.size(); i++) { 9025 String name = pkg.libraryNames.get(i); 9026 SharedLibraryEntry cur = mSharedLibraries.get(name); 9027 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9028 mSharedLibraries.remove(name); 9029 if (DEBUG_REMOVE && chatty) { 9030 if (r == null) { 9031 r = new StringBuilder(256); 9032 } else { 9033 r.append(' '); 9034 } 9035 r.append(name); 9036 } 9037 } 9038 } 9039 } 9040 } 9041 if (r != null) { 9042 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9043 } 9044 } 9045 9046 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9047 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9048 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9049 return true; 9050 } 9051 } 9052 return false; 9053 } 9054 9055 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9056 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9057 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9058 9059 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9060 // Update the parent permissions 9061 updatePermissionsLPw(pkg.packageName, pkg, flags); 9062 // Update the child permissions 9063 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9064 for (int i = 0; i < childCount; i++) { 9065 PackageParser.Package childPkg = pkg.childPackages.get(i); 9066 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9067 } 9068 } 9069 9070 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9071 int flags) { 9072 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9073 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9074 } 9075 9076 private void updatePermissionsLPw(String changingPkg, 9077 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9078 // Make sure there are no dangling permission trees. 9079 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9080 while (it.hasNext()) { 9081 final BasePermission bp = it.next(); 9082 if (bp.packageSetting == null) { 9083 // We may not yet have parsed the package, so just see if 9084 // we still know about its settings. 9085 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9086 } 9087 if (bp.packageSetting == null) { 9088 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9089 + " from package " + bp.sourcePackage); 9090 it.remove(); 9091 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9092 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9093 Slog.i(TAG, "Removing old permission tree: " + bp.name 9094 + " from package " + bp.sourcePackage); 9095 flags |= UPDATE_PERMISSIONS_ALL; 9096 it.remove(); 9097 } 9098 } 9099 } 9100 9101 // Make sure all dynamic permissions have been assigned to a package, 9102 // and make sure there are no dangling permissions. 9103 it = mSettings.mPermissions.values().iterator(); 9104 while (it.hasNext()) { 9105 final BasePermission bp = it.next(); 9106 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9107 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9108 + bp.name + " pkg=" + bp.sourcePackage 9109 + " info=" + bp.pendingInfo); 9110 if (bp.packageSetting == null && bp.pendingInfo != null) { 9111 final BasePermission tree = findPermissionTreeLP(bp.name); 9112 if (tree != null && tree.perm != null) { 9113 bp.packageSetting = tree.packageSetting; 9114 bp.perm = new PackageParser.Permission(tree.perm.owner, 9115 new PermissionInfo(bp.pendingInfo)); 9116 bp.perm.info.packageName = tree.perm.info.packageName; 9117 bp.perm.info.name = bp.name; 9118 bp.uid = tree.uid; 9119 } 9120 } 9121 } 9122 if (bp.packageSetting == null) { 9123 // We may not yet have parsed the package, so just see if 9124 // we still know about its settings. 9125 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9126 } 9127 if (bp.packageSetting == null) { 9128 Slog.w(TAG, "Removing dangling permission: " + bp.name 9129 + " from package " + bp.sourcePackage); 9130 it.remove(); 9131 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9132 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9133 Slog.i(TAG, "Removing old permission: " + bp.name 9134 + " from package " + bp.sourcePackage); 9135 flags |= UPDATE_PERMISSIONS_ALL; 9136 it.remove(); 9137 } 9138 } 9139 } 9140 9141 // Now update the permissions for all packages, in particular 9142 // replace the granted permissions of the system packages. 9143 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9144 for (PackageParser.Package pkg : mPackages.values()) { 9145 if (pkg != pkgInfo) { 9146 // Only replace for packages on requested volume 9147 final String volumeUuid = getVolumeUuidForPackage(pkg); 9148 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9149 && Objects.equals(replaceVolumeUuid, volumeUuid); 9150 grantPermissionsLPw(pkg, replace, changingPkg); 9151 } 9152 } 9153 } 9154 9155 if (pkgInfo != null) { 9156 // Only replace for packages on requested volume 9157 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9158 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9159 && Objects.equals(replaceVolumeUuid, volumeUuid); 9160 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9161 } 9162 } 9163 9164 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9165 String packageOfInterest) { 9166 // IMPORTANT: There are two types of permissions: install and runtime. 9167 // Install time permissions are granted when the app is installed to 9168 // all device users and users added in the future. Runtime permissions 9169 // are granted at runtime explicitly to specific users. Normal and signature 9170 // protected permissions are install time permissions. Dangerous permissions 9171 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9172 // otherwise they are runtime permissions. This function does not manage 9173 // runtime permissions except for the case an app targeting Lollipop MR1 9174 // being upgraded to target a newer SDK, in which case dangerous permissions 9175 // are transformed from install time to runtime ones. 9176 9177 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9178 if (ps == null) { 9179 return; 9180 } 9181 9182 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9183 9184 PermissionsState permissionsState = ps.getPermissionsState(); 9185 PermissionsState origPermissions = permissionsState; 9186 9187 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9188 9189 boolean runtimePermissionsRevoked = false; 9190 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9191 9192 boolean changedInstallPermission = false; 9193 9194 if (replace) { 9195 ps.installPermissionsFixed = false; 9196 if (!ps.isSharedUser()) { 9197 origPermissions = new PermissionsState(permissionsState); 9198 permissionsState.reset(); 9199 } else { 9200 // We need to know only about runtime permission changes since the 9201 // calling code always writes the install permissions state but 9202 // the runtime ones are written only if changed. The only cases of 9203 // changed runtime permissions here are promotion of an install to 9204 // runtime and revocation of a runtime from a shared user. 9205 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9206 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9207 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9208 runtimePermissionsRevoked = true; 9209 } 9210 } 9211 } 9212 9213 permissionsState.setGlobalGids(mGlobalGids); 9214 9215 final int N = pkg.requestedPermissions.size(); 9216 for (int i=0; i<N; i++) { 9217 final String name = pkg.requestedPermissions.get(i); 9218 final BasePermission bp = mSettings.mPermissions.get(name); 9219 9220 if (DEBUG_INSTALL) { 9221 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9222 } 9223 9224 if (bp == null || bp.packageSetting == null) { 9225 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9226 Slog.w(TAG, "Unknown permission " + name 9227 + " in package " + pkg.packageName); 9228 } 9229 continue; 9230 } 9231 9232 final String perm = bp.name; 9233 boolean allowedSig = false; 9234 int grant = GRANT_DENIED; 9235 9236 // Keep track of app op permissions. 9237 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9238 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9239 if (pkgs == null) { 9240 pkgs = new ArraySet<>(); 9241 mAppOpPermissionPackages.put(bp.name, pkgs); 9242 } 9243 pkgs.add(pkg.packageName); 9244 } 9245 9246 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9247 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9248 >= Build.VERSION_CODES.M; 9249 switch (level) { 9250 case PermissionInfo.PROTECTION_NORMAL: { 9251 // For all apps normal permissions are install time ones. 9252 grant = GRANT_INSTALL; 9253 } break; 9254 9255 case PermissionInfo.PROTECTION_DANGEROUS: { 9256 // If a permission review is required for legacy apps we represent 9257 // their permissions as always granted runtime ones since we need 9258 // to keep the review required permission flag per user while an 9259 // install permission's state is shared across all users. 9260 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9261 // For legacy apps dangerous permissions are install time ones. 9262 grant = GRANT_INSTALL; 9263 } else if (origPermissions.hasInstallPermission(bp.name)) { 9264 // For legacy apps that became modern, install becomes runtime. 9265 grant = GRANT_UPGRADE; 9266 } else if (mPromoteSystemApps 9267 && isSystemApp(ps) 9268 && mExistingSystemPackages.contains(ps.name)) { 9269 // For legacy system apps, install becomes runtime. 9270 // We cannot check hasInstallPermission() for system apps since those 9271 // permissions were granted implicitly and not persisted pre-M. 9272 grant = GRANT_UPGRADE; 9273 } else { 9274 // For modern apps keep runtime permissions unchanged. 9275 grant = GRANT_RUNTIME; 9276 } 9277 } break; 9278 9279 case PermissionInfo.PROTECTION_SIGNATURE: { 9280 // For all apps signature permissions are install time ones. 9281 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9282 if (allowedSig) { 9283 grant = GRANT_INSTALL; 9284 } 9285 } break; 9286 } 9287 9288 if (DEBUG_INSTALL) { 9289 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9290 } 9291 9292 if (grant != GRANT_DENIED) { 9293 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9294 // If this is an existing, non-system package, then 9295 // we can't add any new permissions to it. 9296 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9297 // Except... if this is a permission that was added 9298 // to the platform (note: need to only do this when 9299 // updating the platform). 9300 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9301 grant = GRANT_DENIED; 9302 } 9303 } 9304 } 9305 9306 switch (grant) { 9307 case GRANT_INSTALL: { 9308 // Revoke this as runtime permission to handle the case of 9309 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9310 for (int userId : UserManagerService.getInstance().getUserIds()) { 9311 if (origPermissions.getRuntimePermissionState( 9312 bp.name, userId) != null) { 9313 // Revoke the runtime permission and clear the flags. 9314 origPermissions.revokeRuntimePermission(bp, userId); 9315 origPermissions.updatePermissionFlags(bp, userId, 9316 PackageManager.MASK_PERMISSION_FLAGS, 0); 9317 // If we revoked a permission permission, we have to write. 9318 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9319 changedRuntimePermissionUserIds, userId); 9320 } 9321 } 9322 // Grant an install permission. 9323 if (permissionsState.grantInstallPermission(bp) != 9324 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9325 changedInstallPermission = true; 9326 } 9327 } break; 9328 9329 case GRANT_RUNTIME: { 9330 // Grant previously granted runtime permissions. 9331 for (int userId : UserManagerService.getInstance().getUserIds()) { 9332 PermissionState permissionState = origPermissions 9333 .getRuntimePermissionState(bp.name, userId); 9334 int flags = permissionState != null 9335 ? permissionState.getFlags() : 0; 9336 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9337 if (permissionsState.grantRuntimePermission(bp, userId) == 9338 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9339 // If we cannot put the permission as it was, we have to write. 9340 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9341 changedRuntimePermissionUserIds, userId); 9342 } 9343 // If the app supports runtime permissions no need for a review. 9344 if (Build.PERMISSIONS_REVIEW_REQUIRED 9345 && appSupportsRuntimePermissions 9346 && (flags & PackageManager 9347 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9348 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9349 // Since we changed the flags, we have to write. 9350 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9351 changedRuntimePermissionUserIds, userId); 9352 } 9353 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9354 && !appSupportsRuntimePermissions) { 9355 // For legacy apps that need a permission review, every new 9356 // runtime permission is granted but it is pending a review. 9357 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9358 permissionsState.grantRuntimePermission(bp, userId); 9359 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9360 // We changed the permission and flags, hence have to write. 9361 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9362 changedRuntimePermissionUserIds, userId); 9363 } 9364 } 9365 // Propagate the permission flags. 9366 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9367 } 9368 } break; 9369 9370 case GRANT_UPGRADE: { 9371 // Grant runtime permissions for a previously held install permission. 9372 PermissionState permissionState = origPermissions 9373 .getInstallPermissionState(bp.name); 9374 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9375 9376 if (origPermissions.revokeInstallPermission(bp) 9377 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9378 // We will be transferring the permission flags, so clear them. 9379 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9380 PackageManager.MASK_PERMISSION_FLAGS, 0); 9381 changedInstallPermission = true; 9382 } 9383 9384 // If the permission is not to be promoted to runtime we ignore it and 9385 // also its other flags as they are not applicable to install permissions. 9386 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9387 for (int userId : currentUserIds) { 9388 if (permissionsState.grantRuntimePermission(bp, userId) != 9389 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9390 // Transfer the permission flags. 9391 permissionsState.updatePermissionFlags(bp, userId, 9392 flags, flags); 9393 // If we granted the permission, we have to write. 9394 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9395 changedRuntimePermissionUserIds, userId); 9396 } 9397 } 9398 } 9399 } break; 9400 9401 default: { 9402 if (packageOfInterest == null 9403 || packageOfInterest.equals(pkg.packageName)) { 9404 Slog.w(TAG, "Not granting permission " + perm 9405 + " to package " + pkg.packageName 9406 + " because it was previously installed without"); 9407 } 9408 } break; 9409 } 9410 } else { 9411 if (permissionsState.revokeInstallPermission(bp) != 9412 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9413 // Also drop the permission flags. 9414 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9415 PackageManager.MASK_PERMISSION_FLAGS, 0); 9416 changedInstallPermission = true; 9417 Slog.i(TAG, "Un-granting permission " + perm 9418 + " from package " + pkg.packageName 9419 + " (protectionLevel=" + bp.protectionLevel 9420 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9421 + ")"); 9422 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9423 // Don't print warning for app op permissions, since it is fine for them 9424 // not to be granted, there is a UI for the user to decide. 9425 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9426 Slog.w(TAG, "Not granting permission " + perm 9427 + " to package " + pkg.packageName 9428 + " (protectionLevel=" + bp.protectionLevel 9429 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9430 + ")"); 9431 } 9432 } 9433 } 9434 } 9435 9436 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9437 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9438 // This is the first that we have heard about this package, so the 9439 // permissions we have now selected are fixed until explicitly 9440 // changed. 9441 ps.installPermissionsFixed = true; 9442 } 9443 9444 // Persist the runtime permissions state for users with changes. If permissions 9445 // were revoked because no app in the shared user declares them we have to 9446 // write synchronously to avoid losing runtime permissions state. 9447 for (int userId : changedRuntimePermissionUserIds) { 9448 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9449 } 9450 9451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9452 } 9453 9454 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9455 boolean allowed = false; 9456 final int NP = PackageParser.NEW_PERMISSIONS.length; 9457 for (int ip=0; ip<NP; ip++) { 9458 final PackageParser.NewPermissionInfo npi 9459 = PackageParser.NEW_PERMISSIONS[ip]; 9460 if (npi.name.equals(perm) 9461 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9462 allowed = true; 9463 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9464 + pkg.packageName); 9465 break; 9466 } 9467 } 9468 return allowed; 9469 } 9470 9471 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9472 BasePermission bp, PermissionsState origPermissions) { 9473 boolean allowed; 9474 allowed = (compareSignatures( 9475 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9476 == PackageManager.SIGNATURE_MATCH) 9477 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9478 == PackageManager.SIGNATURE_MATCH); 9479 if (!allowed && (bp.protectionLevel 9480 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9481 if (isSystemApp(pkg)) { 9482 // For updated system applications, a system permission 9483 // is granted only if it had been defined by the original application. 9484 if (pkg.isUpdatedSystemApp()) { 9485 final PackageSetting sysPs = mSettings 9486 .getDisabledSystemPkgLPr(pkg.packageName); 9487 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9488 // If the original was granted this permission, we take 9489 // that grant decision as read and propagate it to the 9490 // update. 9491 if (sysPs.isPrivileged()) { 9492 allowed = true; 9493 } 9494 } else { 9495 // The system apk may have been updated with an older 9496 // version of the one on the data partition, but which 9497 // granted a new system permission that it didn't have 9498 // before. In this case we do want to allow the app to 9499 // now get the new permission if the ancestral apk is 9500 // privileged to get it. 9501 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9502 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9503 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9504 allowed = true; 9505 break; 9506 } 9507 } 9508 } 9509 // Also if a privileged parent package on the system image or any of 9510 // its children requested a privileged permission, the updated child 9511 // packages can also get the permission. 9512 if (pkg.parentPackage != null) { 9513 final PackageSetting disabledSysParentPs = mSettings 9514 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9515 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9516 && disabledSysParentPs.isPrivileged()) { 9517 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9518 allowed = true; 9519 } else if (disabledSysParentPs.pkg.childPackages != null) { 9520 final int count = disabledSysParentPs.pkg.childPackages.size(); 9521 for (int i = 0; i < count; i++) { 9522 PackageParser.Package disabledSysChildPkg = 9523 disabledSysParentPs.pkg.childPackages.get(i); 9524 if (isPackageRequestingPermission(disabledSysChildPkg, 9525 perm)) { 9526 allowed = true; 9527 break; 9528 } 9529 } 9530 } 9531 } 9532 } 9533 } 9534 } else { 9535 allowed = isPrivilegedApp(pkg); 9536 } 9537 } 9538 } 9539 if (!allowed) { 9540 if (!allowed && (bp.protectionLevel 9541 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9542 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9543 // If this was a previously normal/dangerous permission that got moved 9544 // to a system permission as part of the runtime permission redesign, then 9545 // we still want to blindly grant it to old apps. 9546 allowed = true; 9547 } 9548 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9549 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9550 // If this permission is to be granted to the system installer and 9551 // this app is an installer, then it gets the permission. 9552 allowed = true; 9553 } 9554 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9555 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9556 // If this permission is to be granted to the system verifier and 9557 // this app is a verifier, then it gets the permission. 9558 allowed = true; 9559 } 9560 if (!allowed && (bp.protectionLevel 9561 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9562 && isSystemApp(pkg)) { 9563 // Any pre-installed system app is allowed to get this permission. 9564 allowed = true; 9565 } 9566 if (!allowed && (bp.protectionLevel 9567 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9568 // For development permissions, a development permission 9569 // is granted only if it was already granted. 9570 allowed = origPermissions.hasInstallPermission(perm); 9571 } 9572 } 9573 return allowed; 9574 } 9575 9576 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9577 final int permCount = pkg.requestedPermissions.size(); 9578 for (int j = 0; j < permCount; j++) { 9579 String requestedPermission = pkg.requestedPermissions.get(j); 9580 if (permission.equals(requestedPermission)) { 9581 return true; 9582 } 9583 } 9584 return false; 9585 } 9586 9587 final class ActivityIntentResolver 9588 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9589 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9590 boolean defaultOnly, int userId) { 9591 if (!sUserManager.exists(userId)) return null; 9592 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9593 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9594 } 9595 9596 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9597 int userId) { 9598 if (!sUserManager.exists(userId)) return null; 9599 mFlags = flags; 9600 return super.queryIntent(intent, resolvedType, 9601 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9602 } 9603 9604 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9605 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9606 if (!sUserManager.exists(userId)) return null; 9607 if (packageActivities == null) { 9608 return null; 9609 } 9610 mFlags = flags; 9611 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9612 final int N = packageActivities.size(); 9613 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9614 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9615 9616 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9617 for (int i = 0; i < N; ++i) { 9618 intentFilters = packageActivities.get(i).intents; 9619 if (intentFilters != null && intentFilters.size() > 0) { 9620 PackageParser.ActivityIntentInfo[] array = 9621 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9622 intentFilters.toArray(array); 9623 listCut.add(array); 9624 } 9625 } 9626 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9627 } 9628 9629 public final void addActivity(PackageParser.Activity a, String type) { 9630 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9631 mActivities.put(a.getComponentName(), a); 9632 if (DEBUG_SHOW_INFO) 9633 Log.v( 9634 TAG, " " + type + " " + 9635 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9636 if (DEBUG_SHOW_INFO) 9637 Log.v(TAG, " Class=" + a.info.name); 9638 final int NI = a.intents.size(); 9639 for (int j=0; j<NI; j++) { 9640 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9641 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9642 intent.setPriority(0); 9643 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9644 + a.className + " with priority > 0, forcing to 0"); 9645 } 9646 if (DEBUG_SHOW_INFO) { 9647 Log.v(TAG, " IntentFilter:"); 9648 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9649 } 9650 if (!intent.debugCheck()) { 9651 Log.w(TAG, "==> For Activity " + a.info.name); 9652 } 9653 addFilter(intent); 9654 } 9655 } 9656 9657 public final void removeActivity(PackageParser.Activity a, String type) { 9658 mActivities.remove(a.getComponentName()); 9659 if (DEBUG_SHOW_INFO) { 9660 Log.v(TAG, " " + type + " " 9661 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9662 : a.info.name) + ":"); 9663 Log.v(TAG, " Class=" + a.info.name); 9664 } 9665 final int NI = a.intents.size(); 9666 for (int j=0; j<NI; j++) { 9667 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9668 if (DEBUG_SHOW_INFO) { 9669 Log.v(TAG, " IntentFilter:"); 9670 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9671 } 9672 removeFilter(intent); 9673 } 9674 } 9675 9676 @Override 9677 protected boolean allowFilterResult( 9678 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9679 ActivityInfo filterAi = filter.activity.info; 9680 for (int i=dest.size()-1; i>=0; i--) { 9681 ActivityInfo destAi = dest.get(i).activityInfo; 9682 if (destAi.name == filterAi.name 9683 && destAi.packageName == filterAi.packageName) { 9684 return false; 9685 } 9686 } 9687 return true; 9688 } 9689 9690 @Override 9691 protected ActivityIntentInfo[] newArray(int size) { 9692 return new ActivityIntentInfo[size]; 9693 } 9694 9695 @Override 9696 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9697 if (!sUserManager.exists(userId)) return true; 9698 PackageParser.Package p = filter.activity.owner; 9699 if (p != null) { 9700 PackageSetting ps = (PackageSetting)p.mExtras; 9701 if (ps != null) { 9702 // System apps are never considered stopped for purposes of 9703 // filtering, because there may be no way for the user to 9704 // actually re-launch them. 9705 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9706 && ps.getStopped(userId); 9707 } 9708 } 9709 return false; 9710 } 9711 9712 @Override 9713 protected boolean isPackageForFilter(String packageName, 9714 PackageParser.ActivityIntentInfo info) { 9715 return packageName.equals(info.activity.owner.packageName); 9716 } 9717 9718 @Override 9719 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9720 int match, int userId) { 9721 if (!sUserManager.exists(userId)) return null; 9722 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9723 return null; 9724 } 9725 final PackageParser.Activity activity = info.activity; 9726 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9727 if (ps == null) { 9728 return null; 9729 } 9730 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9731 ps.readUserState(userId), userId); 9732 if (ai == null) { 9733 return null; 9734 } 9735 final ResolveInfo res = new ResolveInfo(); 9736 res.activityInfo = ai; 9737 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9738 res.filter = info; 9739 } 9740 if (info != null) { 9741 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9742 } 9743 res.priority = info.getPriority(); 9744 res.preferredOrder = activity.owner.mPreferredOrder; 9745 //System.out.println("Result: " + res.activityInfo.className + 9746 // " = " + res.priority); 9747 res.match = match; 9748 res.isDefault = info.hasDefault; 9749 res.labelRes = info.labelRes; 9750 res.nonLocalizedLabel = info.nonLocalizedLabel; 9751 if (userNeedsBadging(userId)) { 9752 res.noResourceId = true; 9753 } else { 9754 res.icon = info.icon; 9755 } 9756 res.iconResourceId = info.icon; 9757 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9758 return res; 9759 } 9760 9761 @Override 9762 protected void sortResults(List<ResolveInfo> results) { 9763 Collections.sort(results, mResolvePrioritySorter); 9764 } 9765 9766 @Override 9767 protected void dumpFilter(PrintWriter out, String prefix, 9768 PackageParser.ActivityIntentInfo filter) { 9769 out.print(prefix); out.print( 9770 Integer.toHexString(System.identityHashCode(filter.activity))); 9771 out.print(' '); 9772 filter.activity.printComponentShortName(out); 9773 out.print(" filter "); 9774 out.println(Integer.toHexString(System.identityHashCode(filter))); 9775 } 9776 9777 @Override 9778 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9779 return filter.activity; 9780 } 9781 9782 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9783 PackageParser.Activity activity = (PackageParser.Activity)label; 9784 out.print(prefix); out.print( 9785 Integer.toHexString(System.identityHashCode(activity))); 9786 out.print(' '); 9787 activity.printComponentShortName(out); 9788 if (count > 1) { 9789 out.print(" ("); out.print(count); out.print(" filters)"); 9790 } 9791 out.println(); 9792 } 9793 9794// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9795// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9796// final List<ResolveInfo> retList = Lists.newArrayList(); 9797// while (i.hasNext()) { 9798// final ResolveInfo resolveInfo = i.next(); 9799// if (isEnabledLP(resolveInfo.activityInfo)) { 9800// retList.add(resolveInfo); 9801// } 9802// } 9803// return retList; 9804// } 9805 9806 // Keys are String (activity class name), values are Activity. 9807 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9808 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9809 private int mFlags; 9810 } 9811 9812 private final class ServiceIntentResolver 9813 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9815 boolean defaultOnly, int userId) { 9816 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9817 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9818 } 9819 9820 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9821 int userId) { 9822 if (!sUserManager.exists(userId)) return null; 9823 mFlags = flags; 9824 return super.queryIntent(intent, resolvedType, 9825 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9826 } 9827 9828 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9829 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9830 if (!sUserManager.exists(userId)) return null; 9831 if (packageServices == null) { 9832 return null; 9833 } 9834 mFlags = flags; 9835 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9836 final int N = packageServices.size(); 9837 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9838 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9839 9840 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9841 for (int i = 0; i < N; ++i) { 9842 intentFilters = packageServices.get(i).intents; 9843 if (intentFilters != null && intentFilters.size() > 0) { 9844 PackageParser.ServiceIntentInfo[] array = 9845 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9846 intentFilters.toArray(array); 9847 listCut.add(array); 9848 } 9849 } 9850 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9851 } 9852 9853 public final void addService(PackageParser.Service s) { 9854 mServices.put(s.getComponentName(), s); 9855 if (DEBUG_SHOW_INFO) { 9856 Log.v(TAG, " " 9857 + (s.info.nonLocalizedLabel != null 9858 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9859 Log.v(TAG, " Class=" + s.info.name); 9860 } 9861 final int NI = s.intents.size(); 9862 int j; 9863 for (j=0; j<NI; j++) { 9864 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9865 if (DEBUG_SHOW_INFO) { 9866 Log.v(TAG, " IntentFilter:"); 9867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9868 } 9869 if (!intent.debugCheck()) { 9870 Log.w(TAG, "==> For Service " + s.info.name); 9871 } 9872 addFilter(intent); 9873 } 9874 } 9875 9876 public final void removeService(PackageParser.Service s) { 9877 mServices.remove(s.getComponentName()); 9878 if (DEBUG_SHOW_INFO) { 9879 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9880 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9881 Log.v(TAG, " Class=" + s.info.name); 9882 } 9883 final int NI = s.intents.size(); 9884 int j; 9885 for (j=0; j<NI; j++) { 9886 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9887 if (DEBUG_SHOW_INFO) { 9888 Log.v(TAG, " IntentFilter:"); 9889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9890 } 9891 removeFilter(intent); 9892 } 9893 } 9894 9895 @Override 9896 protected boolean allowFilterResult( 9897 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9898 ServiceInfo filterSi = filter.service.info; 9899 for (int i=dest.size()-1; i>=0; i--) { 9900 ServiceInfo destAi = dest.get(i).serviceInfo; 9901 if (destAi.name == filterSi.name 9902 && destAi.packageName == filterSi.packageName) { 9903 return false; 9904 } 9905 } 9906 return true; 9907 } 9908 9909 @Override 9910 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9911 return new PackageParser.ServiceIntentInfo[size]; 9912 } 9913 9914 @Override 9915 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9916 if (!sUserManager.exists(userId)) return true; 9917 PackageParser.Package p = filter.service.owner; 9918 if (p != null) { 9919 PackageSetting ps = (PackageSetting)p.mExtras; 9920 if (ps != null) { 9921 // System apps are never considered stopped for purposes of 9922 // filtering, because there may be no way for the user to 9923 // actually re-launch them. 9924 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9925 && ps.getStopped(userId); 9926 } 9927 } 9928 return false; 9929 } 9930 9931 @Override 9932 protected boolean isPackageForFilter(String packageName, 9933 PackageParser.ServiceIntentInfo info) { 9934 return packageName.equals(info.service.owner.packageName); 9935 } 9936 9937 @Override 9938 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9939 int match, int userId) { 9940 if (!sUserManager.exists(userId)) return null; 9941 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9942 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9943 return null; 9944 } 9945 final PackageParser.Service service = info.service; 9946 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9947 if (ps == null) { 9948 return null; 9949 } 9950 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9951 ps.readUserState(userId), userId); 9952 if (si == null) { 9953 return null; 9954 } 9955 final ResolveInfo res = new ResolveInfo(); 9956 res.serviceInfo = si; 9957 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9958 res.filter = filter; 9959 } 9960 res.priority = info.getPriority(); 9961 res.preferredOrder = service.owner.mPreferredOrder; 9962 res.match = match; 9963 res.isDefault = info.hasDefault; 9964 res.labelRes = info.labelRes; 9965 res.nonLocalizedLabel = info.nonLocalizedLabel; 9966 res.icon = info.icon; 9967 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9968 return res; 9969 } 9970 9971 @Override 9972 protected void sortResults(List<ResolveInfo> results) { 9973 Collections.sort(results, mResolvePrioritySorter); 9974 } 9975 9976 @Override 9977 protected void dumpFilter(PrintWriter out, String prefix, 9978 PackageParser.ServiceIntentInfo filter) { 9979 out.print(prefix); out.print( 9980 Integer.toHexString(System.identityHashCode(filter.service))); 9981 out.print(' '); 9982 filter.service.printComponentShortName(out); 9983 out.print(" filter "); 9984 out.println(Integer.toHexString(System.identityHashCode(filter))); 9985 } 9986 9987 @Override 9988 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9989 return filter.service; 9990 } 9991 9992 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9993 PackageParser.Service service = (PackageParser.Service)label; 9994 out.print(prefix); out.print( 9995 Integer.toHexString(System.identityHashCode(service))); 9996 out.print(' '); 9997 service.printComponentShortName(out); 9998 if (count > 1) { 9999 out.print(" ("); out.print(count); out.print(" filters)"); 10000 } 10001 out.println(); 10002 } 10003 10004// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10005// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10006// final List<ResolveInfo> retList = Lists.newArrayList(); 10007// while (i.hasNext()) { 10008// final ResolveInfo resolveInfo = (ResolveInfo) i; 10009// if (isEnabledLP(resolveInfo.serviceInfo)) { 10010// retList.add(resolveInfo); 10011// } 10012// } 10013// return retList; 10014// } 10015 10016 // Keys are String (activity class name), values are Activity. 10017 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10018 = new ArrayMap<ComponentName, PackageParser.Service>(); 10019 private int mFlags; 10020 }; 10021 10022 private final class ProviderIntentResolver 10023 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10024 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10025 boolean defaultOnly, int userId) { 10026 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10027 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10028 } 10029 10030 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10031 int userId) { 10032 if (!sUserManager.exists(userId)) 10033 return null; 10034 mFlags = flags; 10035 return super.queryIntent(intent, resolvedType, 10036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10037 } 10038 10039 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10040 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10041 if (!sUserManager.exists(userId)) 10042 return null; 10043 if (packageProviders == null) { 10044 return null; 10045 } 10046 mFlags = flags; 10047 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10048 final int N = packageProviders.size(); 10049 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10050 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10051 10052 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10053 for (int i = 0; i < N; ++i) { 10054 intentFilters = packageProviders.get(i).intents; 10055 if (intentFilters != null && intentFilters.size() > 0) { 10056 PackageParser.ProviderIntentInfo[] array = 10057 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10058 intentFilters.toArray(array); 10059 listCut.add(array); 10060 } 10061 } 10062 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10063 } 10064 10065 public final void addProvider(PackageParser.Provider p) { 10066 if (mProviders.containsKey(p.getComponentName())) { 10067 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10068 return; 10069 } 10070 10071 mProviders.put(p.getComponentName(), p); 10072 if (DEBUG_SHOW_INFO) { 10073 Log.v(TAG, " " 10074 + (p.info.nonLocalizedLabel != null 10075 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10076 Log.v(TAG, " Class=" + p.info.name); 10077 } 10078 final int NI = p.intents.size(); 10079 int j; 10080 for (j = 0; j < NI; j++) { 10081 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10082 if (DEBUG_SHOW_INFO) { 10083 Log.v(TAG, " IntentFilter:"); 10084 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10085 } 10086 if (!intent.debugCheck()) { 10087 Log.w(TAG, "==> For Provider " + p.info.name); 10088 } 10089 addFilter(intent); 10090 } 10091 } 10092 10093 public final void removeProvider(PackageParser.Provider p) { 10094 mProviders.remove(p.getComponentName()); 10095 if (DEBUG_SHOW_INFO) { 10096 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10097 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10098 Log.v(TAG, " Class=" + p.info.name); 10099 } 10100 final int NI = p.intents.size(); 10101 int j; 10102 for (j = 0; j < NI; j++) { 10103 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10104 if (DEBUG_SHOW_INFO) { 10105 Log.v(TAG, " IntentFilter:"); 10106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10107 } 10108 removeFilter(intent); 10109 } 10110 } 10111 10112 @Override 10113 protected boolean allowFilterResult( 10114 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10115 ProviderInfo filterPi = filter.provider.info; 10116 for (int i = dest.size() - 1; i >= 0; i--) { 10117 ProviderInfo destPi = dest.get(i).providerInfo; 10118 if (destPi.name == filterPi.name 10119 && destPi.packageName == filterPi.packageName) { 10120 return false; 10121 } 10122 } 10123 return true; 10124 } 10125 10126 @Override 10127 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10128 return new PackageParser.ProviderIntentInfo[size]; 10129 } 10130 10131 @Override 10132 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10133 if (!sUserManager.exists(userId)) 10134 return true; 10135 PackageParser.Package p = filter.provider.owner; 10136 if (p != null) { 10137 PackageSetting ps = (PackageSetting) p.mExtras; 10138 if (ps != null) { 10139 // System apps are never considered stopped for purposes of 10140 // filtering, because there may be no way for the user to 10141 // actually re-launch them. 10142 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10143 && ps.getStopped(userId); 10144 } 10145 } 10146 return false; 10147 } 10148 10149 @Override 10150 protected boolean isPackageForFilter(String packageName, 10151 PackageParser.ProviderIntentInfo info) { 10152 return packageName.equals(info.provider.owner.packageName); 10153 } 10154 10155 @Override 10156 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10157 int match, int userId) { 10158 if (!sUserManager.exists(userId)) 10159 return null; 10160 final PackageParser.ProviderIntentInfo info = filter; 10161 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10162 return null; 10163 } 10164 final PackageParser.Provider provider = info.provider; 10165 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10166 if (ps == null) { 10167 return null; 10168 } 10169 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10170 ps.readUserState(userId), userId); 10171 if (pi == null) { 10172 return null; 10173 } 10174 final ResolveInfo res = new ResolveInfo(); 10175 res.providerInfo = pi; 10176 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10177 res.filter = filter; 10178 } 10179 res.priority = info.getPriority(); 10180 res.preferredOrder = provider.owner.mPreferredOrder; 10181 res.match = match; 10182 res.isDefault = info.hasDefault; 10183 res.labelRes = info.labelRes; 10184 res.nonLocalizedLabel = info.nonLocalizedLabel; 10185 res.icon = info.icon; 10186 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10187 return res; 10188 } 10189 10190 @Override 10191 protected void sortResults(List<ResolveInfo> results) { 10192 Collections.sort(results, mResolvePrioritySorter); 10193 } 10194 10195 @Override 10196 protected void dumpFilter(PrintWriter out, String prefix, 10197 PackageParser.ProviderIntentInfo filter) { 10198 out.print(prefix); 10199 out.print( 10200 Integer.toHexString(System.identityHashCode(filter.provider))); 10201 out.print(' '); 10202 filter.provider.printComponentShortName(out); 10203 out.print(" filter "); 10204 out.println(Integer.toHexString(System.identityHashCode(filter))); 10205 } 10206 10207 @Override 10208 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10209 return filter.provider; 10210 } 10211 10212 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10213 PackageParser.Provider provider = (PackageParser.Provider)label; 10214 out.print(prefix); out.print( 10215 Integer.toHexString(System.identityHashCode(provider))); 10216 out.print(' '); 10217 provider.printComponentShortName(out); 10218 if (count > 1) { 10219 out.print(" ("); out.print(count); out.print(" filters)"); 10220 } 10221 out.println(); 10222 } 10223 10224 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10225 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10226 private int mFlags; 10227 } 10228 10229 private static final class EphemeralIntentResolver 10230 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10231 @Override 10232 protected EphemeralResolveIntentInfo[] newArray(int size) { 10233 return new EphemeralResolveIntentInfo[size]; 10234 } 10235 10236 @Override 10237 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10238 return true; 10239 } 10240 10241 @Override 10242 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10243 int userId) { 10244 if (!sUserManager.exists(userId)) { 10245 return null; 10246 } 10247 return info.getEphemeralResolveInfo(); 10248 } 10249 } 10250 10251 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10252 new Comparator<ResolveInfo>() { 10253 public int compare(ResolveInfo r1, ResolveInfo r2) { 10254 int v1 = r1.priority; 10255 int v2 = r2.priority; 10256 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10257 if (v1 != v2) { 10258 return (v1 > v2) ? -1 : 1; 10259 } 10260 v1 = r1.preferredOrder; 10261 v2 = r2.preferredOrder; 10262 if (v1 != v2) { 10263 return (v1 > v2) ? -1 : 1; 10264 } 10265 if (r1.isDefault != r2.isDefault) { 10266 return r1.isDefault ? -1 : 1; 10267 } 10268 v1 = r1.match; 10269 v2 = r2.match; 10270 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10271 if (v1 != v2) { 10272 return (v1 > v2) ? -1 : 1; 10273 } 10274 if (r1.system != r2.system) { 10275 return r1.system ? -1 : 1; 10276 } 10277 if (r1.activityInfo != null) { 10278 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10279 } 10280 if (r1.serviceInfo != null) { 10281 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10282 } 10283 if (r1.providerInfo != null) { 10284 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10285 } 10286 return 0; 10287 } 10288 }; 10289 10290 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10291 new Comparator<ProviderInfo>() { 10292 public int compare(ProviderInfo p1, ProviderInfo p2) { 10293 final int v1 = p1.initOrder; 10294 final int v2 = p2.initOrder; 10295 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10296 } 10297 }; 10298 10299 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10300 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10301 final int[] userIds) { 10302 mHandler.post(new Runnable() { 10303 @Override 10304 public void run() { 10305 try { 10306 final IActivityManager am = ActivityManagerNative.getDefault(); 10307 if (am == null) return; 10308 final int[] resolvedUserIds; 10309 if (userIds == null) { 10310 resolvedUserIds = am.getRunningUserIds(); 10311 } else { 10312 resolvedUserIds = userIds; 10313 } 10314 for (int id : resolvedUserIds) { 10315 final Intent intent = new Intent(action, 10316 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10317 if (extras != null) { 10318 intent.putExtras(extras); 10319 } 10320 if (targetPkg != null) { 10321 intent.setPackage(targetPkg); 10322 } 10323 // Modify the UID when posting to other users 10324 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10325 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10326 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10327 intent.putExtra(Intent.EXTRA_UID, uid); 10328 } 10329 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10330 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10331 if (DEBUG_BROADCASTS) { 10332 RuntimeException here = new RuntimeException("here"); 10333 here.fillInStackTrace(); 10334 Slog.d(TAG, "Sending to user " + id + ": " 10335 + intent.toShortString(false, true, false, false) 10336 + " " + intent.getExtras(), here); 10337 } 10338 am.broadcastIntent(null, intent, null, finishedReceiver, 10339 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10340 null, finishedReceiver != null, false, id); 10341 } 10342 } catch (RemoteException ex) { 10343 } 10344 } 10345 }); 10346 } 10347 10348 /** 10349 * Check if the external storage media is available. This is true if there 10350 * is a mounted external storage medium or if the external storage is 10351 * emulated. 10352 */ 10353 private boolean isExternalMediaAvailable() { 10354 return mMediaMounted || Environment.isExternalStorageEmulated(); 10355 } 10356 10357 @Override 10358 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10359 // writer 10360 synchronized (mPackages) { 10361 if (!isExternalMediaAvailable()) { 10362 // If the external storage is no longer mounted at this point, 10363 // the caller may not have been able to delete all of this 10364 // packages files and can not delete any more. Bail. 10365 return null; 10366 } 10367 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10368 if (lastPackage != null) { 10369 pkgs.remove(lastPackage); 10370 } 10371 if (pkgs.size() > 0) { 10372 return pkgs.get(0); 10373 } 10374 } 10375 return null; 10376 } 10377 10378 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10379 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10380 userId, andCode ? 1 : 0, packageName); 10381 if (mSystemReady) { 10382 msg.sendToTarget(); 10383 } else { 10384 if (mPostSystemReadyMessages == null) { 10385 mPostSystemReadyMessages = new ArrayList<>(); 10386 } 10387 mPostSystemReadyMessages.add(msg); 10388 } 10389 } 10390 10391 void startCleaningPackages() { 10392 // reader 10393 synchronized (mPackages) { 10394 if (!isExternalMediaAvailable()) { 10395 return; 10396 } 10397 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10398 return; 10399 } 10400 } 10401 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10402 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10403 IActivityManager am = ActivityManagerNative.getDefault(); 10404 if (am != null) { 10405 try { 10406 am.startService(null, intent, null, mContext.getOpPackageName(), 10407 UserHandle.USER_SYSTEM); 10408 } catch (RemoteException e) { 10409 } 10410 } 10411 } 10412 10413 @Override 10414 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10415 int installFlags, String installerPackageName, int userId) { 10416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10417 10418 final int callingUid = Binder.getCallingUid(); 10419 enforceCrossUserPermission(callingUid, userId, 10420 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10421 10422 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10423 try { 10424 if (observer != null) { 10425 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10426 } 10427 } catch (RemoteException re) { 10428 } 10429 return; 10430 } 10431 10432 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10433 installFlags |= PackageManager.INSTALL_FROM_ADB; 10434 10435 } else { 10436 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10437 // about installerPackageName. 10438 10439 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10440 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10441 } 10442 10443 UserHandle user; 10444 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10445 user = UserHandle.ALL; 10446 } else { 10447 user = new UserHandle(userId); 10448 } 10449 10450 // Only system components can circumvent runtime permissions when installing. 10451 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10452 && mContext.checkCallingOrSelfPermission(Manifest.permission 10453 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10454 throw new SecurityException("You need the " 10455 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10456 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10457 } 10458 10459 final File originFile = new File(originPath); 10460 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10461 10462 final Message msg = mHandler.obtainMessage(INIT_COPY); 10463 final VerificationInfo verificationInfo = new VerificationInfo( 10464 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10465 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10466 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10467 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10468 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10469 msg.obj = params; 10470 10471 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10472 System.identityHashCode(msg.obj)); 10473 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10474 System.identityHashCode(msg.obj)); 10475 10476 mHandler.sendMessage(msg); 10477 } 10478 10479 void installStage(String packageName, File stagedDir, String stagedCid, 10480 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10481 String installerPackageName, int installerUid, UserHandle user) { 10482 if (DEBUG_EPHEMERAL) { 10483 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10484 Slog.d(TAG, "Ephemeral install of " + packageName); 10485 } 10486 } 10487 final VerificationInfo verificationInfo = new VerificationInfo( 10488 sessionParams.originatingUri, sessionParams.referrerUri, 10489 sessionParams.originatingUid, installerUid); 10490 10491 final OriginInfo origin; 10492 if (stagedDir != null) { 10493 origin = OriginInfo.fromStagedFile(stagedDir); 10494 } else { 10495 origin = OriginInfo.fromStagedContainer(stagedCid); 10496 } 10497 10498 final Message msg = mHandler.obtainMessage(INIT_COPY); 10499 final InstallParams params = new InstallParams(origin, null, observer, 10500 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10501 verificationInfo, user, sessionParams.abiOverride, 10502 sessionParams.grantedRuntimePermissions); 10503 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10504 msg.obj = params; 10505 10506 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10507 System.identityHashCode(msg.obj)); 10508 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10509 System.identityHashCode(msg.obj)); 10510 10511 mHandler.sendMessage(msg); 10512 } 10513 10514 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10515 int userId) { 10516 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10517 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10518 } 10519 10520 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10521 int appId, int userId) { 10522 Bundle extras = new Bundle(1); 10523 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10524 10525 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10526 packageName, extras, 0, null, null, new int[] {userId}); 10527 try { 10528 IActivityManager am = ActivityManagerNative.getDefault(); 10529 if (isSystem && am.isUserRunning(userId, 0)) { 10530 // The just-installed/enabled app is bundled on the system, so presumed 10531 // to be able to run automatically without needing an explicit launch. 10532 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10533 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10534 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10535 .setPackage(packageName); 10536 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10537 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10538 } 10539 } catch (RemoteException e) { 10540 // shouldn't happen 10541 Slog.w(TAG, "Unable to bootstrap installed package", e); 10542 } 10543 } 10544 10545 @Override 10546 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10547 int userId) { 10548 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10549 PackageSetting pkgSetting; 10550 final int uid = Binder.getCallingUid(); 10551 enforceCrossUserPermission(uid, userId, 10552 true /* requireFullPermission */, true /* checkShell */, 10553 "setApplicationHiddenSetting for user " + userId); 10554 10555 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10556 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10557 return false; 10558 } 10559 10560 long callingId = Binder.clearCallingIdentity(); 10561 try { 10562 boolean sendAdded = false; 10563 boolean sendRemoved = false; 10564 // writer 10565 synchronized (mPackages) { 10566 pkgSetting = mSettings.mPackages.get(packageName); 10567 if (pkgSetting == null) { 10568 return false; 10569 } 10570 if (pkgSetting.getHidden(userId) != hidden) { 10571 pkgSetting.setHidden(hidden, userId); 10572 mSettings.writePackageRestrictionsLPr(userId); 10573 if (hidden) { 10574 sendRemoved = true; 10575 } else { 10576 sendAdded = true; 10577 } 10578 } 10579 } 10580 if (sendAdded) { 10581 sendPackageAddedForUser(packageName, pkgSetting, userId); 10582 return true; 10583 } 10584 if (sendRemoved) { 10585 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10586 "hiding pkg"); 10587 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10588 return true; 10589 } 10590 } finally { 10591 Binder.restoreCallingIdentity(callingId); 10592 } 10593 return false; 10594 } 10595 10596 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10597 int userId) { 10598 final PackageRemovedInfo info = new PackageRemovedInfo(); 10599 info.removedPackage = packageName; 10600 info.removedUsers = new int[] {userId}; 10601 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10602 info.sendPackageRemovedBroadcasts(); 10603 } 10604 10605 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10606 if (pkgList.length > 0) { 10607 Bundle extras = new Bundle(1); 10608 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10609 10610 sendPackageBroadcast( 10611 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10612 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10613 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10614 new int[] {userId}); 10615 } 10616 } 10617 10618 /** 10619 * Returns true if application is not found or there was an error. Otherwise it returns 10620 * the hidden state of the package for the given user. 10621 */ 10622 @Override 10623 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10625 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10626 true /* requireFullPermission */, false /* checkShell */, 10627 "getApplicationHidden for user " + userId); 10628 PackageSetting pkgSetting; 10629 long callingId = Binder.clearCallingIdentity(); 10630 try { 10631 // writer 10632 synchronized (mPackages) { 10633 pkgSetting = mSettings.mPackages.get(packageName); 10634 if (pkgSetting == null) { 10635 return true; 10636 } 10637 return pkgSetting.getHidden(userId); 10638 } 10639 } finally { 10640 Binder.restoreCallingIdentity(callingId); 10641 } 10642 } 10643 10644 /** 10645 * @hide 10646 */ 10647 @Override 10648 public int installExistingPackageAsUser(String packageName, int userId) { 10649 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10650 null); 10651 PackageSetting pkgSetting; 10652 final int uid = Binder.getCallingUid(); 10653 enforceCrossUserPermission(uid, userId, 10654 true /* requireFullPermission */, true /* checkShell */, 10655 "installExistingPackage for user " + userId); 10656 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10657 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10658 } 10659 10660 long callingId = Binder.clearCallingIdentity(); 10661 try { 10662 boolean installed = false; 10663 10664 // writer 10665 synchronized (mPackages) { 10666 pkgSetting = mSettings.mPackages.get(packageName); 10667 if (pkgSetting == null) { 10668 return PackageManager.INSTALL_FAILED_INVALID_URI; 10669 } 10670 if (!pkgSetting.getInstalled(userId)) { 10671 pkgSetting.setInstalled(true, userId); 10672 pkgSetting.setHidden(false, userId); 10673 mSettings.writePackageRestrictionsLPr(userId); 10674 installed = true; 10675 } 10676 } 10677 10678 if (installed) { 10679 if (pkgSetting.pkg != null) { 10680 prepareAppDataAfterInstall(pkgSetting.pkg); 10681 } 10682 sendPackageAddedForUser(packageName, pkgSetting, userId); 10683 } 10684 } finally { 10685 Binder.restoreCallingIdentity(callingId); 10686 } 10687 10688 return PackageManager.INSTALL_SUCCEEDED; 10689 } 10690 10691 boolean isUserRestricted(int userId, String restrictionKey) { 10692 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10693 if (restrictions.getBoolean(restrictionKey, false)) { 10694 Log.w(TAG, "User is restricted: " + restrictionKey); 10695 return true; 10696 } 10697 return false; 10698 } 10699 10700 @Override 10701 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10702 int userId) { 10703 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10704 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10705 true /* requireFullPermission */, true /* checkShell */, 10706 "setPackagesSuspended for user " + userId); 10707 10708 if (ArrayUtils.isEmpty(packageNames)) { 10709 return packageNames; 10710 } 10711 10712 // List of package names for whom the suspended state has changed. 10713 List<String> changedPackages = new ArrayList<>(packageNames.length); 10714 // List of package names for whom the suspended state is not set as requested in this 10715 // method. 10716 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10717 for (int i = 0; i < packageNames.length; i++) { 10718 String packageName = packageNames[i]; 10719 long callingId = Binder.clearCallingIdentity(); 10720 try { 10721 boolean changed = false; 10722 final int appId; 10723 synchronized (mPackages) { 10724 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10725 if (pkgSetting == null) { 10726 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10727 + "\". Skipping suspending/un-suspending."); 10728 unactionedPackages.add(packageName); 10729 continue; 10730 } 10731 appId = pkgSetting.appId; 10732 if (pkgSetting.getSuspended(userId) != suspended) { 10733 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10734 unactionedPackages.add(packageName); 10735 continue; 10736 } 10737 pkgSetting.setSuspended(suspended, userId); 10738 mSettings.writePackageRestrictionsLPr(userId); 10739 changed = true; 10740 changedPackages.add(packageName); 10741 } 10742 } 10743 10744 if (changed && suspended) { 10745 killApplication(packageName, UserHandle.getUid(userId, appId), 10746 "suspending package"); 10747 } 10748 } finally { 10749 Binder.restoreCallingIdentity(callingId); 10750 } 10751 } 10752 10753 if (!changedPackages.isEmpty()) { 10754 sendPackagesSuspendedForUser(changedPackages.toArray( 10755 new String[changedPackages.size()]), userId, suspended); 10756 } 10757 10758 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10759 } 10760 10761 @Override 10762 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10763 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10764 true /* requireFullPermission */, false /* checkShell */, 10765 "isPackageSuspendedForUser for user " + userId); 10766 synchronized (mPackages) { 10767 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10768 return pkgSetting != null && pkgSetting.getSuspended(userId); 10769 } 10770 } 10771 10772 // TODO: investigate and add more restrictions for suspending crucial packages. 10773 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10774 if (isPackageDeviceAdmin(packageName, userId)) { 10775 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10776 + "\": has active device admin"); 10777 return false; 10778 } 10779 10780 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10781 if (packageName.equals(activeLauncherPackageName)) { 10782 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10783 + "\" because it is set as the active launcher"); 10784 return false; 10785 } 10786 10787 final PackageParser.Package pkg = mPackages.get(packageName); 10788 if (pkg != null && isPrivilegedApp(pkg)) { 10789 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10790 + "\" because it is a privileged app"); 10791 return false; 10792 } 10793 10794 return true; 10795 } 10796 10797 private String getActiveLauncherPackageName(int userId) { 10798 Intent intent = new Intent(Intent.ACTION_MAIN); 10799 intent.addCategory(Intent.CATEGORY_HOME); 10800 ResolveInfo resolveInfo = resolveIntent( 10801 intent, 10802 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10803 PackageManager.MATCH_DEFAULT_ONLY, 10804 userId); 10805 10806 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10807 } 10808 10809 @Override 10810 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10811 mContext.enforceCallingOrSelfPermission( 10812 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10813 "Only package verification agents can verify applications"); 10814 10815 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10816 final PackageVerificationResponse response = new PackageVerificationResponse( 10817 verificationCode, Binder.getCallingUid()); 10818 msg.arg1 = id; 10819 msg.obj = response; 10820 mHandler.sendMessage(msg); 10821 } 10822 10823 @Override 10824 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10825 long millisecondsToDelay) { 10826 mContext.enforceCallingOrSelfPermission( 10827 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10828 "Only package verification agents can extend verification timeouts"); 10829 10830 final PackageVerificationState state = mPendingVerification.get(id); 10831 final PackageVerificationResponse response = new PackageVerificationResponse( 10832 verificationCodeAtTimeout, Binder.getCallingUid()); 10833 10834 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10835 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10836 } 10837 if (millisecondsToDelay < 0) { 10838 millisecondsToDelay = 0; 10839 } 10840 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10841 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10842 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10843 } 10844 10845 if ((state != null) && !state.timeoutExtended()) { 10846 state.extendTimeout(); 10847 10848 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10849 msg.arg1 = id; 10850 msg.obj = response; 10851 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10852 } 10853 } 10854 10855 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10856 int verificationCode, UserHandle user) { 10857 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10858 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10859 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10860 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10861 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10862 10863 mContext.sendBroadcastAsUser(intent, user, 10864 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10865 } 10866 10867 private ComponentName matchComponentForVerifier(String packageName, 10868 List<ResolveInfo> receivers) { 10869 ActivityInfo targetReceiver = null; 10870 10871 final int NR = receivers.size(); 10872 for (int i = 0; i < NR; i++) { 10873 final ResolveInfo info = receivers.get(i); 10874 if (info.activityInfo == null) { 10875 continue; 10876 } 10877 10878 if (packageName.equals(info.activityInfo.packageName)) { 10879 targetReceiver = info.activityInfo; 10880 break; 10881 } 10882 } 10883 10884 if (targetReceiver == null) { 10885 return null; 10886 } 10887 10888 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10889 } 10890 10891 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10892 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10893 if (pkgInfo.verifiers.length == 0) { 10894 return null; 10895 } 10896 10897 final int N = pkgInfo.verifiers.length; 10898 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10899 for (int i = 0; i < N; i++) { 10900 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10901 10902 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10903 receivers); 10904 if (comp == null) { 10905 continue; 10906 } 10907 10908 final int verifierUid = getUidForVerifier(verifierInfo); 10909 if (verifierUid == -1) { 10910 continue; 10911 } 10912 10913 if (DEBUG_VERIFY) { 10914 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10915 + " with the correct signature"); 10916 } 10917 sufficientVerifiers.add(comp); 10918 verificationState.addSufficientVerifier(verifierUid); 10919 } 10920 10921 return sufficientVerifiers; 10922 } 10923 10924 private int getUidForVerifier(VerifierInfo verifierInfo) { 10925 synchronized (mPackages) { 10926 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10927 if (pkg == null) { 10928 return -1; 10929 } else if (pkg.mSignatures.length != 1) { 10930 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10931 + " has more than one signature; ignoring"); 10932 return -1; 10933 } 10934 10935 /* 10936 * If the public key of the package's signature does not match 10937 * our expected public key, then this is a different package and 10938 * we should skip. 10939 */ 10940 10941 final byte[] expectedPublicKey; 10942 try { 10943 final Signature verifierSig = pkg.mSignatures[0]; 10944 final PublicKey publicKey = verifierSig.getPublicKey(); 10945 expectedPublicKey = publicKey.getEncoded(); 10946 } catch (CertificateException e) { 10947 return -1; 10948 } 10949 10950 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10951 10952 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10953 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10954 + " does not have the expected public key; ignoring"); 10955 return -1; 10956 } 10957 10958 return pkg.applicationInfo.uid; 10959 } 10960 } 10961 10962 @Override 10963 public void finishPackageInstall(int token) { 10964 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10965 10966 if (DEBUG_INSTALL) { 10967 Slog.v(TAG, "BM finishing package install for " + token); 10968 } 10969 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10970 10971 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10972 mHandler.sendMessage(msg); 10973 } 10974 10975 /** 10976 * Get the verification agent timeout. 10977 * 10978 * @return verification timeout in milliseconds 10979 */ 10980 private long getVerificationTimeout() { 10981 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10982 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10983 DEFAULT_VERIFICATION_TIMEOUT); 10984 } 10985 10986 /** 10987 * Get the default verification agent response code. 10988 * 10989 * @return default verification response code 10990 */ 10991 private int getDefaultVerificationResponse() { 10992 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10993 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10994 DEFAULT_VERIFICATION_RESPONSE); 10995 } 10996 10997 /** 10998 * Check whether or not package verification has been enabled. 10999 * 11000 * @return true if verification should be performed 11001 */ 11002 private boolean isVerificationEnabled(int userId, int installFlags) { 11003 if (!DEFAULT_VERIFY_ENABLE) { 11004 return false; 11005 } 11006 // Ephemeral apps don't get the full verification treatment 11007 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11008 if (DEBUG_EPHEMERAL) { 11009 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11010 } 11011 return false; 11012 } 11013 11014 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11015 11016 // Check if installing from ADB 11017 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11018 // Do not run verification in a test harness environment 11019 if (ActivityManager.isRunningInTestHarness()) { 11020 return false; 11021 } 11022 if (ensureVerifyAppsEnabled) { 11023 return true; 11024 } 11025 // Check if the developer does not want package verification for ADB installs 11026 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11027 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11028 return false; 11029 } 11030 } 11031 11032 if (ensureVerifyAppsEnabled) { 11033 return true; 11034 } 11035 11036 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11037 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11038 } 11039 11040 @Override 11041 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11042 throws RemoteException { 11043 mContext.enforceCallingOrSelfPermission( 11044 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11045 "Only intentfilter verification agents can verify applications"); 11046 11047 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11048 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11049 Binder.getCallingUid(), verificationCode, failedDomains); 11050 msg.arg1 = id; 11051 msg.obj = response; 11052 mHandler.sendMessage(msg); 11053 } 11054 11055 @Override 11056 public int getIntentVerificationStatus(String packageName, int userId) { 11057 synchronized (mPackages) { 11058 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11059 } 11060 } 11061 11062 @Override 11063 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11064 mContext.enforceCallingOrSelfPermission( 11065 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11066 11067 boolean result = false; 11068 synchronized (mPackages) { 11069 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11070 } 11071 if (result) { 11072 scheduleWritePackageRestrictionsLocked(userId); 11073 } 11074 return result; 11075 } 11076 11077 @Override 11078 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 11079 synchronized (mPackages) { 11080 return mSettings.getIntentFilterVerificationsLPr(packageName); 11081 } 11082 } 11083 11084 @Override 11085 public List<IntentFilter> getAllIntentFilters(String packageName) { 11086 if (TextUtils.isEmpty(packageName)) { 11087 return Collections.<IntentFilter>emptyList(); 11088 } 11089 synchronized (mPackages) { 11090 PackageParser.Package pkg = mPackages.get(packageName); 11091 if (pkg == null || pkg.activities == null) { 11092 return Collections.<IntentFilter>emptyList(); 11093 } 11094 final int count = pkg.activities.size(); 11095 ArrayList<IntentFilter> result = new ArrayList<>(); 11096 for (int n=0; n<count; n++) { 11097 PackageParser.Activity activity = pkg.activities.get(n); 11098 if (activity.intents != null && activity.intents.size() > 0) { 11099 result.addAll(activity.intents); 11100 } 11101 } 11102 return result; 11103 } 11104 } 11105 11106 @Override 11107 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11108 mContext.enforceCallingOrSelfPermission( 11109 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11110 11111 synchronized (mPackages) { 11112 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11113 if (packageName != null) { 11114 result |= updateIntentVerificationStatus(packageName, 11115 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11116 userId); 11117 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11118 packageName, userId); 11119 } 11120 return result; 11121 } 11122 } 11123 11124 @Override 11125 public String getDefaultBrowserPackageName(int userId) { 11126 synchronized (mPackages) { 11127 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11128 } 11129 } 11130 11131 /** 11132 * Get the "allow unknown sources" setting. 11133 * 11134 * @return the current "allow unknown sources" setting 11135 */ 11136 private int getUnknownSourcesSettings() { 11137 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11138 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11139 -1); 11140 } 11141 11142 @Override 11143 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11144 final int uid = Binder.getCallingUid(); 11145 // writer 11146 synchronized (mPackages) { 11147 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11148 if (targetPackageSetting == null) { 11149 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11150 } 11151 11152 PackageSetting installerPackageSetting; 11153 if (installerPackageName != null) { 11154 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11155 if (installerPackageSetting == null) { 11156 throw new IllegalArgumentException("Unknown installer package: " 11157 + installerPackageName); 11158 } 11159 } else { 11160 installerPackageSetting = null; 11161 } 11162 11163 Signature[] callerSignature; 11164 Object obj = mSettings.getUserIdLPr(uid); 11165 if (obj != null) { 11166 if (obj instanceof SharedUserSetting) { 11167 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11168 } else if (obj instanceof PackageSetting) { 11169 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11170 } else { 11171 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11172 } 11173 } else { 11174 throw new SecurityException("Unknown calling UID: " + uid); 11175 } 11176 11177 // Verify: can't set installerPackageName to a package that is 11178 // not signed with the same cert as the caller. 11179 if (installerPackageSetting != null) { 11180 if (compareSignatures(callerSignature, 11181 installerPackageSetting.signatures.mSignatures) 11182 != PackageManager.SIGNATURE_MATCH) { 11183 throw new SecurityException( 11184 "Caller does not have same cert as new installer package " 11185 + installerPackageName); 11186 } 11187 } 11188 11189 // Verify: if target already has an installer package, it must 11190 // be signed with the same cert as the caller. 11191 if (targetPackageSetting.installerPackageName != null) { 11192 PackageSetting setting = mSettings.mPackages.get( 11193 targetPackageSetting.installerPackageName); 11194 // If the currently set package isn't valid, then it's always 11195 // okay to change it. 11196 if (setting != null) { 11197 if (compareSignatures(callerSignature, 11198 setting.signatures.mSignatures) 11199 != PackageManager.SIGNATURE_MATCH) { 11200 throw new SecurityException( 11201 "Caller does not have same cert as old installer package " 11202 + targetPackageSetting.installerPackageName); 11203 } 11204 } 11205 } 11206 11207 // Okay! 11208 targetPackageSetting.installerPackageName = installerPackageName; 11209 scheduleWriteSettingsLocked(); 11210 } 11211 } 11212 11213 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11214 // Queue up an async operation since the package installation may take a little while. 11215 mHandler.post(new Runnable() { 11216 public void run() { 11217 mHandler.removeCallbacks(this); 11218 // Result object to be returned 11219 PackageInstalledInfo res = new PackageInstalledInfo(); 11220 res.setReturnCode(currentStatus); 11221 res.uid = -1; 11222 res.pkg = null; 11223 res.removedInfo = null; 11224 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11225 args.doPreInstall(res.returnCode); 11226 synchronized (mInstallLock) { 11227 installPackageTracedLI(args, res); 11228 } 11229 args.doPostInstall(res.returnCode, res.uid); 11230 } 11231 11232 // A restore should be performed at this point if (a) the install 11233 // succeeded, (b) the operation is not an update, and (c) the new 11234 // package has not opted out of backup participation. 11235 final boolean update = res.removedInfo != null 11236 && res.removedInfo.removedPackage != null; 11237 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11238 boolean doRestore = !update 11239 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11240 11241 // Set up the post-install work request bookkeeping. This will be used 11242 // and cleaned up by the post-install event handling regardless of whether 11243 // there's a restore pass performed. Token values are >= 1. 11244 int token; 11245 if (mNextInstallToken < 0) mNextInstallToken = 1; 11246 token = mNextInstallToken++; 11247 11248 PostInstallData data = new PostInstallData(args, res); 11249 mRunningInstalls.put(token, data); 11250 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11251 11252 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11253 // Pass responsibility to the Backup Manager. It will perform a 11254 // restore if appropriate, then pass responsibility back to the 11255 // Package Manager to run the post-install observer callbacks 11256 // and broadcasts. 11257 IBackupManager bm = IBackupManager.Stub.asInterface( 11258 ServiceManager.getService(Context.BACKUP_SERVICE)); 11259 if (bm != null) { 11260 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11261 + " to BM for possible restore"); 11262 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11263 try { 11264 // TODO: http://b/22388012 11265 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11266 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11267 } else { 11268 doRestore = false; 11269 } 11270 } catch (RemoteException e) { 11271 // can't happen; the backup manager is local 11272 } catch (Exception e) { 11273 Slog.e(TAG, "Exception trying to enqueue restore", e); 11274 doRestore = false; 11275 } 11276 } else { 11277 Slog.e(TAG, "Backup Manager not found!"); 11278 doRestore = false; 11279 } 11280 } 11281 11282 if (!doRestore) { 11283 // No restore possible, or the Backup Manager was mysteriously not 11284 // available -- just fire the post-install work request directly. 11285 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11286 11287 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11288 11289 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11290 mHandler.sendMessage(msg); 11291 } 11292 } 11293 }); 11294 } 11295 11296 private abstract class HandlerParams { 11297 private static final int MAX_RETRIES = 4; 11298 11299 /** 11300 * Number of times startCopy() has been attempted and had a non-fatal 11301 * error. 11302 */ 11303 private int mRetries = 0; 11304 11305 /** User handle for the user requesting the information or installation. */ 11306 private final UserHandle mUser; 11307 String traceMethod; 11308 int traceCookie; 11309 11310 HandlerParams(UserHandle user) { 11311 mUser = user; 11312 } 11313 11314 UserHandle getUser() { 11315 return mUser; 11316 } 11317 11318 HandlerParams setTraceMethod(String traceMethod) { 11319 this.traceMethod = traceMethod; 11320 return this; 11321 } 11322 11323 HandlerParams setTraceCookie(int traceCookie) { 11324 this.traceCookie = traceCookie; 11325 return this; 11326 } 11327 11328 final boolean startCopy() { 11329 boolean res; 11330 try { 11331 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11332 11333 if (++mRetries > MAX_RETRIES) { 11334 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11335 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11336 handleServiceError(); 11337 return false; 11338 } else { 11339 handleStartCopy(); 11340 res = true; 11341 } 11342 } catch (RemoteException e) { 11343 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11344 mHandler.sendEmptyMessage(MCS_RECONNECT); 11345 res = false; 11346 } 11347 handleReturnCode(); 11348 return res; 11349 } 11350 11351 final void serviceError() { 11352 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11353 handleServiceError(); 11354 handleReturnCode(); 11355 } 11356 11357 abstract void handleStartCopy() throws RemoteException; 11358 abstract void handleServiceError(); 11359 abstract void handleReturnCode(); 11360 } 11361 11362 class MeasureParams extends HandlerParams { 11363 private final PackageStats mStats; 11364 private boolean mSuccess; 11365 11366 private final IPackageStatsObserver mObserver; 11367 11368 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11369 super(new UserHandle(stats.userHandle)); 11370 mObserver = observer; 11371 mStats = stats; 11372 } 11373 11374 @Override 11375 public String toString() { 11376 return "MeasureParams{" 11377 + Integer.toHexString(System.identityHashCode(this)) 11378 + " " + mStats.packageName + "}"; 11379 } 11380 11381 @Override 11382 void handleStartCopy() throws RemoteException { 11383 synchronized (mInstallLock) { 11384 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11385 } 11386 11387 if (mSuccess) { 11388 final boolean mounted; 11389 if (Environment.isExternalStorageEmulated()) { 11390 mounted = true; 11391 } else { 11392 final String status = Environment.getExternalStorageState(); 11393 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11394 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11395 } 11396 11397 if (mounted) { 11398 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11399 11400 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11401 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11402 11403 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11404 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11405 11406 // Always subtract cache size, since it's a subdirectory 11407 mStats.externalDataSize -= mStats.externalCacheSize; 11408 11409 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11410 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11411 11412 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11413 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11414 } 11415 } 11416 } 11417 11418 @Override 11419 void handleReturnCode() { 11420 if (mObserver != null) { 11421 try { 11422 mObserver.onGetStatsCompleted(mStats, mSuccess); 11423 } catch (RemoteException e) { 11424 Slog.i(TAG, "Observer no longer exists."); 11425 } 11426 } 11427 } 11428 11429 @Override 11430 void handleServiceError() { 11431 Slog.e(TAG, "Could not measure application " + mStats.packageName 11432 + " external storage"); 11433 } 11434 } 11435 11436 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11437 throws RemoteException { 11438 long result = 0; 11439 for (File path : paths) { 11440 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11441 } 11442 return result; 11443 } 11444 11445 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11446 for (File path : paths) { 11447 try { 11448 mcs.clearDirectory(path.getAbsolutePath()); 11449 } catch (RemoteException e) { 11450 } 11451 } 11452 } 11453 11454 static class OriginInfo { 11455 /** 11456 * Location where install is coming from, before it has been 11457 * copied/renamed into place. This could be a single monolithic APK 11458 * file, or a cluster directory. This location may be untrusted. 11459 */ 11460 final File file; 11461 final String cid; 11462 11463 /** 11464 * Flag indicating that {@link #file} or {@link #cid} has already been 11465 * staged, meaning downstream users don't need to defensively copy the 11466 * contents. 11467 */ 11468 final boolean staged; 11469 11470 /** 11471 * Flag indicating that {@link #file} or {@link #cid} is an already 11472 * installed app that is being moved. 11473 */ 11474 final boolean existing; 11475 11476 final String resolvedPath; 11477 final File resolvedFile; 11478 11479 static OriginInfo fromNothing() { 11480 return new OriginInfo(null, null, false, false); 11481 } 11482 11483 static OriginInfo fromUntrustedFile(File file) { 11484 return new OriginInfo(file, null, false, false); 11485 } 11486 11487 static OriginInfo fromExistingFile(File file) { 11488 return new OriginInfo(file, null, false, true); 11489 } 11490 11491 static OriginInfo fromStagedFile(File file) { 11492 return new OriginInfo(file, null, true, false); 11493 } 11494 11495 static OriginInfo fromStagedContainer(String cid) { 11496 return new OriginInfo(null, cid, true, false); 11497 } 11498 11499 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11500 this.file = file; 11501 this.cid = cid; 11502 this.staged = staged; 11503 this.existing = existing; 11504 11505 if (cid != null) { 11506 resolvedPath = PackageHelper.getSdDir(cid); 11507 resolvedFile = new File(resolvedPath); 11508 } else if (file != null) { 11509 resolvedPath = file.getAbsolutePath(); 11510 resolvedFile = file; 11511 } else { 11512 resolvedPath = null; 11513 resolvedFile = null; 11514 } 11515 } 11516 } 11517 11518 static class MoveInfo { 11519 final int moveId; 11520 final String fromUuid; 11521 final String toUuid; 11522 final String packageName; 11523 final String dataAppName; 11524 final int appId; 11525 final String seinfo; 11526 final int targetSdkVersion; 11527 11528 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11529 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11530 this.moveId = moveId; 11531 this.fromUuid = fromUuid; 11532 this.toUuid = toUuid; 11533 this.packageName = packageName; 11534 this.dataAppName = dataAppName; 11535 this.appId = appId; 11536 this.seinfo = seinfo; 11537 this.targetSdkVersion = targetSdkVersion; 11538 } 11539 } 11540 11541 static class VerificationInfo { 11542 /** A constant used to indicate that a uid value is not present. */ 11543 public static final int NO_UID = -1; 11544 11545 /** URI referencing where the package was downloaded from. */ 11546 final Uri originatingUri; 11547 11548 /** HTTP referrer URI associated with the originatingURI. */ 11549 final Uri referrer; 11550 11551 /** UID of the application that the install request originated from. */ 11552 final int originatingUid; 11553 11554 /** UID of application requesting the install */ 11555 final int installerUid; 11556 11557 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11558 this.originatingUri = originatingUri; 11559 this.referrer = referrer; 11560 this.originatingUid = originatingUid; 11561 this.installerUid = installerUid; 11562 } 11563 } 11564 11565 class InstallParams extends HandlerParams { 11566 final OriginInfo origin; 11567 final MoveInfo move; 11568 final IPackageInstallObserver2 observer; 11569 int installFlags; 11570 final String installerPackageName; 11571 final String volumeUuid; 11572 private InstallArgs mArgs; 11573 private int mRet; 11574 final String packageAbiOverride; 11575 final String[] grantedRuntimePermissions; 11576 final VerificationInfo verificationInfo; 11577 11578 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11579 int installFlags, String installerPackageName, String volumeUuid, 11580 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11581 String[] grantedPermissions) { 11582 super(user); 11583 this.origin = origin; 11584 this.move = move; 11585 this.observer = observer; 11586 this.installFlags = installFlags; 11587 this.installerPackageName = installerPackageName; 11588 this.volumeUuid = volumeUuid; 11589 this.verificationInfo = verificationInfo; 11590 this.packageAbiOverride = packageAbiOverride; 11591 this.grantedRuntimePermissions = grantedPermissions; 11592 } 11593 11594 @Override 11595 public String toString() { 11596 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11597 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11598 } 11599 11600 private int installLocationPolicy(PackageInfoLite pkgLite) { 11601 String packageName = pkgLite.packageName; 11602 int installLocation = pkgLite.installLocation; 11603 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11604 // reader 11605 synchronized (mPackages) { 11606 // Currently installed package which the new package is attempting to replace or 11607 // null if no such package is installed. 11608 PackageParser.Package installedPkg = mPackages.get(packageName); 11609 // Package which currently owns the data which the new package will own if installed. 11610 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11611 // will be null whereas dataOwnerPkg will contain information about the package 11612 // which was uninstalled while keeping its data. 11613 PackageParser.Package dataOwnerPkg = installedPkg; 11614 if (dataOwnerPkg == null) { 11615 PackageSetting ps = mSettings.mPackages.get(packageName); 11616 if (ps != null) { 11617 dataOwnerPkg = ps.pkg; 11618 } 11619 } 11620 11621 if (dataOwnerPkg != null) { 11622 // If installed, the package will get access to data left on the device by its 11623 // predecessor. As a security measure, this is permited only if this is not a 11624 // version downgrade or if the predecessor package is marked as debuggable and 11625 // a downgrade is explicitly requested. 11626 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11627 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11628 try { 11629 checkDowngrade(dataOwnerPkg, pkgLite); 11630 } catch (PackageManagerException e) { 11631 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11632 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11633 } 11634 } 11635 } 11636 11637 if (installedPkg != null) { 11638 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11639 // Check for updated system application. 11640 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11641 if (onSd) { 11642 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11643 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11644 } 11645 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11646 } else { 11647 if (onSd) { 11648 // Install flag overrides everything. 11649 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11650 } 11651 // If current upgrade specifies particular preference 11652 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11653 // Application explicitly specified internal. 11654 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11655 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11656 // App explictly prefers external. Let policy decide 11657 } else { 11658 // Prefer previous location 11659 if (isExternal(installedPkg)) { 11660 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11661 } 11662 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11663 } 11664 } 11665 } else { 11666 // Invalid install. Return error code 11667 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11668 } 11669 } 11670 } 11671 // All the special cases have been taken care of. 11672 // Return result based on recommended install location. 11673 if (onSd) { 11674 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11675 } 11676 return pkgLite.recommendedInstallLocation; 11677 } 11678 11679 /* 11680 * Invoke remote method to get package information and install 11681 * location values. Override install location based on default 11682 * policy if needed and then create install arguments based 11683 * on the install location. 11684 */ 11685 public void handleStartCopy() throws RemoteException { 11686 int ret = PackageManager.INSTALL_SUCCEEDED; 11687 11688 // If we're already staged, we've firmly committed to an install location 11689 if (origin.staged) { 11690 if (origin.file != null) { 11691 installFlags |= PackageManager.INSTALL_INTERNAL; 11692 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11693 } else if (origin.cid != null) { 11694 installFlags |= PackageManager.INSTALL_EXTERNAL; 11695 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11696 } else { 11697 throw new IllegalStateException("Invalid stage location"); 11698 } 11699 } 11700 11701 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11702 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11703 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11704 PackageInfoLite pkgLite = null; 11705 11706 if (onInt && onSd) { 11707 // Check if both bits are set. 11708 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11709 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11710 } else if (onSd && ephemeral) { 11711 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11712 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11713 } else { 11714 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11715 packageAbiOverride); 11716 11717 if (DEBUG_EPHEMERAL && ephemeral) { 11718 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11719 } 11720 11721 /* 11722 * If we have too little free space, try to free cache 11723 * before giving up. 11724 */ 11725 if (!origin.staged && pkgLite.recommendedInstallLocation 11726 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11727 // TODO: focus freeing disk space on the target device 11728 final StorageManager storage = StorageManager.from(mContext); 11729 final long lowThreshold = storage.getStorageLowBytes( 11730 Environment.getDataDirectory()); 11731 11732 final long sizeBytes = mContainerService.calculateInstalledSize( 11733 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11734 11735 try { 11736 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11737 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11738 installFlags, packageAbiOverride); 11739 } catch (InstallerException e) { 11740 Slog.w(TAG, "Failed to free cache", e); 11741 } 11742 11743 /* 11744 * The cache free must have deleted the file we 11745 * downloaded to install. 11746 * 11747 * TODO: fix the "freeCache" call to not delete 11748 * the file we care about. 11749 */ 11750 if (pkgLite.recommendedInstallLocation 11751 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11752 pkgLite.recommendedInstallLocation 11753 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11754 } 11755 } 11756 } 11757 11758 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11759 int loc = pkgLite.recommendedInstallLocation; 11760 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11761 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11762 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11763 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11764 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11765 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11766 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11767 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11768 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11769 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11770 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11771 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11772 } else { 11773 // Override with defaults if needed. 11774 loc = installLocationPolicy(pkgLite); 11775 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11776 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11777 } else if (!onSd && !onInt) { 11778 // Override install location with flags 11779 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11780 // Set the flag to install on external media. 11781 installFlags |= PackageManager.INSTALL_EXTERNAL; 11782 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11783 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11784 if (DEBUG_EPHEMERAL) { 11785 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11786 } 11787 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11788 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11789 |PackageManager.INSTALL_INTERNAL); 11790 } else { 11791 // Make sure the flag for installing on external 11792 // media is unset 11793 installFlags |= PackageManager.INSTALL_INTERNAL; 11794 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11795 } 11796 } 11797 } 11798 } 11799 11800 final InstallArgs args = createInstallArgs(this); 11801 mArgs = args; 11802 11803 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11804 // TODO: http://b/22976637 11805 // Apps installed for "all" users use the device owner to verify the app 11806 UserHandle verifierUser = getUser(); 11807 if (verifierUser == UserHandle.ALL) { 11808 verifierUser = UserHandle.SYSTEM; 11809 } 11810 11811 /* 11812 * Determine if we have any installed package verifiers. If we 11813 * do, then we'll defer to them to verify the packages. 11814 */ 11815 final int requiredUid = mRequiredVerifierPackage == null ? -1 11816 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11817 verifierUser.getIdentifier()); 11818 if (!origin.existing && requiredUid != -1 11819 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11820 final Intent verification = new Intent( 11821 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11822 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11823 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11824 PACKAGE_MIME_TYPE); 11825 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11826 11827 // Query all live verifiers based on current user state 11828 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11829 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11830 11831 if (DEBUG_VERIFY) { 11832 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11833 + verification.toString() + " with " + pkgLite.verifiers.length 11834 + " optional verifiers"); 11835 } 11836 11837 final int verificationId = mPendingVerificationToken++; 11838 11839 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11840 11841 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11842 installerPackageName); 11843 11844 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11845 installFlags); 11846 11847 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11848 pkgLite.packageName); 11849 11850 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11851 pkgLite.versionCode); 11852 11853 if (verificationInfo != null) { 11854 if (verificationInfo.originatingUri != null) { 11855 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11856 verificationInfo.originatingUri); 11857 } 11858 if (verificationInfo.referrer != null) { 11859 verification.putExtra(Intent.EXTRA_REFERRER, 11860 verificationInfo.referrer); 11861 } 11862 if (verificationInfo.originatingUid >= 0) { 11863 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11864 verificationInfo.originatingUid); 11865 } 11866 if (verificationInfo.installerUid >= 0) { 11867 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11868 verificationInfo.installerUid); 11869 } 11870 } 11871 11872 final PackageVerificationState verificationState = new PackageVerificationState( 11873 requiredUid, args); 11874 11875 mPendingVerification.append(verificationId, verificationState); 11876 11877 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11878 receivers, verificationState); 11879 11880 /* 11881 * If any sufficient verifiers were listed in the package 11882 * manifest, attempt to ask them. 11883 */ 11884 if (sufficientVerifiers != null) { 11885 final int N = sufficientVerifiers.size(); 11886 if (N == 0) { 11887 Slog.i(TAG, "Additional verifiers required, but none installed."); 11888 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11889 } else { 11890 for (int i = 0; i < N; i++) { 11891 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11892 11893 final Intent sufficientIntent = new Intent(verification); 11894 sufficientIntent.setComponent(verifierComponent); 11895 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11896 } 11897 } 11898 } 11899 11900 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11901 mRequiredVerifierPackage, receivers); 11902 if (ret == PackageManager.INSTALL_SUCCEEDED 11903 && mRequiredVerifierPackage != null) { 11904 Trace.asyncTraceBegin( 11905 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11906 /* 11907 * Send the intent to the required verification agent, 11908 * but only start the verification timeout after the 11909 * target BroadcastReceivers have run. 11910 */ 11911 verification.setComponent(requiredVerifierComponent); 11912 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11913 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11914 new BroadcastReceiver() { 11915 @Override 11916 public void onReceive(Context context, Intent intent) { 11917 final Message msg = mHandler 11918 .obtainMessage(CHECK_PENDING_VERIFICATION); 11919 msg.arg1 = verificationId; 11920 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11921 } 11922 }, null, 0, null, null); 11923 11924 /* 11925 * We don't want the copy to proceed until verification 11926 * succeeds, so null out this field. 11927 */ 11928 mArgs = null; 11929 } 11930 } else { 11931 /* 11932 * No package verification is enabled, so immediately start 11933 * the remote call to initiate copy using temporary file. 11934 */ 11935 ret = args.copyApk(mContainerService, true); 11936 } 11937 } 11938 11939 mRet = ret; 11940 } 11941 11942 @Override 11943 void handleReturnCode() { 11944 // If mArgs is null, then MCS couldn't be reached. When it 11945 // reconnects, it will try again to install. At that point, this 11946 // will succeed. 11947 if (mArgs != null) { 11948 processPendingInstall(mArgs, mRet); 11949 } 11950 } 11951 11952 @Override 11953 void handleServiceError() { 11954 mArgs = createInstallArgs(this); 11955 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11956 } 11957 11958 public boolean isForwardLocked() { 11959 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11960 } 11961 } 11962 11963 /** 11964 * Used during creation of InstallArgs 11965 * 11966 * @param installFlags package installation flags 11967 * @return true if should be installed on external storage 11968 */ 11969 private static boolean installOnExternalAsec(int installFlags) { 11970 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11971 return false; 11972 } 11973 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11974 return true; 11975 } 11976 return false; 11977 } 11978 11979 /** 11980 * Used during creation of InstallArgs 11981 * 11982 * @param installFlags package installation flags 11983 * @return true if should be installed as forward locked 11984 */ 11985 private static boolean installForwardLocked(int installFlags) { 11986 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11987 } 11988 11989 private InstallArgs createInstallArgs(InstallParams params) { 11990 if (params.move != null) { 11991 return new MoveInstallArgs(params); 11992 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11993 return new AsecInstallArgs(params); 11994 } else { 11995 return new FileInstallArgs(params); 11996 } 11997 } 11998 11999 /** 12000 * Create args that describe an existing installed package. Typically used 12001 * when cleaning up old installs, or used as a move source. 12002 */ 12003 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12004 String resourcePath, String[] instructionSets) { 12005 final boolean isInAsec; 12006 if (installOnExternalAsec(installFlags)) { 12007 /* Apps on SD card are always in ASEC containers. */ 12008 isInAsec = true; 12009 } else if (installForwardLocked(installFlags) 12010 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12011 /* 12012 * Forward-locked apps are only in ASEC containers if they're the 12013 * new style 12014 */ 12015 isInAsec = true; 12016 } else { 12017 isInAsec = false; 12018 } 12019 12020 if (isInAsec) { 12021 return new AsecInstallArgs(codePath, instructionSets, 12022 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12023 } else { 12024 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12025 } 12026 } 12027 12028 static abstract class InstallArgs { 12029 /** @see InstallParams#origin */ 12030 final OriginInfo origin; 12031 /** @see InstallParams#move */ 12032 final MoveInfo move; 12033 12034 final IPackageInstallObserver2 observer; 12035 // Always refers to PackageManager flags only 12036 final int installFlags; 12037 final String installerPackageName; 12038 final String volumeUuid; 12039 final UserHandle user; 12040 final String abiOverride; 12041 final String[] installGrantPermissions; 12042 /** If non-null, drop an async trace when the install completes */ 12043 final String traceMethod; 12044 final int traceCookie; 12045 12046 // The list of instruction sets supported by this app. This is currently 12047 // only used during the rmdex() phase to clean up resources. We can get rid of this 12048 // if we move dex files under the common app path. 12049 /* nullable */ String[] instructionSets; 12050 12051 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12052 int installFlags, String installerPackageName, String volumeUuid, 12053 UserHandle user, String[] instructionSets, 12054 String abiOverride, String[] installGrantPermissions, 12055 String traceMethod, int traceCookie) { 12056 this.origin = origin; 12057 this.move = move; 12058 this.installFlags = installFlags; 12059 this.observer = observer; 12060 this.installerPackageName = installerPackageName; 12061 this.volumeUuid = volumeUuid; 12062 this.user = user; 12063 this.instructionSets = instructionSets; 12064 this.abiOverride = abiOverride; 12065 this.installGrantPermissions = installGrantPermissions; 12066 this.traceMethod = traceMethod; 12067 this.traceCookie = traceCookie; 12068 } 12069 12070 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12071 abstract int doPreInstall(int status); 12072 12073 /** 12074 * Rename package into final resting place. All paths on the given 12075 * scanned package should be updated to reflect the rename. 12076 */ 12077 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12078 abstract int doPostInstall(int status, int uid); 12079 12080 /** @see PackageSettingBase#codePathString */ 12081 abstract String getCodePath(); 12082 /** @see PackageSettingBase#resourcePathString */ 12083 abstract String getResourcePath(); 12084 12085 // Need installer lock especially for dex file removal. 12086 abstract void cleanUpResourcesLI(); 12087 abstract boolean doPostDeleteLI(boolean delete); 12088 12089 /** 12090 * Called before the source arguments are copied. This is used mostly 12091 * for MoveParams when it needs to read the source file to put it in the 12092 * destination. 12093 */ 12094 int doPreCopy() { 12095 return PackageManager.INSTALL_SUCCEEDED; 12096 } 12097 12098 /** 12099 * Called after the source arguments are copied. This is used mostly for 12100 * MoveParams when it needs to read the source file to put it in the 12101 * destination. 12102 * 12103 * @return 12104 */ 12105 int doPostCopy(int uid) { 12106 return PackageManager.INSTALL_SUCCEEDED; 12107 } 12108 12109 protected boolean isFwdLocked() { 12110 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12111 } 12112 12113 protected boolean isExternalAsec() { 12114 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12115 } 12116 12117 protected boolean isEphemeral() { 12118 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12119 } 12120 12121 UserHandle getUser() { 12122 return user; 12123 } 12124 } 12125 12126 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12127 if (!allCodePaths.isEmpty()) { 12128 if (instructionSets == null) { 12129 throw new IllegalStateException("instructionSet == null"); 12130 } 12131 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12132 for (String codePath : allCodePaths) { 12133 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12134 try { 12135 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12136 } catch (InstallerException ignored) { 12137 } 12138 } 12139 } 12140 } 12141 } 12142 12143 /** 12144 * Logic to handle installation of non-ASEC applications, including copying 12145 * and renaming logic. 12146 */ 12147 class FileInstallArgs extends InstallArgs { 12148 private File codeFile; 12149 private File resourceFile; 12150 12151 // Example topology: 12152 // /data/app/com.example/base.apk 12153 // /data/app/com.example/split_foo.apk 12154 // /data/app/com.example/lib/arm/libfoo.so 12155 // /data/app/com.example/lib/arm64/libfoo.so 12156 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12157 12158 /** New install */ 12159 FileInstallArgs(InstallParams params) { 12160 super(params.origin, params.move, params.observer, params.installFlags, 12161 params.installerPackageName, params.volumeUuid, 12162 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12163 params.grantedRuntimePermissions, 12164 params.traceMethod, params.traceCookie); 12165 if (isFwdLocked()) { 12166 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12167 } 12168 } 12169 12170 /** Existing install */ 12171 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12172 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12173 null, null, null, 0); 12174 this.codeFile = (codePath != null) ? new File(codePath) : null; 12175 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12176 } 12177 12178 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12179 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12180 try { 12181 return doCopyApk(imcs, temp); 12182 } finally { 12183 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12184 } 12185 } 12186 12187 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12188 if (origin.staged) { 12189 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12190 codeFile = origin.file; 12191 resourceFile = origin.file; 12192 return PackageManager.INSTALL_SUCCEEDED; 12193 } 12194 12195 try { 12196 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12197 final File tempDir = 12198 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12199 codeFile = tempDir; 12200 resourceFile = tempDir; 12201 } catch (IOException e) { 12202 Slog.w(TAG, "Failed to create copy file: " + e); 12203 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12204 } 12205 12206 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12207 @Override 12208 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12209 if (!FileUtils.isValidExtFilename(name)) { 12210 throw new IllegalArgumentException("Invalid filename: " + name); 12211 } 12212 try { 12213 final File file = new File(codeFile, name); 12214 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12215 O_RDWR | O_CREAT, 0644); 12216 Os.chmod(file.getAbsolutePath(), 0644); 12217 return new ParcelFileDescriptor(fd); 12218 } catch (ErrnoException e) { 12219 throw new RemoteException("Failed to open: " + e.getMessage()); 12220 } 12221 } 12222 }; 12223 12224 int ret = PackageManager.INSTALL_SUCCEEDED; 12225 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12226 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12227 Slog.e(TAG, "Failed to copy package"); 12228 return ret; 12229 } 12230 12231 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12232 NativeLibraryHelper.Handle handle = null; 12233 try { 12234 handle = NativeLibraryHelper.Handle.create(codeFile); 12235 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12236 abiOverride); 12237 } catch (IOException e) { 12238 Slog.e(TAG, "Copying native libraries failed", e); 12239 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12240 } finally { 12241 IoUtils.closeQuietly(handle); 12242 } 12243 12244 return ret; 12245 } 12246 12247 int doPreInstall(int status) { 12248 if (status != PackageManager.INSTALL_SUCCEEDED) { 12249 cleanUp(); 12250 } 12251 return status; 12252 } 12253 12254 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12255 if (status != PackageManager.INSTALL_SUCCEEDED) { 12256 cleanUp(); 12257 return false; 12258 } 12259 12260 final File targetDir = codeFile.getParentFile(); 12261 final File beforeCodeFile = codeFile; 12262 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12263 12264 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12265 try { 12266 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12267 } catch (ErrnoException e) { 12268 Slog.w(TAG, "Failed to rename", e); 12269 return false; 12270 } 12271 12272 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12273 Slog.w(TAG, "Failed to restorecon"); 12274 return false; 12275 } 12276 12277 // Reflect the rename internally 12278 codeFile = afterCodeFile; 12279 resourceFile = afterCodeFile; 12280 12281 // Reflect the rename in scanned details 12282 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12283 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12284 afterCodeFile, pkg.baseCodePath)); 12285 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12286 afterCodeFile, pkg.splitCodePaths)); 12287 12288 // Reflect the rename in app info 12289 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12290 pkg.setApplicationInfoCodePath(pkg.codePath); 12291 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12292 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12293 pkg.setApplicationInfoResourcePath(pkg.codePath); 12294 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12295 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12296 12297 return true; 12298 } 12299 12300 int doPostInstall(int status, int uid) { 12301 if (status != PackageManager.INSTALL_SUCCEEDED) { 12302 cleanUp(); 12303 } 12304 return status; 12305 } 12306 12307 @Override 12308 String getCodePath() { 12309 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12310 } 12311 12312 @Override 12313 String getResourcePath() { 12314 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12315 } 12316 12317 private boolean cleanUp() { 12318 if (codeFile == null || !codeFile.exists()) { 12319 return false; 12320 } 12321 12322 removeCodePathLI(codeFile); 12323 12324 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12325 resourceFile.delete(); 12326 } 12327 12328 return true; 12329 } 12330 12331 void cleanUpResourcesLI() { 12332 // Try enumerating all code paths before deleting 12333 List<String> allCodePaths = Collections.EMPTY_LIST; 12334 if (codeFile != null && codeFile.exists()) { 12335 try { 12336 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12337 allCodePaths = pkg.getAllCodePaths(); 12338 } catch (PackageParserException e) { 12339 // Ignored; we tried our best 12340 } 12341 } 12342 12343 cleanUp(); 12344 removeDexFiles(allCodePaths, instructionSets); 12345 } 12346 12347 boolean doPostDeleteLI(boolean delete) { 12348 // XXX err, shouldn't we respect the delete flag? 12349 cleanUpResourcesLI(); 12350 return true; 12351 } 12352 } 12353 12354 private boolean isAsecExternal(String cid) { 12355 final String asecPath = PackageHelper.getSdFilesystem(cid); 12356 return !asecPath.startsWith(mAsecInternalPath); 12357 } 12358 12359 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12360 PackageManagerException { 12361 if (copyRet < 0) { 12362 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12363 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12364 throw new PackageManagerException(copyRet, message); 12365 } 12366 } 12367 } 12368 12369 /** 12370 * Extract the MountService "container ID" from the full code path of an 12371 * .apk. 12372 */ 12373 static String cidFromCodePath(String fullCodePath) { 12374 int eidx = fullCodePath.lastIndexOf("/"); 12375 String subStr1 = fullCodePath.substring(0, eidx); 12376 int sidx = subStr1.lastIndexOf("/"); 12377 return subStr1.substring(sidx+1, eidx); 12378 } 12379 12380 /** 12381 * Logic to handle installation of ASEC applications, including copying and 12382 * renaming logic. 12383 */ 12384 class AsecInstallArgs extends InstallArgs { 12385 static final String RES_FILE_NAME = "pkg.apk"; 12386 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12387 12388 String cid; 12389 String packagePath; 12390 String resourcePath; 12391 12392 /** New install */ 12393 AsecInstallArgs(InstallParams params) { 12394 super(params.origin, params.move, params.observer, params.installFlags, 12395 params.installerPackageName, params.volumeUuid, 12396 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12397 params.grantedRuntimePermissions, 12398 params.traceMethod, params.traceCookie); 12399 } 12400 12401 /** Existing install */ 12402 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12403 boolean isExternal, boolean isForwardLocked) { 12404 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12405 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12406 instructionSets, null, null, null, 0); 12407 // Hackily pretend we're still looking at a full code path 12408 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12409 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12410 } 12411 12412 // Extract cid from fullCodePath 12413 int eidx = fullCodePath.lastIndexOf("/"); 12414 String subStr1 = fullCodePath.substring(0, eidx); 12415 int sidx = subStr1.lastIndexOf("/"); 12416 cid = subStr1.substring(sidx+1, eidx); 12417 setMountPath(subStr1); 12418 } 12419 12420 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12421 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12422 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12423 instructionSets, null, null, null, 0); 12424 this.cid = cid; 12425 setMountPath(PackageHelper.getSdDir(cid)); 12426 } 12427 12428 void createCopyFile() { 12429 cid = mInstallerService.allocateExternalStageCidLegacy(); 12430 } 12431 12432 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12433 if (origin.staged && origin.cid != null) { 12434 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12435 cid = origin.cid; 12436 setMountPath(PackageHelper.getSdDir(cid)); 12437 return PackageManager.INSTALL_SUCCEEDED; 12438 } 12439 12440 if (temp) { 12441 createCopyFile(); 12442 } else { 12443 /* 12444 * Pre-emptively destroy the container since it's destroyed if 12445 * copying fails due to it existing anyway. 12446 */ 12447 PackageHelper.destroySdDir(cid); 12448 } 12449 12450 final String newMountPath = imcs.copyPackageToContainer( 12451 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12452 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12453 12454 if (newMountPath != null) { 12455 setMountPath(newMountPath); 12456 return PackageManager.INSTALL_SUCCEEDED; 12457 } else { 12458 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12459 } 12460 } 12461 12462 @Override 12463 String getCodePath() { 12464 return packagePath; 12465 } 12466 12467 @Override 12468 String getResourcePath() { 12469 return resourcePath; 12470 } 12471 12472 int doPreInstall(int status) { 12473 if (status != PackageManager.INSTALL_SUCCEEDED) { 12474 // Destroy container 12475 PackageHelper.destroySdDir(cid); 12476 } else { 12477 boolean mounted = PackageHelper.isContainerMounted(cid); 12478 if (!mounted) { 12479 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12480 Process.SYSTEM_UID); 12481 if (newMountPath != null) { 12482 setMountPath(newMountPath); 12483 } else { 12484 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12485 } 12486 } 12487 } 12488 return status; 12489 } 12490 12491 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12492 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12493 String newMountPath = null; 12494 if (PackageHelper.isContainerMounted(cid)) { 12495 // Unmount the container 12496 if (!PackageHelper.unMountSdDir(cid)) { 12497 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12498 return false; 12499 } 12500 } 12501 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12502 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12503 " which might be stale. Will try to clean up."); 12504 // Clean up the stale container and proceed to recreate. 12505 if (!PackageHelper.destroySdDir(newCacheId)) { 12506 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12507 return false; 12508 } 12509 // Successfully cleaned up stale container. Try to rename again. 12510 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12511 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12512 + " inspite of cleaning it up."); 12513 return false; 12514 } 12515 } 12516 if (!PackageHelper.isContainerMounted(newCacheId)) { 12517 Slog.w(TAG, "Mounting container " + newCacheId); 12518 newMountPath = PackageHelper.mountSdDir(newCacheId, 12519 getEncryptKey(), Process.SYSTEM_UID); 12520 } else { 12521 newMountPath = PackageHelper.getSdDir(newCacheId); 12522 } 12523 if (newMountPath == null) { 12524 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12525 return false; 12526 } 12527 Log.i(TAG, "Succesfully renamed " + cid + 12528 " to " + newCacheId + 12529 " at new path: " + newMountPath); 12530 cid = newCacheId; 12531 12532 final File beforeCodeFile = new File(packagePath); 12533 setMountPath(newMountPath); 12534 final File afterCodeFile = new File(packagePath); 12535 12536 // Reflect the rename in scanned details 12537 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12538 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12539 afterCodeFile, pkg.baseCodePath)); 12540 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12541 afterCodeFile, pkg.splitCodePaths)); 12542 12543 // Reflect the rename in app info 12544 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12545 pkg.setApplicationInfoCodePath(pkg.codePath); 12546 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12547 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12548 pkg.setApplicationInfoResourcePath(pkg.codePath); 12549 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12550 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12551 12552 return true; 12553 } 12554 12555 private void setMountPath(String mountPath) { 12556 final File mountFile = new File(mountPath); 12557 12558 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12559 if (monolithicFile.exists()) { 12560 packagePath = monolithicFile.getAbsolutePath(); 12561 if (isFwdLocked()) { 12562 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12563 } else { 12564 resourcePath = packagePath; 12565 } 12566 } else { 12567 packagePath = mountFile.getAbsolutePath(); 12568 resourcePath = packagePath; 12569 } 12570 } 12571 12572 int doPostInstall(int status, int uid) { 12573 if (status != PackageManager.INSTALL_SUCCEEDED) { 12574 cleanUp(); 12575 } else { 12576 final int groupOwner; 12577 final String protectedFile; 12578 if (isFwdLocked()) { 12579 groupOwner = UserHandle.getSharedAppGid(uid); 12580 protectedFile = RES_FILE_NAME; 12581 } else { 12582 groupOwner = -1; 12583 protectedFile = null; 12584 } 12585 12586 if (uid < Process.FIRST_APPLICATION_UID 12587 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12588 Slog.e(TAG, "Failed to finalize " + cid); 12589 PackageHelper.destroySdDir(cid); 12590 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12591 } 12592 12593 boolean mounted = PackageHelper.isContainerMounted(cid); 12594 if (!mounted) { 12595 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12596 } 12597 } 12598 return status; 12599 } 12600 12601 private void cleanUp() { 12602 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12603 12604 // Destroy secure container 12605 PackageHelper.destroySdDir(cid); 12606 } 12607 12608 private List<String> getAllCodePaths() { 12609 final File codeFile = new File(getCodePath()); 12610 if (codeFile != null && codeFile.exists()) { 12611 try { 12612 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12613 return pkg.getAllCodePaths(); 12614 } catch (PackageParserException e) { 12615 // Ignored; we tried our best 12616 } 12617 } 12618 return Collections.EMPTY_LIST; 12619 } 12620 12621 void cleanUpResourcesLI() { 12622 // Enumerate all code paths before deleting 12623 cleanUpResourcesLI(getAllCodePaths()); 12624 } 12625 12626 private void cleanUpResourcesLI(List<String> allCodePaths) { 12627 cleanUp(); 12628 removeDexFiles(allCodePaths, instructionSets); 12629 } 12630 12631 String getPackageName() { 12632 return getAsecPackageName(cid); 12633 } 12634 12635 boolean doPostDeleteLI(boolean delete) { 12636 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12637 final List<String> allCodePaths = getAllCodePaths(); 12638 boolean mounted = PackageHelper.isContainerMounted(cid); 12639 if (mounted) { 12640 // Unmount first 12641 if (PackageHelper.unMountSdDir(cid)) { 12642 mounted = false; 12643 } 12644 } 12645 if (!mounted && delete) { 12646 cleanUpResourcesLI(allCodePaths); 12647 } 12648 return !mounted; 12649 } 12650 12651 @Override 12652 int doPreCopy() { 12653 if (isFwdLocked()) { 12654 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12655 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12656 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12657 } 12658 } 12659 12660 return PackageManager.INSTALL_SUCCEEDED; 12661 } 12662 12663 @Override 12664 int doPostCopy(int uid) { 12665 if (isFwdLocked()) { 12666 if (uid < Process.FIRST_APPLICATION_UID 12667 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12668 RES_FILE_NAME)) { 12669 Slog.e(TAG, "Failed to finalize " + cid); 12670 PackageHelper.destroySdDir(cid); 12671 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12672 } 12673 } 12674 12675 return PackageManager.INSTALL_SUCCEEDED; 12676 } 12677 } 12678 12679 /** 12680 * Logic to handle movement of existing installed applications. 12681 */ 12682 class MoveInstallArgs extends InstallArgs { 12683 private File codeFile; 12684 private File resourceFile; 12685 12686 /** New install */ 12687 MoveInstallArgs(InstallParams params) { 12688 super(params.origin, params.move, params.observer, params.installFlags, 12689 params.installerPackageName, params.volumeUuid, 12690 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12691 params.grantedRuntimePermissions, 12692 params.traceMethod, params.traceCookie); 12693 } 12694 12695 int copyApk(IMediaContainerService imcs, boolean temp) { 12696 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12697 + move.fromUuid + " to " + move.toUuid); 12698 synchronized (mInstaller) { 12699 try { 12700 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12701 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12702 } catch (InstallerException e) { 12703 Slog.w(TAG, "Failed to move app", e); 12704 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12705 } 12706 } 12707 12708 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12709 resourceFile = codeFile; 12710 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12711 12712 return PackageManager.INSTALL_SUCCEEDED; 12713 } 12714 12715 int doPreInstall(int status) { 12716 if (status != PackageManager.INSTALL_SUCCEEDED) { 12717 cleanUp(move.toUuid); 12718 } 12719 return status; 12720 } 12721 12722 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12723 if (status != PackageManager.INSTALL_SUCCEEDED) { 12724 cleanUp(move.toUuid); 12725 return false; 12726 } 12727 12728 // Reflect the move in app info 12729 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12730 pkg.setApplicationInfoCodePath(pkg.codePath); 12731 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12732 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12733 pkg.setApplicationInfoResourcePath(pkg.codePath); 12734 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12735 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12736 12737 return true; 12738 } 12739 12740 int doPostInstall(int status, int uid) { 12741 if (status == PackageManager.INSTALL_SUCCEEDED) { 12742 cleanUp(move.fromUuid); 12743 } else { 12744 cleanUp(move.toUuid); 12745 } 12746 return status; 12747 } 12748 12749 @Override 12750 String getCodePath() { 12751 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12752 } 12753 12754 @Override 12755 String getResourcePath() { 12756 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12757 } 12758 12759 private boolean cleanUp(String volumeUuid) { 12760 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12761 move.dataAppName); 12762 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12763 synchronized (mInstallLock) { 12764 // Clean up both app data and code 12765 removeDataDirsLI(volumeUuid, move.packageName); 12766 removeCodePathLI(codeFile); 12767 } 12768 return true; 12769 } 12770 12771 void cleanUpResourcesLI() { 12772 throw new UnsupportedOperationException(); 12773 } 12774 12775 boolean doPostDeleteLI(boolean delete) { 12776 throw new UnsupportedOperationException(); 12777 } 12778 } 12779 12780 static String getAsecPackageName(String packageCid) { 12781 int idx = packageCid.lastIndexOf("-"); 12782 if (idx == -1) { 12783 return packageCid; 12784 } 12785 return packageCid.substring(0, idx); 12786 } 12787 12788 // Utility method used to create code paths based on package name and available index. 12789 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12790 String idxStr = ""; 12791 int idx = 1; 12792 // Fall back to default value of idx=1 if prefix is not 12793 // part of oldCodePath 12794 if (oldCodePath != null) { 12795 String subStr = oldCodePath; 12796 // Drop the suffix right away 12797 if (suffix != null && subStr.endsWith(suffix)) { 12798 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12799 } 12800 // If oldCodePath already contains prefix find out the 12801 // ending index to either increment or decrement. 12802 int sidx = subStr.lastIndexOf(prefix); 12803 if (sidx != -1) { 12804 subStr = subStr.substring(sidx + prefix.length()); 12805 if (subStr != null) { 12806 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12807 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12808 } 12809 try { 12810 idx = Integer.parseInt(subStr); 12811 if (idx <= 1) { 12812 idx++; 12813 } else { 12814 idx--; 12815 } 12816 } catch(NumberFormatException e) { 12817 } 12818 } 12819 } 12820 } 12821 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12822 return prefix + idxStr; 12823 } 12824 12825 private File getNextCodePath(File targetDir, String packageName) { 12826 int suffix = 1; 12827 File result; 12828 do { 12829 result = new File(targetDir, packageName + "-" + suffix); 12830 suffix++; 12831 } while (result.exists()); 12832 return result; 12833 } 12834 12835 // Utility method that returns the relative package path with respect 12836 // to the installation directory. Like say for /data/data/com.test-1.apk 12837 // string com.test-1 is returned. 12838 static String deriveCodePathName(String codePath) { 12839 if (codePath == null) { 12840 return null; 12841 } 12842 final File codeFile = new File(codePath); 12843 final String name = codeFile.getName(); 12844 if (codeFile.isDirectory()) { 12845 return name; 12846 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12847 final int lastDot = name.lastIndexOf('.'); 12848 return name.substring(0, lastDot); 12849 } else { 12850 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12851 return null; 12852 } 12853 } 12854 12855 static class PackageInstalledInfo { 12856 String name; 12857 int uid; 12858 // The set of users that originally had this package installed. 12859 int[] origUsers; 12860 // The set of users that now have this package installed. 12861 int[] newUsers; 12862 PackageParser.Package pkg; 12863 int returnCode; 12864 String returnMsg; 12865 PackageRemovedInfo removedInfo; 12866 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12867 12868 public void setError(int code, String msg) { 12869 setReturnCode(code); 12870 setReturnMessage(msg); 12871 Slog.w(TAG, msg); 12872 } 12873 12874 public void setError(String msg, PackageParserException e) { 12875 setReturnCode(e.error); 12876 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12877 Slog.w(TAG, msg, e); 12878 } 12879 12880 public void setError(String msg, PackageManagerException e) { 12881 returnCode = e.error; 12882 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12883 Slog.w(TAG, msg, e); 12884 } 12885 12886 public void setReturnCode(int returnCode) { 12887 this.returnCode = returnCode; 12888 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12889 for (int i = 0; i < childCount; i++) { 12890 addedChildPackages.valueAt(i).returnCode = returnCode; 12891 } 12892 } 12893 12894 private void setReturnMessage(String returnMsg) { 12895 this.returnMsg = returnMsg; 12896 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12897 for (int i = 0; i < childCount; i++) { 12898 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12899 } 12900 } 12901 12902 // In some error cases we want to convey more info back to the observer 12903 String origPackage; 12904 String origPermission; 12905 } 12906 12907 /* 12908 * Install a non-existing package. 12909 */ 12910 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12911 UserHandle user, String installerPackageName, String volumeUuid, 12912 PackageInstalledInfo res) { 12913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12914 12915 // Remember this for later, in case we need to rollback this install 12916 String pkgName = pkg.packageName; 12917 12918 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12919 12920 synchronized(mPackages) { 12921 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12922 // A package with the same name is already installed, though 12923 // it has been renamed to an older name. The package we 12924 // are trying to install should be installed as an update to 12925 // the existing one, but that has not been requested, so bail. 12926 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12927 + " without first uninstalling package running as " 12928 + mSettings.mRenamedPackages.get(pkgName)); 12929 return; 12930 } 12931 if (mPackages.containsKey(pkgName)) { 12932 // Don't allow installation over an existing package with the same name. 12933 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12934 + " without first uninstalling."); 12935 return; 12936 } 12937 } 12938 12939 try { 12940 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12941 System.currentTimeMillis(), user); 12942 12943 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12944 12945 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12946 prepareAppDataAfterInstall(newPackage); 12947 12948 } else { 12949 // Remove package from internal structures, but keep around any 12950 // data that might have already existed 12951 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12952 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12953 } 12954 } catch (PackageManagerException e) { 12955 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12956 } 12957 12958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12959 } 12960 12961 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12962 // Can't rotate keys during boot or if sharedUser. 12963 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12964 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12965 return false; 12966 } 12967 // app is using upgradeKeySets; make sure all are valid 12968 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12969 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12970 for (int i = 0; i < upgradeKeySets.length; i++) { 12971 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12972 Slog.wtf(TAG, "Package " 12973 + (oldPs.name != null ? oldPs.name : "<null>") 12974 + " contains upgrade-key-set reference to unknown key-set: " 12975 + upgradeKeySets[i] 12976 + " reverting to signatures check."); 12977 return false; 12978 } 12979 } 12980 return true; 12981 } 12982 12983 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12984 // Upgrade keysets are being used. Determine if new package has a superset of the 12985 // required keys. 12986 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12987 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12988 for (int i = 0; i < upgradeKeySets.length; i++) { 12989 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12990 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12991 return true; 12992 } 12993 } 12994 return false; 12995 } 12996 12997 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12998 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 12999 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13000 13001 final PackageParser.Package oldPackage; 13002 final String pkgName = pkg.packageName; 13003 final int[] allUsers; 13004 13005 // First find the old package info and check signatures 13006 synchronized(mPackages) { 13007 oldPackage = mPackages.get(pkgName); 13008 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13009 if (isEphemeral && !oldIsEphemeral) { 13010 // can't downgrade from full to ephemeral 13011 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13012 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13013 return; 13014 } 13015 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13016 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13017 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13018 if (!checkUpgradeKeySetLP(ps, pkg)) { 13019 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13020 "New package not signed by keys specified by upgrade-keysets: " 13021 + pkgName); 13022 return; 13023 } 13024 } else { 13025 // default to original signature matching 13026 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13027 != PackageManager.SIGNATURE_MATCH) { 13028 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13029 "New package has a different signature: " + pkgName); 13030 return; 13031 } 13032 } 13033 13034 // In case of rollback, remember per-user/profile install state 13035 allUsers = sUserManager.getUserIds(); 13036 } 13037 13038 // Update what is removed 13039 res.removedInfo = new PackageRemovedInfo(); 13040 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13041 res.removedInfo.removedPackage = oldPackage.packageName; 13042 res.removedInfo.isUpdate = true; 13043 final int childCount = (oldPackage.childPackages != null) 13044 ? oldPackage.childPackages.size() : 0; 13045 for (int i = 0; i < childCount; i++) { 13046 boolean childPackageUpdated = false; 13047 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13048 if (res.addedChildPackages != null) { 13049 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13050 if (childRes != null) { 13051 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13052 childRes.removedInfo.removedPackage = childPkg.packageName; 13053 childRes.removedInfo.isUpdate = true; 13054 childPackageUpdated = true; 13055 } 13056 } 13057 if (!childPackageUpdated) { 13058 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13059 childRemovedRes.removedPackage = childPkg.packageName; 13060 childRemovedRes.isUpdate = false; 13061 childRemovedRes.dataRemoved = true; 13062 synchronized (mPackages) { 13063 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13064 if (childPs != null) { 13065 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13066 } 13067 } 13068 if (res.removedInfo.removedChildPackages == null) { 13069 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13070 } 13071 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13072 } 13073 } 13074 13075 boolean sysPkg = (isSystemApp(oldPackage)); 13076 if (sysPkg) { 13077 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13078 user, allUsers, installerPackageName, res); 13079 } else { 13080 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13081 user, allUsers, installerPackageName, res); 13082 } 13083 } 13084 13085 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13086 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13087 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13088 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13089 + deletedPackage); 13090 13091 String pkgName = deletedPackage.packageName; 13092 boolean deletedPkg = true; 13093 boolean addedPkg = false; 13094 13095 final long origUpdateTime = (pkg.mExtras != null) 13096 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13097 13098 // First delete the existing package while retaining the data directory 13099 if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13100 res.removedInfo, true, pkg)) { 13101 // If the existing package wasn't successfully deleted 13102 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13103 deletedPkg = false; 13104 } else { 13105 // Successfully deleted the old package; proceed with replace. 13106 13107 // If deleted package lived in a container, give users a chance to 13108 // relinquish resources before killing. 13109 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13110 if (DEBUG_INSTALL) { 13111 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13112 } 13113 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13114 final ArrayList<String> pkgList = new ArrayList<String>(1); 13115 pkgList.add(deletedPackage.applicationInfo.packageName); 13116 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13117 } 13118 13119 deleteCodeCacheDirsLI(pkg); 13120 13121 try { 13122 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13123 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13124 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13125 prepareAppDataAfterInstall(newPackage); 13126 addedPkg = true; 13127 } catch (PackageManagerException e) { 13128 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13129 } 13130 } 13131 13132 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13133 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13134 13135 // Revert all internal state mutations and added folders for the failed install 13136 if (addedPkg) { 13137 deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA, 13138 res.removedInfo, true, null); 13139 } 13140 13141 // Restore the old package 13142 if (deletedPkg) { 13143 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13144 File restoreFile = new File(deletedPackage.codePath); 13145 // Parse old package 13146 boolean oldExternal = isExternal(deletedPackage); 13147 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13148 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13149 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13150 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13151 try { 13152 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13153 null); 13154 } catch (PackageManagerException e) { 13155 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13156 + e.getMessage()); 13157 return; 13158 } 13159 13160 synchronized (mPackages) { 13161 // Ensure the installer package name up to date 13162 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13163 13164 // Update permissions for restored package 13165 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13166 13167 mSettings.writeLPr(); 13168 } 13169 13170 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13171 } 13172 } else { 13173 synchronized (mPackages) { 13174 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13175 if (ps != null) { 13176 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13177 if (res.removedInfo.removedChildPackages != null) { 13178 final int childCount = res.removedInfo.removedChildPackages.size(); 13179 // Iterate in reverse as we may modify the collection 13180 for (int i = childCount - 1; i >= 0; i--) { 13181 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13182 if (res.addedChildPackages.containsKey(childPackageName)) { 13183 res.removedInfo.removedChildPackages.removeAt(i); 13184 } else { 13185 PackageRemovedInfo childInfo = res.removedInfo 13186 .removedChildPackages.valueAt(i); 13187 childInfo.removedForAllUsers = mPackages.get( 13188 childInfo.removedPackage) == null; 13189 } 13190 } 13191 } 13192 } 13193 } 13194 } 13195 } 13196 13197 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13198 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13199 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13200 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13201 + ", old=" + deletedPackage); 13202 13203 final boolean disabledSystem; 13204 13205 // Set the system/privileged flags as needed 13206 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13207 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13208 != 0) { 13209 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13210 } 13211 13212 // Kill package processes including services, providers, etc. 13213 killPackage(deletedPackage, "replace sys pkg"); 13214 13215 // Remove existing system package 13216 removePackageLI(deletedPackage, true); 13217 13218 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13219 if (!disabledSystem) { 13220 // We didn't need to disable the .apk as a current system package, 13221 // which means we are replacing another update that is already 13222 // installed. We need to make sure to delete the older one's .apk. 13223 res.removedInfo.args = createInstallArgsForExisting(0, 13224 deletedPackage.applicationInfo.getCodePath(), 13225 deletedPackage.applicationInfo.getResourcePath(), 13226 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13227 } else { 13228 res.removedInfo.args = null; 13229 } 13230 13231 // Successfully disabled the old package. Now proceed with re-installation 13232 deleteCodeCacheDirsLI(pkg); 13233 13234 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13235 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13236 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13237 13238 PackageParser.Package newPackage = null; 13239 try { 13240 // Add the package to the internal data structures 13241 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13242 13243 // Set the update and install times 13244 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13245 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13246 System.currentTimeMillis()); 13247 13248 // Check for shared user id changes 13249 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13250 deletedPackage, newPackage); 13251 if (invalidPackageName != null) { 13252 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13253 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13254 + " to " + invalidPackageName); 13255 } 13256 13257 // Update the package dynamic state if succeeded 13258 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13259 // Now that the install succeeded make sure we remove data 13260 // directories for any child package the update removed. 13261 final int deletedChildCount = (deletedPackage.childPackages != null) 13262 ? deletedPackage.childPackages.size() : 0; 13263 final int newChildCount = (newPackage.childPackages != null) 13264 ? newPackage.childPackages.size() : 0; 13265 for (int i = 0; i < deletedChildCount; i++) { 13266 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13267 boolean childPackageDeleted = true; 13268 for (int j = 0; j < newChildCount; j++) { 13269 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13270 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13271 childPackageDeleted = false; 13272 break; 13273 } 13274 } 13275 if (childPackageDeleted) { 13276 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13277 deletedChildPkg.packageName); 13278 if (ps != null && res.removedInfo.removedChildPackages != null) { 13279 PackageRemovedInfo removedChildRes = res.removedInfo 13280 .removedChildPackages.get(deletedChildPkg.packageName); 13281 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13282 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13283 } 13284 } 13285 } 13286 13287 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13288 prepareAppDataAfterInstall(newPackage); 13289 } 13290 } catch (PackageManagerException e) { 13291 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13292 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13293 } 13294 13295 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13296 // Re installation failed. Restore old information 13297 // Remove new pkg information 13298 if (newPackage != null) { 13299 removeInstalledPackageLI(newPackage, true); 13300 } 13301 // Add back the old system package 13302 try { 13303 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13304 } catch (PackageManagerException e) { 13305 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13306 } 13307 13308 synchronized (mPackages) { 13309 if (disabledSystem) { 13310 enableSystemPackageLPw(deletedPackage); 13311 } 13312 13313 // Ensure the installer package name up to date 13314 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13315 13316 // Update permissions for restored package 13317 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13318 13319 mSettings.writeLPr(); 13320 } 13321 13322 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13323 + " after failed upgrade"); 13324 } 13325 } 13326 13327 /** 13328 * Checks whether the parent or any of the child packages have a change shared 13329 * user. For a package to be a valid update the shred users of the parent and 13330 * the children should match. We may later support changing child shared users. 13331 * @param oldPkg The updated package. 13332 * @param newPkg The update package. 13333 * @return The shared user that change between the versions. 13334 */ 13335 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13336 PackageParser.Package newPkg) { 13337 // Check parent shared user 13338 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13339 return newPkg.packageName; 13340 } 13341 // Check child shared users 13342 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13343 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13344 for (int i = 0; i < newChildCount; i++) { 13345 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13346 // If this child was present, did it have the same shared user? 13347 for (int j = 0; j < oldChildCount; j++) { 13348 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13349 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13350 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13351 return newChildPkg.packageName; 13352 } 13353 } 13354 } 13355 return null; 13356 } 13357 13358 private void removeNativeBinariesLI(PackageSetting ps) { 13359 // Remove the lib path for the parent package 13360 if (ps != null) { 13361 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13362 // Remove the lib path for the child packages 13363 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13364 for (int i = 0; i < childCount; i++) { 13365 PackageSetting childPs = null; 13366 synchronized (mPackages) { 13367 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13368 } 13369 if (childPs != null) { 13370 NativeLibraryHelper.removeNativeBinariesLI(childPs 13371 .legacyNativeLibraryPathString); 13372 } 13373 } 13374 } 13375 } 13376 13377 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13378 // Enable the parent package 13379 mSettings.enableSystemPackageLPw(pkg.packageName); 13380 // Enable the child packages 13381 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13382 for (int i = 0; i < childCount; i++) { 13383 PackageParser.Package childPkg = pkg.childPackages.get(i); 13384 mSettings.enableSystemPackageLPw(childPkg.packageName); 13385 } 13386 } 13387 13388 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13389 PackageParser.Package newPkg) { 13390 // Disable the parent package (parent always replaced) 13391 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13392 // Disable the child packages 13393 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13394 for (int i = 0; i < childCount; i++) { 13395 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13396 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13397 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13398 } 13399 return disabled; 13400 } 13401 13402 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13403 String installerPackageName) { 13404 // Enable the parent package 13405 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13406 // Enable the child packages 13407 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13408 for (int i = 0; i < childCount; i++) { 13409 PackageParser.Package childPkg = pkg.childPackages.get(i); 13410 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13411 } 13412 } 13413 13414 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13415 // Collect all used permissions in the UID 13416 ArraySet<String> usedPermissions = new ArraySet<>(); 13417 final int packageCount = su.packages.size(); 13418 for (int i = 0; i < packageCount; i++) { 13419 PackageSetting ps = su.packages.valueAt(i); 13420 if (ps.pkg == null) { 13421 continue; 13422 } 13423 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13424 for (int j = 0; j < requestedPermCount; j++) { 13425 String permission = ps.pkg.requestedPermissions.get(j); 13426 BasePermission bp = mSettings.mPermissions.get(permission); 13427 if (bp != null) { 13428 usedPermissions.add(permission); 13429 } 13430 } 13431 } 13432 13433 PermissionsState permissionsState = su.getPermissionsState(); 13434 // Prune install permissions 13435 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13436 final int installPermCount = installPermStates.size(); 13437 for (int i = installPermCount - 1; i >= 0; i--) { 13438 PermissionState permissionState = installPermStates.get(i); 13439 if (!usedPermissions.contains(permissionState.getName())) { 13440 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13441 if (bp != null) { 13442 permissionsState.revokeInstallPermission(bp); 13443 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13444 PackageManager.MASK_PERMISSION_FLAGS, 0); 13445 } 13446 } 13447 } 13448 13449 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13450 13451 // Prune runtime permissions 13452 for (int userId : allUserIds) { 13453 List<PermissionState> runtimePermStates = permissionsState 13454 .getRuntimePermissionStates(userId); 13455 final int runtimePermCount = runtimePermStates.size(); 13456 for (int i = runtimePermCount - 1; i >= 0; i--) { 13457 PermissionState permissionState = runtimePermStates.get(i); 13458 if (!usedPermissions.contains(permissionState.getName())) { 13459 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13460 if (bp != null) { 13461 permissionsState.revokeRuntimePermission(bp, userId); 13462 permissionsState.updatePermissionFlags(bp, userId, 13463 PackageManager.MASK_PERMISSION_FLAGS, 0); 13464 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13465 runtimePermissionChangedUserIds, userId); 13466 } 13467 } 13468 } 13469 } 13470 13471 return runtimePermissionChangedUserIds; 13472 } 13473 13474 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13475 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13476 // Update the parent package setting 13477 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13478 res, user); 13479 // Update the child packages setting 13480 final int childCount = (newPackage.childPackages != null) 13481 ? newPackage.childPackages.size() : 0; 13482 for (int i = 0; i < childCount; i++) { 13483 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13484 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13485 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13486 childRes.origUsers, childRes, user); 13487 } 13488 } 13489 13490 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13491 String installerPackageName, int[] allUsers, int[] installedForUsers, 13492 PackageInstalledInfo res, UserHandle user) { 13493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13494 13495 String pkgName = newPackage.packageName; 13496 synchronized (mPackages) { 13497 //write settings. the installStatus will be incomplete at this stage. 13498 //note that the new package setting would have already been 13499 //added to mPackages. It hasn't been persisted yet. 13500 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13502 mSettings.writeLPr(); 13503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13504 } 13505 13506 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13507 synchronized (mPackages) { 13508 updatePermissionsLPw(newPackage.packageName, newPackage, 13509 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13510 ? UPDATE_PERMISSIONS_ALL : 0)); 13511 // For system-bundled packages, we assume that installing an upgraded version 13512 // of the package implies that the user actually wants to run that new code, 13513 // so we enable the package. 13514 PackageSetting ps = mSettings.mPackages.get(pkgName); 13515 final int userId = user.getIdentifier(); 13516 if (ps != null) { 13517 if (isSystemApp(newPackage)) { 13518 if (DEBUG_INSTALL) { 13519 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13520 } 13521 // Enable system package for requested users 13522 if (res.origUsers != null) { 13523 for (int origUserId : res.origUsers) { 13524 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13525 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13526 origUserId, installerPackageName); 13527 } 13528 } 13529 } 13530 // Also convey the prior install/uninstall state 13531 if (allUsers != null && installedForUsers != null) { 13532 for (int currentUserId : allUsers) { 13533 final boolean installed = ArrayUtils.contains( 13534 installedForUsers, currentUserId); 13535 if (DEBUG_INSTALL) { 13536 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13537 } 13538 ps.setInstalled(installed, currentUserId); 13539 } 13540 // these install state changes will be persisted in the 13541 // upcoming call to mSettings.writeLPr(). 13542 } 13543 } 13544 // It's implied that when a user requests installation, they want the app to be 13545 // installed and enabled. 13546 if (userId != UserHandle.USER_ALL) { 13547 ps.setInstalled(true, userId); 13548 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13549 } 13550 } 13551 res.name = pkgName; 13552 res.uid = newPackage.applicationInfo.uid; 13553 res.pkg = newPackage; 13554 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13555 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13556 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13557 //to update install status 13558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13559 mSettings.writeLPr(); 13560 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13561 } 13562 13563 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13564 } 13565 13566 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13567 try { 13568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13569 installPackageLI(args, res); 13570 } finally { 13571 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13572 } 13573 } 13574 13575 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13576 final int installFlags = args.installFlags; 13577 final String installerPackageName = args.installerPackageName; 13578 final String volumeUuid = args.volumeUuid; 13579 final File tmpPackageFile = new File(args.getCodePath()); 13580 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13581 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13582 || (args.volumeUuid != null)); 13583 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13584 boolean replace = false; 13585 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13586 if (args.move != null) { 13587 // moving a complete application; perform an initial scan on the new install location 13588 scanFlags |= SCAN_INITIAL; 13589 } 13590 13591 // Result object to be returned 13592 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13593 13594 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13595 13596 // Sanity check 13597 if (ephemeral && (forwardLocked || onExternal)) { 13598 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13599 + " external=" + onExternal); 13600 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13601 return; 13602 } 13603 13604 // Retrieve PackageSettings and parse package 13605 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13606 | PackageParser.PARSE_ENFORCE_CODE 13607 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13608 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13609 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13610 PackageParser pp = new PackageParser(); 13611 pp.setSeparateProcesses(mSeparateProcesses); 13612 pp.setDisplayMetrics(mMetrics); 13613 13614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13615 final PackageParser.Package pkg; 13616 try { 13617 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13618 } catch (PackageParserException e) { 13619 res.setError("Failed parse during installPackageLI", e); 13620 return; 13621 } finally { 13622 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13623 } 13624 13625 // If we are installing a clustered package add results for the children 13626 if (pkg.childPackages != null) { 13627 synchronized (mPackages) { 13628 final int childCount = pkg.childPackages.size(); 13629 for (int i = 0; i < childCount; i++) { 13630 PackageParser.Package childPkg = pkg.childPackages.get(i); 13631 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13632 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13633 childRes.pkg = childPkg; 13634 childRes.name = childPkg.packageName; 13635 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13636 if (childPs != null) { 13637 childRes.origUsers = childPs.queryInstalledUsers( 13638 sUserManager.getUserIds(), true); 13639 } 13640 if ((mPackages.containsKey(childPkg.packageName))) { 13641 childRes.removedInfo = new PackageRemovedInfo(); 13642 childRes.removedInfo.removedPackage = childPkg.packageName; 13643 } 13644 if (res.addedChildPackages == null) { 13645 res.addedChildPackages = new ArrayMap<>(); 13646 } 13647 res.addedChildPackages.put(childPkg.packageName, childRes); 13648 } 13649 } 13650 } 13651 13652 // If package doesn't declare API override, mark that we have an install 13653 // time CPU ABI override. 13654 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13655 pkg.cpuAbiOverride = args.abiOverride; 13656 } 13657 13658 String pkgName = res.name = pkg.packageName; 13659 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13660 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13661 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13662 return; 13663 } 13664 } 13665 13666 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13667 try { 13668 PackageParser.collectCertificates(pkg, parseFlags); 13669 } catch (PackageParserException e) { 13670 res.setError("Failed collect during installPackageLI", e); 13671 return; 13672 } finally { 13673 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13674 } 13675 13676 // Get rid of all references to package scan path via parser. 13677 pp = null; 13678 String oldCodePath = null; 13679 boolean systemApp = false; 13680 synchronized (mPackages) { 13681 // Check if installing already existing package 13682 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13683 String oldName = mSettings.mRenamedPackages.get(pkgName); 13684 if (pkg.mOriginalPackages != null 13685 && pkg.mOriginalPackages.contains(oldName) 13686 && mPackages.containsKey(oldName)) { 13687 // This package is derived from an original package, 13688 // and this device has been updating from that original 13689 // name. We must continue using the original name, so 13690 // rename the new package here. 13691 pkg.setPackageName(oldName); 13692 pkgName = pkg.packageName; 13693 replace = true; 13694 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13695 + oldName + " pkgName=" + pkgName); 13696 } else if (mPackages.containsKey(pkgName)) { 13697 // This package, under its official name, already exists 13698 // on the device; we should replace it. 13699 replace = true; 13700 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13701 } 13702 13703 // Child packages are installed through the parent package 13704 if (pkg.parentPackage != null) { 13705 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13706 "Package " + pkg.packageName + " is child of package " 13707 + pkg.parentPackage.parentPackage + ". Child packages " 13708 + "can be updated only through the parent package."); 13709 return; 13710 } 13711 13712 if (replace) { 13713 // Prevent apps opting out from runtime permissions 13714 PackageParser.Package oldPackage = mPackages.get(pkgName); 13715 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13716 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13717 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13718 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13719 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13720 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13721 + " doesn't support runtime permissions but the old" 13722 + " target SDK " + oldTargetSdk + " does."); 13723 return; 13724 } 13725 13726 // Prevent installing of child packages 13727 if (oldPackage.parentPackage != null) { 13728 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13729 "Package " + pkg.packageName + " is child of package " 13730 + oldPackage.parentPackage + ". Child packages " 13731 + "can be updated only through the parent package."); 13732 return; 13733 } 13734 } 13735 } 13736 13737 PackageSetting ps = mSettings.mPackages.get(pkgName); 13738 if (ps != null) { 13739 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13740 13741 // Quick sanity check that we're signed correctly if updating; 13742 // we'll check this again later when scanning, but we want to 13743 // bail early here before tripping over redefined permissions. 13744 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13745 if (!checkUpgradeKeySetLP(ps, pkg)) { 13746 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13747 + pkg.packageName + " upgrade keys do not match the " 13748 + "previously installed version"); 13749 return; 13750 } 13751 } else { 13752 try { 13753 verifySignaturesLP(ps, pkg); 13754 } catch (PackageManagerException e) { 13755 res.setError(e.error, e.getMessage()); 13756 return; 13757 } 13758 } 13759 13760 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13761 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13762 systemApp = (ps.pkg.applicationInfo.flags & 13763 ApplicationInfo.FLAG_SYSTEM) != 0; 13764 } 13765 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13766 } 13767 13768 // Check whether the newly-scanned package wants to define an already-defined perm 13769 int N = pkg.permissions.size(); 13770 for (int i = N-1; i >= 0; i--) { 13771 PackageParser.Permission perm = pkg.permissions.get(i); 13772 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13773 if (bp != null) { 13774 // If the defining package is signed with our cert, it's okay. This 13775 // also includes the "updating the same package" case, of course. 13776 // "updating same package" could also involve key-rotation. 13777 final boolean sigsOk; 13778 if (bp.sourcePackage.equals(pkg.packageName) 13779 && (bp.packageSetting instanceof PackageSetting) 13780 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13781 scanFlags))) { 13782 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13783 } else { 13784 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13785 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13786 } 13787 if (!sigsOk) { 13788 // If the owning package is the system itself, we log but allow 13789 // install to proceed; we fail the install on all other permission 13790 // redefinitions. 13791 if (!bp.sourcePackage.equals("android")) { 13792 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13793 + pkg.packageName + " attempting to redeclare permission " 13794 + perm.info.name + " already owned by " + bp.sourcePackage); 13795 res.origPermission = perm.info.name; 13796 res.origPackage = bp.sourcePackage; 13797 return; 13798 } else { 13799 Slog.w(TAG, "Package " + pkg.packageName 13800 + " attempting to redeclare system permission " 13801 + perm.info.name + "; ignoring new declaration"); 13802 pkg.permissions.remove(i); 13803 } 13804 } 13805 } 13806 } 13807 } 13808 13809 if (systemApp) { 13810 if (onExternal) { 13811 // Abort update; system app can't be replaced with app on sdcard 13812 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13813 "Cannot install updates to system apps on sdcard"); 13814 return; 13815 } else if (ephemeral) { 13816 // Abort update; system app can't be replaced with an ephemeral app 13817 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13818 "Cannot update a system app with an ephemeral app"); 13819 return; 13820 } 13821 } 13822 13823 if (args.move != null) { 13824 // We did an in-place move, so dex is ready to roll 13825 scanFlags |= SCAN_NO_DEX; 13826 scanFlags |= SCAN_MOVE; 13827 13828 synchronized (mPackages) { 13829 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13830 if (ps == null) { 13831 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13832 "Missing settings for moved package " + pkgName); 13833 } 13834 13835 // We moved the entire application as-is, so bring over the 13836 // previously derived ABI information. 13837 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13838 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13839 } 13840 13841 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13842 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13843 scanFlags |= SCAN_NO_DEX; 13844 13845 try { 13846 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13847 args.abiOverride : pkg.cpuAbiOverride); 13848 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13849 true /* extract libs */); 13850 } catch (PackageManagerException pme) { 13851 Slog.e(TAG, "Error deriving application ABI", pme); 13852 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13853 return; 13854 } 13855 13856 // Extract package to save the VM unzipping the APK in memory during 13857 // launch. Only do this if profile-guided compilation is enabled because 13858 // otherwise BackgroundDexOptService will not dexopt the package later. 13859 if (mUseJitProfiles) { 13860 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13861 // Do not run PackageDexOptimizer through the local performDexOpt 13862 // method because `pkg` is not in `mPackages` yet. 13863 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13864 false /* useProfiles */, true /* extractOnly */); 13865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13866 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13867 String msg = "Extracking package failed for " + pkgName; 13868 res.setError(INSTALL_FAILED_DEXOPT, msg); 13869 return; 13870 } 13871 } 13872 } 13873 13874 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13875 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13876 return; 13877 } 13878 13879 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13880 13881 if (replace) { 13882 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13883 installerPackageName, res); 13884 } else { 13885 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13886 args.user, installerPackageName, volumeUuid, res); 13887 } 13888 synchronized (mPackages) { 13889 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13890 if (ps != null) { 13891 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13892 } 13893 13894 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13895 for (int i = 0; i < childCount; i++) { 13896 PackageParser.Package childPkg = pkg.childPackages.get(i); 13897 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13898 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13899 if (childPs != null) { 13900 childRes.newUsers = childPs.queryInstalledUsers( 13901 sUserManager.getUserIds(), true); 13902 } 13903 } 13904 } 13905 } 13906 13907 private void startIntentFilterVerifications(int userId, boolean replacing, 13908 PackageParser.Package pkg) { 13909 if (mIntentFilterVerifierComponent == null) { 13910 Slog.w(TAG, "No IntentFilter verification will not be done as " 13911 + "there is no IntentFilterVerifier available!"); 13912 return; 13913 } 13914 13915 final int verifierUid = getPackageUid( 13916 mIntentFilterVerifierComponent.getPackageName(), 13917 MATCH_DEBUG_TRIAGED_MISSING, 13918 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13919 13920 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13921 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13922 mHandler.sendMessage(msg); 13923 13924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13925 for (int i = 0; i < childCount; i++) { 13926 PackageParser.Package childPkg = pkg.childPackages.get(i); 13927 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13928 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 13929 mHandler.sendMessage(msg); 13930 } 13931 } 13932 13933 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13934 PackageParser.Package pkg) { 13935 int size = pkg.activities.size(); 13936 if (size == 0) { 13937 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13938 "No activity, so no need to verify any IntentFilter!"); 13939 return; 13940 } 13941 13942 final boolean hasDomainURLs = hasDomainURLs(pkg); 13943 if (!hasDomainURLs) { 13944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13945 "No domain URLs, so no need to verify any IntentFilter!"); 13946 return; 13947 } 13948 13949 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13950 + " if any IntentFilter from the " + size 13951 + " Activities needs verification ..."); 13952 13953 int count = 0; 13954 final String packageName = pkg.packageName; 13955 13956 synchronized (mPackages) { 13957 // If this is a new install and we see that we've already run verification for this 13958 // package, we have nothing to do: it means the state was restored from backup. 13959 if (!replacing) { 13960 IntentFilterVerificationInfo ivi = 13961 mSettings.getIntentFilterVerificationLPr(packageName); 13962 if (ivi != null) { 13963 if (DEBUG_DOMAIN_VERIFICATION) { 13964 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13965 + ivi.getStatusString()); 13966 } 13967 return; 13968 } 13969 } 13970 13971 // If any filters need to be verified, then all need to be. 13972 boolean needToVerify = false; 13973 for (PackageParser.Activity a : pkg.activities) { 13974 for (ActivityIntentInfo filter : a.intents) { 13975 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13976 if (DEBUG_DOMAIN_VERIFICATION) { 13977 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13978 } 13979 needToVerify = true; 13980 break; 13981 } 13982 } 13983 } 13984 13985 if (needToVerify) { 13986 final int verificationId = mIntentFilterVerificationToken++; 13987 for (PackageParser.Activity a : pkg.activities) { 13988 for (ActivityIntentInfo filter : a.intents) { 13989 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13991 "Verification needed for IntentFilter:" + filter.toString()); 13992 mIntentFilterVerifier.addOneIntentFilterVerification( 13993 verifierUid, userId, verificationId, filter, packageName); 13994 count++; 13995 } 13996 } 13997 } 13998 } 13999 } 14000 14001 if (count > 0) { 14002 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14003 + " IntentFilter verification" + (count > 1 ? "s" : "") 14004 + " for userId:" + userId); 14005 mIntentFilterVerifier.startVerifications(userId); 14006 } else { 14007 if (DEBUG_DOMAIN_VERIFICATION) { 14008 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14009 } 14010 } 14011 } 14012 14013 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14014 final ComponentName cn = filter.activity.getComponentName(); 14015 final String packageName = cn.getPackageName(); 14016 14017 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14018 packageName); 14019 if (ivi == null) { 14020 return true; 14021 } 14022 int status = ivi.getStatus(); 14023 switch (status) { 14024 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14025 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14026 return true; 14027 14028 default: 14029 // Nothing to do 14030 return false; 14031 } 14032 } 14033 14034 private static boolean isMultiArch(ApplicationInfo info) { 14035 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14036 } 14037 14038 private static boolean isExternal(PackageParser.Package pkg) { 14039 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14040 } 14041 14042 private static boolean isExternal(PackageSetting ps) { 14043 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14044 } 14045 14046 private static boolean isEphemeral(PackageParser.Package pkg) { 14047 return pkg.applicationInfo.isEphemeralApp(); 14048 } 14049 14050 private static boolean isEphemeral(PackageSetting ps) { 14051 return ps.pkg != null && isEphemeral(ps.pkg); 14052 } 14053 14054 private static boolean isSystemApp(PackageParser.Package pkg) { 14055 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14056 } 14057 14058 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14059 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14060 } 14061 14062 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14063 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14064 } 14065 14066 private static boolean isSystemApp(PackageSetting ps) { 14067 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14068 } 14069 14070 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14071 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14072 } 14073 14074 private int packageFlagsToInstallFlags(PackageSetting ps) { 14075 int installFlags = 0; 14076 if (isEphemeral(ps)) { 14077 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14078 } 14079 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14080 // This existing package was an external ASEC install when we have 14081 // the external flag without a UUID 14082 installFlags |= PackageManager.INSTALL_EXTERNAL; 14083 } 14084 if (ps.isForwardLocked()) { 14085 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14086 } 14087 return installFlags; 14088 } 14089 14090 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14091 if (isExternal(pkg)) { 14092 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14093 return StorageManager.UUID_PRIMARY_PHYSICAL; 14094 } else { 14095 return pkg.volumeUuid; 14096 } 14097 } else { 14098 return StorageManager.UUID_PRIVATE_INTERNAL; 14099 } 14100 } 14101 14102 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14103 if (isExternal(pkg)) { 14104 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14105 return mSettings.getExternalVersion(); 14106 } else { 14107 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14108 } 14109 } else { 14110 return mSettings.getInternalVersion(); 14111 } 14112 } 14113 14114 private void deleteTempPackageFiles() { 14115 final FilenameFilter filter = new FilenameFilter() { 14116 public boolean accept(File dir, String name) { 14117 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14118 } 14119 }; 14120 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14121 file.delete(); 14122 } 14123 } 14124 14125 @Override 14126 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14127 int flags) { 14128 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14129 flags); 14130 } 14131 14132 @Override 14133 public void deletePackage(final String packageName, 14134 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14135 mContext.enforceCallingOrSelfPermission( 14136 android.Manifest.permission.DELETE_PACKAGES, null); 14137 Preconditions.checkNotNull(packageName); 14138 Preconditions.checkNotNull(observer); 14139 final int uid = Binder.getCallingUid(); 14140 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14141 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14142 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14143 mContext.enforceCallingOrSelfPermission( 14144 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14145 "deletePackage for user " + userId); 14146 } 14147 14148 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14149 try { 14150 observer.onPackageDeleted(packageName, 14151 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14152 } catch (RemoteException re) { 14153 } 14154 return; 14155 } 14156 14157 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14158 try { 14159 observer.onPackageDeleted(packageName, 14160 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14161 } catch (RemoteException re) { 14162 } 14163 return; 14164 } 14165 14166 if (DEBUG_REMOVE) { 14167 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14168 + " deleteAllUsers: " + deleteAllUsers ); 14169 } 14170 // Queue up an async operation since the package deletion may take a little while. 14171 mHandler.post(new Runnable() { 14172 public void run() { 14173 mHandler.removeCallbacks(this); 14174 int returnCode; 14175 if (!deleteAllUsers) { 14176 returnCode = deletePackageX(packageName, userId, flags); 14177 } else { 14178 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14179 // If nobody is blocking uninstall, proceed with delete for all users 14180 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14181 returnCode = deletePackageX(packageName, userId, flags); 14182 } else { 14183 // Otherwise uninstall individually for users with blockUninstalls=false 14184 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14185 for (int userId : users) { 14186 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14187 returnCode = deletePackageX(packageName, userId, userFlags); 14188 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14189 Slog.w(TAG, "Package delete failed for user " + userId 14190 + ", returnCode " + returnCode); 14191 } 14192 } 14193 } 14194 // The app has only been marked uninstalled for certain users. 14195 // We still need to report that delete was blocked 14196 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14197 } 14198 } 14199 try { 14200 observer.onPackageDeleted(packageName, returnCode, null); 14201 } catch (RemoteException e) { 14202 Log.i(TAG, "Observer no longer exists."); 14203 } //end catch 14204 } //end run 14205 }); 14206 } 14207 14208 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14209 int[] result = EMPTY_INT_ARRAY; 14210 for (int userId : userIds) { 14211 if (getBlockUninstallForUser(packageName, userId)) { 14212 result = ArrayUtils.appendInt(result, userId); 14213 } 14214 } 14215 return result; 14216 } 14217 14218 @Override 14219 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14220 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14221 } 14222 14223 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14224 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14225 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14226 try { 14227 if (dpm != null) { 14228 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14229 /* callingUserOnly =*/ false); 14230 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14231 : deviceOwnerComponentName.getPackageName(); 14232 // Does the package contains the device owner? 14233 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14234 // this check is probably not needed, since DO should be registered as a device 14235 // admin on some user too. (Original bug for this: b/17657954) 14236 if (packageName.equals(deviceOwnerPackageName)) { 14237 return true; 14238 } 14239 // Does it contain a device admin for any user? 14240 int[] users; 14241 if (userId == UserHandle.USER_ALL) { 14242 users = sUserManager.getUserIds(); 14243 } else { 14244 users = new int[]{userId}; 14245 } 14246 for (int i = 0; i < users.length; ++i) { 14247 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14248 return true; 14249 } 14250 } 14251 } 14252 } catch (RemoteException e) { 14253 } 14254 return false; 14255 } 14256 14257 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14258 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14259 } 14260 14261 /** 14262 * This method is an internal method that could be get invoked either 14263 * to delete an installed package or to clean up a failed installation. 14264 * After deleting an installed package, a broadcast is sent to notify any 14265 * listeners that the package has been installed. For cleaning up a failed 14266 * installation, the broadcast is not necessary since the package's 14267 * installation wouldn't have sent the initial broadcast either 14268 * The key steps in deleting a package are 14269 * deleting the package information in internal structures like mPackages, 14270 * deleting the packages base directories through installd 14271 * updating mSettings to reflect current status 14272 * persisting settings for later use 14273 * sending a broadcast if necessary 14274 */ 14275 private int deletePackageX(String packageName, int userId, int flags) { 14276 final PackageRemovedInfo info = new PackageRemovedInfo(); 14277 final boolean res; 14278 14279 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14280 ? UserHandle.ALL : new UserHandle(userId); 14281 14282 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14283 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14284 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14285 } 14286 14287 PackageSetting uninstalledPs = null; 14288 14289 // for the uninstall-updates case and restricted profiles, remember the per- 14290 // user handle installed state 14291 int[] allUsers; 14292 synchronized (mPackages) { 14293 uninstalledPs = mSettings.mPackages.get(packageName); 14294 if (uninstalledPs == null) { 14295 Slog.w(TAG, "Not removing non-existent package " + packageName); 14296 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14297 } 14298 allUsers = sUserManager.getUserIds(); 14299 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14300 } 14301 14302 synchronized (mInstallLock) { 14303 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14304 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14305 flags | REMOVE_CHATTY, info, true, null); 14306 synchronized (mPackages) { 14307 if (res) { 14308 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14309 } 14310 } 14311 } 14312 14313 if (res) { 14314 info.sendPackageRemovedBroadcasts(); 14315 info.sendSystemPackageUpdatedBroadcasts(); 14316 info.sendSystemPackageAppearedBroadcasts(); 14317 } 14318 // Force a gc here. 14319 Runtime.getRuntime().gc(); 14320 // Delete the resources here after sending the broadcast to let 14321 // other processes clean up before deleting resources. 14322 if (info.args != null) { 14323 synchronized (mInstallLock) { 14324 info.args.doPostDeleteLI(true); 14325 } 14326 } 14327 14328 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14329 } 14330 14331 class PackageRemovedInfo { 14332 String removedPackage; 14333 int uid = -1; 14334 int removedAppId = -1; 14335 int[] origUsers; 14336 int[] removedUsers = null; 14337 boolean isRemovedPackageSystemUpdate = false; 14338 boolean isUpdate; 14339 boolean dataRemoved; 14340 boolean removedForAllUsers; 14341 // Clean up resources deleted packages. 14342 InstallArgs args = null; 14343 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14344 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14345 14346 void sendPackageRemovedBroadcasts() { 14347 sendPackageRemovedBroadcastInternal(); 14348 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14349 for (int i = 0; i < childCount; i++) { 14350 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14351 childInfo.sendPackageRemovedBroadcastInternal(); 14352 } 14353 } 14354 14355 void sendSystemPackageUpdatedBroadcasts() { 14356 if (isRemovedPackageSystemUpdate) { 14357 sendSystemPackageUpdatedBroadcastsInternal(); 14358 final int childCount = (removedChildPackages != null) 14359 ? removedChildPackages.size() : 0; 14360 for (int i = 0; i < childCount; i++) { 14361 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14362 if (childInfo.isRemovedPackageSystemUpdate) { 14363 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14364 } 14365 } 14366 } 14367 } 14368 14369 void sendSystemPackageAppearedBroadcasts() { 14370 final int packageCount = (appearedChildPackages != null) 14371 ? appearedChildPackages.size() : 0; 14372 for (int i = 0; i < packageCount; i++) { 14373 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14374 for (int userId : installedInfo.newUsers) { 14375 sendPackageAddedForUser(installedInfo.name, true, 14376 UserHandle.getAppId(installedInfo.uid), userId); 14377 } 14378 } 14379 } 14380 14381 private void sendSystemPackageUpdatedBroadcastsInternal() { 14382 Bundle extras = new Bundle(2); 14383 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14384 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14385 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14386 extras, 0, null, null, null); 14387 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14388 extras, 0, null, null, null); 14389 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14390 null, 0, removedPackage, null, null); 14391 } 14392 14393 private void sendPackageRemovedBroadcastInternal() { 14394 Bundle extras = new Bundle(2); 14395 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14396 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14397 if (isUpdate || isRemovedPackageSystemUpdate) { 14398 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14399 } 14400 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14401 if (removedPackage != null) { 14402 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14403 extras, 0, null, null, removedUsers); 14404 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14405 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14406 removedPackage, extras, 0, null, null, removedUsers); 14407 } 14408 } 14409 if (removedAppId >= 0) { 14410 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14411 removedUsers); 14412 } 14413 } 14414 } 14415 14416 /* 14417 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14418 * flag is not set, the data directory is removed as well. 14419 * make sure this flag is set for partially installed apps. If not its meaningless to 14420 * delete a partially installed application. 14421 */ 14422 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14423 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14424 String packageName = ps.name; 14425 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14426 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14427 // Retrieve object to delete permissions for shared user later on 14428 final PackageSetting deletedPs; 14429 // reader 14430 synchronized (mPackages) { 14431 deletedPs = mSettings.mPackages.get(packageName); 14432 if (outInfo != null) { 14433 outInfo.removedPackage = packageName; 14434 outInfo.removedUsers = deletedPs != null 14435 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14436 : null; 14437 } 14438 } 14439 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14440 removeDataDirsLI(ps.volumeUuid, packageName); 14441 if (outInfo != null) { 14442 outInfo.dataRemoved = true; 14443 } 14444 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14445 } 14446 // writer 14447 synchronized (mPackages) { 14448 if (deletedPs != null) { 14449 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14450 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14451 clearDefaultBrowserIfNeeded(packageName); 14452 if (outInfo != null) { 14453 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14454 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14455 } 14456 updatePermissionsLPw(deletedPs.name, null, 0); 14457 if (deletedPs.sharedUser != null) { 14458 // Remove permissions associated with package. Since runtime 14459 // permissions are per user we have to kill the removed package 14460 // or packages running under the shared user of the removed 14461 // package if revoking the permissions requested only by the removed 14462 // package is successful and this causes a change in gids. 14463 for (int userId : UserManagerService.getInstance().getUserIds()) { 14464 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14465 userId); 14466 if (userIdToKill == UserHandle.USER_ALL 14467 || userIdToKill >= UserHandle.USER_SYSTEM) { 14468 // If gids changed for this user, kill all affected packages. 14469 mHandler.post(new Runnable() { 14470 @Override 14471 public void run() { 14472 // This has to happen with no lock held. 14473 killApplication(deletedPs.name, deletedPs.appId, 14474 KILL_APP_REASON_GIDS_CHANGED); 14475 } 14476 }); 14477 break; 14478 } 14479 } 14480 } 14481 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14482 } 14483 // make sure to preserve per-user disabled state if this removal was just 14484 // a downgrade of a system app to the factory package 14485 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14486 if (DEBUG_REMOVE) { 14487 Slog.d(TAG, "Propagating install state across downgrade"); 14488 } 14489 for (int userId : allUserHandles) { 14490 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14491 if (DEBUG_REMOVE) { 14492 Slog.d(TAG, " user " + userId + " => " + installed); 14493 } 14494 ps.setInstalled(installed, userId); 14495 } 14496 } 14497 } 14498 // can downgrade to reader 14499 if (writeSettings) { 14500 // Save settings now 14501 mSettings.writeLPr(); 14502 } 14503 } 14504 if (outInfo != null) { 14505 // A user ID was deleted here. Go through all users and remove it 14506 // from KeyStore. 14507 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14508 } 14509 } 14510 14511 static boolean locationIsPrivileged(File path) { 14512 try { 14513 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14514 .getCanonicalPath(); 14515 return path.getCanonicalPath().startsWith(privilegedAppDir); 14516 } catch (IOException e) { 14517 Slog.e(TAG, "Unable to access code path " + path); 14518 } 14519 return false; 14520 } 14521 14522 /* 14523 * Tries to delete system package. 14524 */ 14525 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14526 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14527 boolean writeSettings) { 14528 if (deletedPs.parentPackageName != null) { 14529 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14530 return false; 14531 } 14532 14533 final boolean applyUserRestrictions 14534 = (allUserHandles != null) && (outInfo.origUsers != null); 14535 final PackageSetting disabledPs; 14536 // Confirm if the system package has been updated 14537 // An updated system app can be deleted. This will also have to restore 14538 // the system pkg from system partition 14539 // reader 14540 synchronized (mPackages) { 14541 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14542 } 14543 14544 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14545 + " disabledPs=" + disabledPs); 14546 14547 if (disabledPs == null) { 14548 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14549 return false; 14550 } else if (DEBUG_REMOVE) { 14551 Slog.d(TAG, "Deleting system pkg from data partition"); 14552 } 14553 14554 if (DEBUG_REMOVE) { 14555 if (applyUserRestrictions) { 14556 Slog.d(TAG, "Remembering install states:"); 14557 for (int userId : allUserHandles) { 14558 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14559 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14560 } 14561 } 14562 } 14563 14564 // Delete the updated package 14565 outInfo.isRemovedPackageSystemUpdate = true; 14566 if (outInfo.removedChildPackages != null) { 14567 final int childCount = (deletedPs.childPackageNames != null) 14568 ? deletedPs.childPackageNames.size() : 0; 14569 for (int i = 0; i < childCount; i++) { 14570 String childPackageName = deletedPs.childPackageNames.get(i); 14571 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14572 .contains(childPackageName)) { 14573 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14574 childPackageName); 14575 if (childInfo != null) { 14576 childInfo.isRemovedPackageSystemUpdate = true; 14577 } 14578 } 14579 } 14580 } 14581 14582 if (disabledPs.versionCode < deletedPs.versionCode) { 14583 // Delete data for downgrades 14584 flags &= ~PackageManager.DELETE_KEEP_DATA; 14585 } else { 14586 // Preserve data by setting flag 14587 flags |= PackageManager.DELETE_KEEP_DATA; 14588 } 14589 14590 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14591 outInfo, writeSettings, disabledPs.pkg); 14592 if (!ret) { 14593 return false; 14594 } 14595 14596 // writer 14597 synchronized (mPackages) { 14598 // Reinstate the old system package 14599 enableSystemPackageLPw(disabledPs.pkg); 14600 // Remove any native libraries from the upgraded package. 14601 removeNativeBinariesLI(deletedPs); 14602 } 14603 14604 // Install the system package 14605 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14606 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14607 if (locationIsPrivileged(disabledPs.codePath)) { 14608 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14609 } 14610 14611 final PackageParser.Package newPkg; 14612 try { 14613 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14614 } catch (PackageManagerException e) { 14615 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14616 + e.getMessage()); 14617 return false; 14618 } 14619 14620 prepareAppDataAfterInstall(newPkg); 14621 14622 // writer 14623 synchronized (mPackages) { 14624 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14625 14626 // Propagate the permissions state as we do not want to drop on the floor 14627 // runtime permissions. The update permissions method below will take 14628 // care of removing obsolete permissions and grant install permissions. 14629 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14630 updatePermissionsLPw(newPkg.packageName, newPkg, 14631 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14632 14633 if (applyUserRestrictions) { 14634 if (DEBUG_REMOVE) { 14635 Slog.d(TAG, "Propagating install state across reinstall"); 14636 } 14637 for (int userId : allUserHandles) { 14638 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14639 if (DEBUG_REMOVE) { 14640 Slog.d(TAG, " user " + userId + " => " + installed); 14641 } 14642 ps.setInstalled(installed, userId); 14643 14644 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14645 } 14646 // Regardless of writeSettings we need to ensure that this restriction 14647 // state propagation is persisted 14648 mSettings.writeAllUsersPackageRestrictionsLPr(); 14649 } 14650 // can downgrade to reader here 14651 if (writeSettings) { 14652 mSettings.writeLPr(); 14653 } 14654 } 14655 return true; 14656 } 14657 14658 private boolean deleteInstalledPackageLI(PackageSetting ps, 14659 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14660 PackageRemovedInfo outInfo, boolean writeSettings, 14661 PackageParser.Package replacingPackage) { 14662 synchronized (mPackages) { 14663 if (outInfo != null) { 14664 outInfo.uid = ps.appId; 14665 } 14666 14667 if (outInfo != null && outInfo.removedChildPackages != null) { 14668 final int childCount = (ps.childPackageNames != null) 14669 ? ps.childPackageNames.size() : 0; 14670 for (int i = 0; i < childCount; i++) { 14671 String childPackageName = ps.childPackageNames.get(i); 14672 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14673 if (childPs == null) { 14674 return false; 14675 } 14676 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14677 childPackageName); 14678 if (childInfo != null) { 14679 childInfo.uid = childPs.appId; 14680 } 14681 } 14682 } 14683 } 14684 14685 // Delete package data from internal structures and also remove data if flag is set 14686 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14687 14688 // Delete the child packages data 14689 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14690 for (int i = 0; i < childCount; i++) { 14691 PackageSetting childPs; 14692 synchronized (mPackages) { 14693 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14694 } 14695 if (childPs != null) { 14696 PackageRemovedInfo childOutInfo = (outInfo != null 14697 && outInfo.removedChildPackages != null) 14698 ? outInfo.removedChildPackages.get(childPs.name) : null; 14699 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14700 && (replacingPackage != null 14701 && !replacingPackage.hasChildPackage(childPs.name)) 14702 ? flags & ~DELETE_KEEP_DATA : flags; 14703 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14704 deleteFlags, writeSettings); 14705 } 14706 } 14707 14708 // Delete application code and resources only for parent packages 14709 if (ps.parentPackageName == null) { 14710 if (deleteCodeAndResources && (outInfo != null)) { 14711 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14712 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14713 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14714 } 14715 } 14716 14717 return true; 14718 } 14719 14720 @Override 14721 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14722 int userId) { 14723 mContext.enforceCallingOrSelfPermission( 14724 android.Manifest.permission.DELETE_PACKAGES, null); 14725 synchronized (mPackages) { 14726 PackageSetting ps = mSettings.mPackages.get(packageName); 14727 if (ps == null) { 14728 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14729 return false; 14730 } 14731 if (!ps.getInstalled(userId)) { 14732 // Can't block uninstall for an app that is not installed or enabled. 14733 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14734 return false; 14735 } 14736 ps.setBlockUninstall(blockUninstall, userId); 14737 mSettings.writePackageRestrictionsLPr(userId); 14738 } 14739 return true; 14740 } 14741 14742 @Override 14743 public boolean getBlockUninstallForUser(String packageName, int userId) { 14744 synchronized (mPackages) { 14745 PackageSetting ps = mSettings.mPackages.get(packageName); 14746 if (ps == null) { 14747 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14748 return false; 14749 } 14750 return ps.getBlockUninstall(userId); 14751 } 14752 } 14753 14754 @Override 14755 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14756 int callingUid = Binder.getCallingUid(); 14757 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14758 throw new SecurityException( 14759 "setRequiredForSystemUser can only be run by the system or root"); 14760 } 14761 synchronized (mPackages) { 14762 PackageSetting ps = mSettings.mPackages.get(packageName); 14763 if (ps == null) { 14764 Log.w(TAG, "Package doesn't exist: " + packageName); 14765 return false; 14766 } 14767 if (systemUserApp) { 14768 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14769 } else { 14770 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14771 } 14772 mSettings.writeLPr(); 14773 } 14774 return true; 14775 } 14776 14777 /* 14778 * This method handles package deletion in general 14779 */ 14780 private boolean deletePackageLI(String packageName, UserHandle user, 14781 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14782 PackageRemovedInfo outInfo, boolean writeSettings, 14783 PackageParser.Package replacingPackage) { 14784 if (packageName == null) { 14785 Slog.w(TAG, "Attempt to delete null packageName."); 14786 return false; 14787 } 14788 14789 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14790 14791 PackageSetting ps; 14792 14793 synchronized (mPackages) { 14794 ps = mSettings.mPackages.get(packageName); 14795 if (ps == null) { 14796 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14797 return false; 14798 } 14799 14800 if (ps.parentPackageName != null && (!isSystemApp(ps) 14801 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14802 if (DEBUG_REMOVE) { 14803 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14804 + ((user == null) ? UserHandle.USER_ALL : user)); 14805 } 14806 final int removedUserId = (user != null) ? user.getIdentifier() 14807 : UserHandle.USER_ALL; 14808 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14809 return false; 14810 } 14811 markPackageUninstalledForUserLPw(ps, user); 14812 scheduleWritePackageRestrictionsLocked(user); 14813 return true; 14814 } 14815 } 14816 14817 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14818 && user.getIdentifier() != UserHandle.USER_ALL)) { 14819 // The caller is asking that the package only be deleted for a single 14820 // user. To do this, we just mark its uninstalled state and delete 14821 // its data. If this is a system app, we only allow this to happen if 14822 // they have set the special DELETE_SYSTEM_APP which requests different 14823 // semantics than normal for uninstalling system apps. 14824 markPackageUninstalledForUserLPw(ps, user); 14825 14826 if (!isSystemApp(ps)) { 14827 // Do not uninstall the APK if an app should be cached 14828 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14829 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14830 // Other user still have this package installed, so all 14831 // we need to do is clear this user's data and save that 14832 // it is uninstalled. 14833 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14834 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14835 return false; 14836 } 14837 scheduleWritePackageRestrictionsLocked(user); 14838 return true; 14839 } else { 14840 // We need to set it back to 'installed' so the uninstall 14841 // broadcasts will be sent correctly. 14842 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14843 ps.setInstalled(true, user.getIdentifier()); 14844 } 14845 } else { 14846 // This is a system app, so we assume that the 14847 // other users still have this package installed, so all 14848 // we need to do is clear this user's data and save that 14849 // it is uninstalled. 14850 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14851 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14852 return false; 14853 } 14854 scheduleWritePackageRestrictionsLocked(user); 14855 return true; 14856 } 14857 } 14858 14859 // If we are deleting a composite package for all users, keep track 14860 // of result for each child. 14861 if (ps.childPackageNames != null && outInfo != null) { 14862 synchronized (mPackages) { 14863 final int childCount = ps.childPackageNames.size(); 14864 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14865 for (int i = 0; i < childCount; i++) { 14866 String childPackageName = ps.childPackageNames.get(i); 14867 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14868 childInfo.removedPackage = childPackageName; 14869 outInfo.removedChildPackages.put(childPackageName, childInfo); 14870 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14871 if (childPs != null) { 14872 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14873 } 14874 } 14875 } 14876 } 14877 14878 boolean ret = false; 14879 if (isSystemApp(ps)) { 14880 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14881 // When an updated system application is deleted we delete the existing resources 14882 // as well and fall back to existing code in system partition 14883 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14884 } else { 14885 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14886 // Kill application pre-emptively especially for apps on sd. 14887 killApplication(packageName, ps.appId, "uninstall pkg"); 14888 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14889 outInfo, writeSettings, replacingPackage); 14890 } 14891 14892 // Take a note whether we deleted the package for all users 14893 if (outInfo != null) { 14894 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14895 if (outInfo.removedChildPackages != null) { 14896 synchronized (mPackages) { 14897 final int childCount = outInfo.removedChildPackages.size(); 14898 for (int i = 0; i < childCount; i++) { 14899 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14900 if (childInfo != null) { 14901 childInfo.removedForAllUsers = mPackages.get( 14902 childInfo.removedPackage) == null; 14903 } 14904 } 14905 } 14906 } 14907 // If we uninstalled an update to a system app there may be some 14908 // child packages that appeared as they are declared in the system 14909 // app but were not declared in the update. 14910 if (isSystemApp(ps)) { 14911 synchronized (mPackages) { 14912 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14913 final int childCount = (updatedPs.childPackageNames != null) 14914 ? updatedPs.childPackageNames.size() : 0; 14915 for (int i = 0; i < childCount; i++) { 14916 String childPackageName = updatedPs.childPackageNames.get(i); 14917 if (outInfo.removedChildPackages == null 14918 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 14919 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14920 if (childPs == null) { 14921 continue; 14922 } 14923 PackageInstalledInfo installRes = new PackageInstalledInfo(); 14924 installRes.name = childPackageName; 14925 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 14926 installRes.pkg = mPackages.get(childPackageName); 14927 installRes.uid = childPs.pkg.applicationInfo.uid; 14928 if (outInfo.appearedChildPackages == null) { 14929 outInfo.appearedChildPackages = new ArrayMap<>(); 14930 } 14931 outInfo.appearedChildPackages.put(childPackageName, installRes); 14932 } 14933 } 14934 } 14935 } 14936 } 14937 14938 return ret; 14939 } 14940 14941 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14942 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14943 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14944 for (int nextUserId : userIds) { 14945 if (DEBUG_REMOVE) { 14946 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14947 } 14948 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14949 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14950 false /*hidden*/, false /*suspended*/, null, null, null, 14951 false /*blockUninstall*/, 14952 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14953 } 14954 } 14955 14956 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14957 PackageRemovedInfo outInfo) { 14958 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14959 : new int[] {userId}; 14960 for (int nextUserId : userIds) { 14961 if (DEBUG_REMOVE) { 14962 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14963 + nextUserId); 14964 } 14965 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14966 try { 14967 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14968 } catch (InstallerException e) { 14969 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14970 return false; 14971 } 14972 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14973 schedulePackageCleaning(ps.name, nextUserId, false); 14974 synchronized (mPackages) { 14975 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14976 scheduleWritePackageRestrictionsLocked(nextUserId); 14977 } 14978 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14979 } 14980 } 14981 14982 if (outInfo != null) { 14983 outInfo.removedPackage = ps.name; 14984 outInfo.removedAppId = ps.appId; 14985 outInfo.removedUsers = userIds; 14986 } 14987 14988 return true; 14989 } 14990 14991 private final class ClearStorageConnection implements ServiceConnection { 14992 IMediaContainerService mContainerService; 14993 14994 @Override 14995 public void onServiceConnected(ComponentName name, IBinder service) { 14996 synchronized (this) { 14997 mContainerService = IMediaContainerService.Stub.asInterface(service); 14998 notifyAll(); 14999 } 15000 } 15001 15002 @Override 15003 public void onServiceDisconnected(ComponentName name) { 15004 } 15005 } 15006 15007 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15008 final boolean mounted; 15009 if (Environment.isExternalStorageEmulated()) { 15010 mounted = true; 15011 } else { 15012 final String status = Environment.getExternalStorageState(); 15013 15014 mounted = status.equals(Environment.MEDIA_MOUNTED) 15015 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15016 } 15017 15018 if (!mounted) { 15019 return; 15020 } 15021 15022 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15023 int[] users; 15024 if (userId == UserHandle.USER_ALL) { 15025 users = sUserManager.getUserIds(); 15026 } else { 15027 users = new int[] { userId }; 15028 } 15029 final ClearStorageConnection conn = new ClearStorageConnection(); 15030 if (mContext.bindServiceAsUser( 15031 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15032 try { 15033 for (int curUser : users) { 15034 long timeout = SystemClock.uptimeMillis() + 5000; 15035 synchronized (conn) { 15036 long now = SystemClock.uptimeMillis(); 15037 while (conn.mContainerService == null && now < timeout) { 15038 try { 15039 conn.wait(timeout - now); 15040 } catch (InterruptedException e) { 15041 } 15042 } 15043 } 15044 if (conn.mContainerService == null) { 15045 return; 15046 } 15047 15048 final UserEnvironment userEnv = new UserEnvironment(curUser); 15049 clearDirectory(conn.mContainerService, 15050 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15051 if (allData) { 15052 clearDirectory(conn.mContainerService, 15053 userEnv.buildExternalStorageAppDataDirs(packageName)); 15054 clearDirectory(conn.mContainerService, 15055 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15056 } 15057 } 15058 } finally { 15059 mContext.unbindService(conn); 15060 } 15061 } 15062 } 15063 15064 @Override 15065 public void clearApplicationUserData(final String packageName, 15066 final IPackageDataObserver observer, final int userId) { 15067 mContext.enforceCallingOrSelfPermission( 15068 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15070 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15071 // Queue up an async operation since the package deletion may take a little while. 15072 mHandler.post(new Runnable() { 15073 public void run() { 15074 mHandler.removeCallbacks(this); 15075 final boolean succeeded; 15076 synchronized (mInstallLock) { 15077 succeeded = clearApplicationUserDataLI(packageName, userId); 15078 } 15079 clearExternalStorageDataSync(packageName, userId, true); 15080 if (succeeded) { 15081 // invoke DeviceStorageMonitor's update method to clear any notifications 15082 DeviceStorageMonitorInternal 15083 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15084 if (dsm != null) { 15085 dsm.checkMemory(); 15086 } 15087 } 15088 if(observer != null) { 15089 try { 15090 observer.onRemoveCompleted(packageName, succeeded); 15091 } catch (RemoteException e) { 15092 Log.i(TAG, "Observer no longer exists."); 15093 } 15094 } //end if observer 15095 } //end run 15096 }); 15097 } 15098 15099 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15100 if (packageName == null) { 15101 Slog.w(TAG, "Attempt to delete null packageName."); 15102 return false; 15103 } 15104 15105 // Try finding details about the requested package 15106 PackageParser.Package pkg; 15107 synchronized (mPackages) { 15108 pkg = mPackages.get(packageName); 15109 if (pkg == null) { 15110 final PackageSetting ps = mSettings.mPackages.get(packageName); 15111 if (ps != null) { 15112 pkg = ps.pkg; 15113 } 15114 } 15115 15116 if (pkg == null) { 15117 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15118 return false; 15119 } 15120 15121 PackageSetting ps = (PackageSetting) pkg.mExtras; 15122 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15123 } 15124 15125 // Always delete data directories for package, even if we found no other 15126 // record of app. This helps users recover from UID mismatches without 15127 // resorting to a full data wipe. 15128 // TODO: triage flags as part of 26466827 15129 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15130 try { 15131 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15132 } catch (InstallerException e) { 15133 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15134 return false; 15135 } 15136 15137 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15138 removeKeystoreDataIfNeeded(userId, appId); 15139 15140 // Create a native library symlink only if we have native libraries 15141 // and if the native libraries are 32 bit libraries. We do not provide 15142 // this symlink for 64 bit libraries. 15143 if (pkg.applicationInfo.primaryCpuAbi != null && 15144 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15145 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15146 try { 15147 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15148 nativeLibPath, userId); 15149 } catch (InstallerException e) { 15150 Slog.w(TAG, "Failed linking native library dir", e); 15151 return false; 15152 } 15153 } 15154 15155 return true; 15156 } 15157 15158 /** 15159 * Reverts user permission state changes (permissions and flags) in 15160 * all packages for a given user. 15161 * 15162 * @param userId The device user for which to do a reset. 15163 */ 15164 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15165 final int packageCount = mPackages.size(); 15166 for (int i = 0; i < packageCount; i++) { 15167 PackageParser.Package pkg = mPackages.valueAt(i); 15168 PackageSetting ps = (PackageSetting) pkg.mExtras; 15169 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15170 } 15171 } 15172 15173 /** 15174 * Reverts user permission state changes (permissions and flags). 15175 * 15176 * @param ps The package for which to reset. 15177 * @param userId The device user for which to do a reset. 15178 */ 15179 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15180 final PackageSetting ps, final int userId) { 15181 if (ps.pkg == null) { 15182 return; 15183 } 15184 15185 // These are flags that can change base on user actions. 15186 final int userSettableMask = FLAG_PERMISSION_USER_SET 15187 | FLAG_PERMISSION_USER_FIXED 15188 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15189 | FLAG_PERMISSION_REVIEW_REQUIRED; 15190 15191 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15192 | FLAG_PERMISSION_POLICY_FIXED; 15193 15194 boolean writeInstallPermissions = false; 15195 boolean writeRuntimePermissions = false; 15196 15197 final int permissionCount = ps.pkg.requestedPermissions.size(); 15198 for (int i = 0; i < permissionCount; i++) { 15199 String permission = ps.pkg.requestedPermissions.get(i); 15200 15201 BasePermission bp = mSettings.mPermissions.get(permission); 15202 if (bp == null) { 15203 continue; 15204 } 15205 15206 // If shared user we just reset the state to which only this app contributed. 15207 if (ps.sharedUser != null) { 15208 boolean used = false; 15209 final int packageCount = ps.sharedUser.packages.size(); 15210 for (int j = 0; j < packageCount; j++) { 15211 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15212 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15213 && pkg.pkg.requestedPermissions.contains(permission)) { 15214 used = true; 15215 break; 15216 } 15217 } 15218 if (used) { 15219 continue; 15220 } 15221 } 15222 15223 PermissionsState permissionsState = ps.getPermissionsState(); 15224 15225 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15226 15227 // Always clear the user settable flags. 15228 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15229 bp.name) != null; 15230 // If permission review is enabled and this is a legacy app, mark the 15231 // permission as requiring a review as this is the initial state. 15232 int flags = 0; 15233 if (Build.PERMISSIONS_REVIEW_REQUIRED 15234 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15235 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15236 } 15237 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15238 if (hasInstallState) { 15239 writeInstallPermissions = true; 15240 } else { 15241 writeRuntimePermissions = true; 15242 } 15243 } 15244 15245 // Below is only runtime permission handling. 15246 if (!bp.isRuntime()) { 15247 continue; 15248 } 15249 15250 // Never clobber system or policy. 15251 if ((oldFlags & policyOrSystemFlags) != 0) { 15252 continue; 15253 } 15254 15255 // If this permission was granted by default, make sure it is. 15256 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15257 if (permissionsState.grantRuntimePermission(bp, userId) 15258 != PERMISSION_OPERATION_FAILURE) { 15259 writeRuntimePermissions = true; 15260 } 15261 // If permission review is enabled the permissions for a legacy apps 15262 // are represented as constantly granted runtime ones, so don't revoke. 15263 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15264 // Otherwise, reset the permission. 15265 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15266 switch (revokeResult) { 15267 case PERMISSION_OPERATION_SUCCESS: { 15268 writeRuntimePermissions = true; 15269 } break; 15270 15271 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15272 writeRuntimePermissions = true; 15273 final int appId = ps.appId; 15274 mHandler.post(new Runnable() { 15275 @Override 15276 public void run() { 15277 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15278 } 15279 }); 15280 } break; 15281 } 15282 } 15283 } 15284 15285 // Synchronously write as we are taking permissions away. 15286 if (writeRuntimePermissions) { 15287 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15288 } 15289 15290 // Synchronously write as we are taking permissions away. 15291 if (writeInstallPermissions) { 15292 mSettings.writeLPr(); 15293 } 15294 } 15295 15296 /** 15297 * Remove entries from the keystore daemon. Will only remove it if the 15298 * {@code appId} is valid. 15299 */ 15300 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15301 if (appId < 0) { 15302 return; 15303 } 15304 15305 final KeyStore keyStore = KeyStore.getInstance(); 15306 if (keyStore != null) { 15307 if (userId == UserHandle.USER_ALL) { 15308 for (final int individual : sUserManager.getUserIds()) { 15309 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15310 } 15311 } else { 15312 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15313 } 15314 } else { 15315 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15316 } 15317 } 15318 15319 @Override 15320 public void deleteApplicationCacheFiles(final String packageName, 15321 final IPackageDataObserver observer) { 15322 mContext.enforceCallingOrSelfPermission( 15323 android.Manifest.permission.DELETE_CACHE_FILES, null); 15324 // Queue up an async operation since the package deletion may take a little while. 15325 final int userId = UserHandle.getCallingUserId(); 15326 mHandler.post(new Runnable() { 15327 public void run() { 15328 mHandler.removeCallbacks(this); 15329 final boolean succeded; 15330 synchronized (mInstallLock) { 15331 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15332 } 15333 clearExternalStorageDataSync(packageName, userId, false); 15334 if (observer != null) { 15335 try { 15336 observer.onRemoveCompleted(packageName, succeded); 15337 } catch (RemoteException e) { 15338 Log.i(TAG, "Observer no longer exists."); 15339 } 15340 } //end if observer 15341 } //end run 15342 }); 15343 } 15344 15345 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15346 if (packageName == null) { 15347 Slog.w(TAG, "Attempt to delete null packageName."); 15348 return false; 15349 } 15350 PackageParser.Package p; 15351 synchronized (mPackages) { 15352 p = mPackages.get(packageName); 15353 } 15354 if (p == null) { 15355 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15356 return false; 15357 } 15358 final ApplicationInfo applicationInfo = p.applicationInfo; 15359 if (applicationInfo == null) { 15360 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15361 return false; 15362 } 15363 // TODO: triage flags as part of 26466827 15364 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15365 try { 15366 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15367 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15368 } catch (InstallerException e) { 15369 Slog.w(TAG, "Couldn't remove cache files for package " 15370 + packageName + " u" + userId, e); 15371 return false; 15372 } 15373 return true; 15374 } 15375 15376 @Override 15377 public void getPackageSizeInfo(final String packageName, int userHandle, 15378 final IPackageStatsObserver observer) { 15379 mContext.enforceCallingOrSelfPermission( 15380 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15381 if (packageName == null) { 15382 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15383 } 15384 15385 PackageStats stats = new PackageStats(packageName, userHandle); 15386 15387 /* 15388 * Queue up an async operation since the package measurement may take a 15389 * little while. 15390 */ 15391 Message msg = mHandler.obtainMessage(INIT_COPY); 15392 msg.obj = new MeasureParams(stats, observer); 15393 mHandler.sendMessage(msg); 15394 } 15395 15396 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15397 PackageStats pStats) { 15398 if (packageName == null) { 15399 Slog.w(TAG, "Attempt to get size of null packageName."); 15400 return false; 15401 } 15402 PackageParser.Package p; 15403 boolean dataOnly = false; 15404 String libDirRoot = null; 15405 String asecPath = null; 15406 PackageSetting ps = null; 15407 synchronized (mPackages) { 15408 p = mPackages.get(packageName); 15409 ps = mSettings.mPackages.get(packageName); 15410 if(p == null) { 15411 dataOnly = true; 15412 if((ps == null) || (ps.pkg == null)) { 15413 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15414 return false; 15415 } 15416 p = ps.pkg; 15417 } 15418 if (ps != null) { 15419 libDirRoot = ps.legacyNativeLibraryPathString; 15420 } 15421 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15422 final long token = Binder.clearCallingIdentity(); 15423 try { 15424 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15425 if (secureContainerId != null) { 15426 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15427 } 15428 } finally { 15429 Binder.restoreCallingIdentity(token); 15430 } 15431 } 15432 } 15433 String publicSrcDir = null; 15434 if(!dataOnly) { 15435 final ApplicationInfo applicationInfo = p.applicationInfo; 15436 if (applicationInfo == null) { 15437 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15438 return false; 15439 } 15440 if (p.isForwardLocked()) { 15441 publicSrcDir = applicationInfo.getBaseResourcePath(); 15442 } 15443 } 15444 // TODO: extend to measure size of split APKs 15445 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15446 // not just the first level. 15447 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15448 // just the primary. 15449 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15450 15451 String apkPath; 15452 File packageDir = new File(p.codePath); 15453 15454 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15455 apkPath = packageDir.getAbsolutePath(); 15456 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15457 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15458 libDirRoot = null; 15459 } 15460 } else { 15461 apkPath = p.baseCodePath; 15462 } 15463 15464 // TODO: triage flags as part of 26466827 15465 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15466 try { 15467 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15468 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15469 } catch (InstallerException e) { 15470 return false; 15471 } 15472 15473 // Fix-up for forward-locked applications in ASEC containers. 15474 if (!isExternal(p)) { 15475 pStats.codeSize += pStats.externalCodeSize; 15476 pStats.externalCodeSize = 0L; 15477 } 15478 15479 return true; 15480 } 15481 15482 15483 @Override 15484 public void addPackageToPreferred(String packageName) { 15485 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15486 } 15487 15488 @Override 15489 public void removePackageFromPreferred(String packageName) { 15490 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15491 } 15492 15493 @Override 15494 public List<PackageInfo> getPreferredPackages(int flags) { 15495 return new ArrayList<PackageInfo>(); 15496 } 15497 15498 private int getUidTargetSdkVersionLockedLPr(int uid) { 15499 Object obj = mSettings.getUserIdLPr(uid); 15500 if (obj instanceof SharedUserSetting) { 15501 final SharedUserSetting sus = (SharedUserSetting) obj; 15502 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15503 final Iterator<PackageSetting> it = sus.packages.iterator(); 15504 while (it.hasNext()) { 15505 final PackageSetting ps = it.next(); 15506 if (ps.pkg != null) { 15507 int v = ps.pkg.applicationInfo.targetSdkVersion; 15508 if (v < vers) vers = v; 15509 } 15510 } 15511 return vers; 15512 } else if (obj instanceof PackageSetting) { 15513 final PackageSetting ps = (PackageSetting) obj; 15514 if (ps.pkg != null) { 15515 return ps.pkg.applicationInfo.targetSdkVersion; 15516 } 15517 } 15518 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15519 } 15520 15521 @Override 15522 public void addPreferredActivity(IntentFilter filter, int match, 15523 ComponentName[] set, ComponentName activity, int userId) { 15524 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15525 "Adding preferred"); 15526 } 15527 15528 private void addPreferredActivityInternal(IntentFilter filter, int match, 15529 ComponentName[] set, ComponentName activity, boolean always, int userId, 15530 String opname) { 15531 // writer 15532 int callingUid = Binder.getCallingUid(); 15533 enforceCrossUserPermission(callingUid, userId, 15534 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15535 if (filter.countActions() == 0) { 15536 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15537 return; 15538 } 15539 synchronized (mPackages) { 15540 if (mContext.checkCallingOrSelfPermission( 15541 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15542 != PackageManager.PERMISSION_GRANTED) { 15543 if (getUidTargetSdkVersionLockedLPr(callingUid) 15544 < Build.VERSION_CODES.FROYO) { 15545 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15546 + callingUid); 15547 return; 15548 } 15549 mContext.enforceCallingOrSelfPermission( 15550 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15551 } 15552 15553 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15554 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15555 + userId + ":"); 15556 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15557 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15558 scheduleWritePackageRestrictionsLocked(userId); 15559 } 15560 } 15561 15562 @Override 15563 public void replacePreferredActivity(IntentFilter filter, int match, 15564 ComponentName[] set, ComponentName activity, int userId) { 15565 if (filter.countActions() != 1) { 15566 throw new IllegalArgumentException( 15567 "replacePreferredActivity expects filter to have only 1 action."); 15568 } 15569 if (filter.countDataAuthorities() != 0 15570 || filter.countDataPaths() != 0 15571 || filter.countDataSchemes() > 1 15572 || filter.countDataTypes() != 0) { 15573 throw new IllegalArgumentException( 15574 "replacePreferredActivity expects filter to have no data authorities, " + 15575 "paths, or types; and at most one scheme."); 15576 } 15577 15578 final int callingUid = Binder.getCallingUid(); 15579 enforceCrossUserPermission(callingUid, userId, 15580 true /* requireFullPermission */, false /* checkShell */, 15581 "replace preferred activity"); 15582 synchronized (mPackages) { 15583 if (mContext.checkCallingOrSelfPermission( 15584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15585 != PackageManager.PERMISSION_GRANTED) { 15586 if (getUidTargetSdkVersionLockedLPr(callingUid) 15587 < Build.VERSION_CODES.FROYO) { 15588 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15589 + Binder.getCallingUid()); 15590 return; 15591 } 15592 mContext.enforceCallingOrSelfPermission( 15593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15594 } 15595 15596 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15597 if (pir != null) { 15598 // Get all of the existing entries that exactly match this filter. 15599 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15600 if (existing != null && existing.size() == 1) { 15601 PreferredActivity cur = existing.get(0); 15602 if (DEBUG_PREFERRED) { 15603 Slog.i(TAG, "Checking replace of preferred:"); 15604 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15605 if (!cur.mPref.mAlways) { 15606 Slog.i(TAG, " -- CUR; not mAlways!"); 15607 } else { 15608 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15609 Slog.i(TAG, " -- CUR: mSet=" 15610 + Arrays.toString(cur.mPref.mSetComponents)); 15611 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15612 Slog.i(TAG, " -- NEW: mMatch=" 15613 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15614 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15615 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15616 } 15617 } 15618 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15619 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15620 && cur.mPref.sameSet(set)) { 15621 // Setting the preferred activity to what it happens to be already 15622 if (DEBUG_PREFERRED) { 15623 Slog.i(TAG, "Replacing with same preferred activity " 15624 + cur.mPref.mShortComponent + " for user " 15625 + userId + ":"); 15626 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15627 } 15628 return; 15629 } 15630 } 15631 15632 if (existing != null) { 15633 if (DEBUG_PREFERRED) { 15634 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15635 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15636 } 15637 for (int i = 0; i < existing.size(); i++) { 15638 PreferredActivity pa = existing.get(i); 15639 if (DEBUG_PREFERRED) { 15640 Slog.i(TAG, "Removing existing preferred activity " 15641 + pa.mPref.mComponent + ":"); 15642 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15643 } 15644 pir.removeFilter(pa); 15645 } 15646 } 15647 } 15648 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15649 "Replacing preferred"); 15650 } 15651 } 15652 15653 @Override 15654 public void clearPackagePreferredActivities(String packageName) { 15655 final int uid = Binder.getCallingUid(); 15656 // writer 15657 synchronized (mPackages) { 15658 PackageParser.Package pkg = mPackages.get(packageName); 15659 if (pkg == null || pkg.applicationInfo.uid != uid) { 15660 if (mContext.checkCallingOrSelfPermission( 15661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15662 != PackageManager.PERMISSION_GRANTED) { 15663 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15664 < Build.VERSION_CODES.FROYO) { 15665 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15666 + Binder.getCallingUid()); 15667 return; 15668 } 15669 mContext.enforceCallingOrSelfPermission( 15670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15671 } 15672 } 15673 15674 int user = UserHandle.getCallingUserId(); 15675 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15676 scheduleWritePackageRestrictionsLocked(user); 15677 } 15678 } 15679 } 15680 15681 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15682 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15683 ArrayList<PreferredActivity> removed = null; 15684 boolean changed = false; 15685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15686 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15687 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15688 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15689 continue; 15690 } 15691 Iterator<PreferredActivity> it = pir.filterIterator(); 15692 while (it.hasNext()) { 15693 PreferredActivity pa = it.next(); 15694 // Mark entry for removal only if it matches the package name 15695 // and the entry is of type "always". 15696 if (packageName == null || 15697 (pa.mPref.mComponent.getPackageName().equals(packageName) 15698 && pa.mPref.mAlways)) { 15699 if (removed == null) { 15700 removed = new ArrayList<PreferredActivity>(); 15701 } 15702 removed.add(pa); 15703 } 15704 } 15705 if (removed != null) { 15706 for (int j=0; j<removed.size(); j++) { 15707 PreferredActivity pa = removed.get(j); 15708 pir.removeFilter(pa); 15709 } 15710 changed = true; 15711 } 15712 } 15713 return changed; 15714 } 15715 15716 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15717 private void clearIntentFilterVerificationsLPw(int userId) { 15718 final int packageCount = mPackages.size(); 15719 for (int i = 0; i < packageCount; i++) { 15720 PackageParser.Package pkg = mPackages.valueAt(i); 15721 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15722 } 15723 } 15724 15725 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15726 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15727 if (userId == UserHandle.USER_ALL) { 15728 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15729 sUserManager.getUserIds())) { 15730 for (int oneUserId : sUserManager.getUserIds()) { 15731 scheduleWritePackageRestrictionsLocked(oneUserId); 15732 } 15733 } 15734 } else { 15735 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15736 scheduleWritePackageRestrictionsLocked(userId); 15737 } 15738 } 15739 } 15740 15741 void clearDefaultBrowserIfNeeded(String packageName) { 15742 for (int oneUserId : sUserManager.getUserIds()) { 15743 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15744 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15745 if (packageName.equals(defaultBrowserPackageName)) { 15746 setDefaultBrowserPackageName(null, oneUserId); 15747 } 15748 } 15749 } 15750 15751 @Override 15752 public void resetApplicationPreferences(int userId) { 15753 mContext.enforceCallingOrSelfPermission( 15754 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15755 // writer 15756 synchronized (mPackages) { 15757 final long identity = Binder.clearCallingIdentity(); 15758 try { 15759 clearPackagePreferredActivitiesLPw(null, userId); 15760 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15761 // TODO: We have to reset the default SMS and Phone. This requires 15762 // significant refactoring to keep all default apps in the package 15763 // manager (cleaner but more work) or have the services provide 15764 // callbacks to the package manager to request a default app reset. 15765 applyFactoryDefaultBrowserLPw(userId); 15766 clearIntentFilterVerificationsLPw(userId); 15767 primeDomainVerificationsLPw(userId); 15768 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15769 scheduleWritePackageRestrictionsLocked(userId); 15770 } finally { 15771 Binder.restoreCallingIdentity(identity); 15772 } 15773 } 15774 } 15775 15776 @Override 15777 public int getPreferredActivities(List<IntentFilter> outFilters, 15778 List<ComponentName> outActivities, String packageName) { 15779 15780 int num = 0; 15781 final int userId = UserHandle.getCallingUserId(); 15782 // reader 15783 synchronized (mPackages) { 15784 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15785 if (pir != null) { 15786 final Iterator<PreferredActivity> it = pir.filterIterator(); 15787 while (it.hasNext()) { 15788 final PreferredActivity pa = it.next(); 15789 if (packageName == null 15790 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15791 && pa.mPref.mAlways)) { 15792 if (outFilters != null) { 15793 outFilters.add(new IntentFilter(pa)); 15794 } 15795 if (outActivities != null) { 15796 outActivities.add(pa.mPref.mComponent); 15797 } 15798 } 15799 } 15800 } 15801 } 15802 15803 return num; 15804 } 15805 15806 @Override 15807 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15808 int userId) { 15809 int callingUid = Binder.getCallingUid(); 15810 if (callingUid != Process.SYSTEM_UID) { 15811 throw new SecurityException( 15812 "addPersistentPreferredActivity can only be run by the system"); 15813 } 15814 if (filter.countActions() == 0) { 15815 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15816 return; 15817 } 15818 synchronized (mPackages) { 15819 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15820 ":"); 15821 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15822 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15823 new PersistentPreferredActivity(filter, activity)); 15824 scheduleWritePackageRestrictionsLocked(userId); 15825 } 15826 } 15827 15828 @Override 15829 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15830 int callingUid = Binder.getCallingUid(); 15831 if (callingUid != Process.SYSTEM_UID) { 15832 throw new SecurityException( 15833 "clearPackagePersistentPreferredActivities can only be run by the system"); 15834 } 15835 ArrayList<PersistentPreferredActivity> removed = null; 15836 boolean changed = false; 15837 synchronized (mPackages) { 15838 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15839 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15840 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15841 .valueAt(i); 15842 if (userId != thisUserId) { 15843 continue; 15844 } 15845 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15846 while (it.hasNext()) { 15847 PersistentPreferredActivity ppa = it.next(); 15848 // Mark entry for removal only if it matches the package name. 15849 if (ppa.mComponent.getPackageName().equals(packageName)) { 15850 if (removed == null) { 15851 removed = new ArrayList<PersistentPreferredActivity>(); 15852 } 15853 removed.add(ppa); 15854 } 15855 } 15856 if (removed != null) { 15857 for (int j=0; j<removed.size(); j++) { 15858 PersistentPreferredActivity ppa = removed.get(j); 15859 ppir.removeFilter(ppa); 15860 } 15861 changed = true; 15862 } 15863 } 15864 15865 if (changed) { 15866 scheduleWritePackageRestrictionsLocked(userId); 15867 } 15868 } 15869 } 15870 15871 /** 15872 * Common machinery for picking apart a restored XML blob and passing 15873 * it to a caller-supplied functor to be applied to the running system. 15874 */ 15875 private void restoreFromXml(XmlPullParser parser, int userId, 15876 String expectedStartTag, BlobXmlRestorer functor) 15877 throws IOException, XmlPullParserException { 15878 int type; 15879 while ((type = parser.next()) != XmlPullParser.START_TAG 15880 && type != XmlPullParser.END_DOCUMENT) { 15881 } 15882 if (type != XmlPullParser.START_TAG) { 15883 // oops didn't find a start tag?! 15884 if (DEBUG_BACKUP) { 15885 Slog.e(TAG, "Didn't find start tag during restore"); 15886 } 15887 return; 15888 } 15889Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15890 // this is supposed to be TAG_PREFERRED_BACKUP 15891 if (!expectedStartTag.equals(parser.getName())) { 15892 if (DEBUG_BACKUP) { 15893 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15894 } 15895 return; 15896 } 15897 15898 // skip interfering stuff, then we're aligned with the backing implementation 15899 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15900Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15901 functor.apply(parser, userId); 15902 } 15903 15904 private interface BlobXmlRestorer { 15905 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15906 } 15907 15908 /** 15909 * Non-Binder method, support for the backup/restore mechanism: write the 15910 * full set of preferred activities in its canonical XML format. Returns the 15911 * XML output as a byte array, or null if there is none. 15912 */ 15913 @Override 15914 public byte[] getPreferredActivityBackup(int userId) { 15915 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15916 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15917 } 15918 15919 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15920 try { 15921 final XmlSerializer serializer = new FastXmlSerializer(); 15922 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15923 serializer.startDocument(null, true); 15924 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15925 15926 synchronized (mPackages) { 15927 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15928 } 15929 15930 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15931 serializer.endDocument(); 15932 serializer.flush(); 15933 } catch (Exception e) { 15934 if (DEBUG_BACKUP) { 15935 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15936 } 15937 return null; 15938 } 15939 15940 return dataStream.toByteArray(); 15941 } 15942 15943 @Override 15944 public void restorePreferredActivities(byte[] backup, int userId) { 15945 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15946 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15947 } 15948 15949 try { 15950 final XmlPullParser parser = Xml.newPullParser(); 15951 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15952 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15953 new BlobXmlRestorer() { 15954 @Override 15955 public void apply(XmlPullParser parser, int userId) 15956 throws XmlPullParserException, IOException { 15957 synchronized (mPackages) { 15958 mSettings.readPreferredActivitiesLPw(parser, userId); 15959 } 15960 } 15961 } ); 15962 } catch (Exception e) { 15963 if (DEBUG_BACKUP) { 15964 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15965 } 15966 } 15967 } 15968 15969 /** 15970 * Non-Binder method, support for the backup/restore mechanism: write the 15971 * default browser (etc) settings in its canonical XML format. Returns the default 15972 * browser XML representation as a byte array, or null if there is none. 15973 */ 15974 @Override 15975 public byte[] getDefaultAppsBackup(int userId) { 15976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15977 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15978 } 15979 15980 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15981 try { 15982 final XmlSerializer serializer = new FastXmlSerializer(); 15983 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15984 serializer.startDocument(null, true); 15985 serializer.startTag(null, TAG_DEFAULT_APPS); 15986 15987 synchronized (mPackages) { 15988 mSettings.writeDefaultAppsLPr(serializer, userId); 15989 } 15990 15991 serializer.endTag(null, TAG_DEFAULT_APPS); 15992 serializer.endDocument(); 15993 serializer.flush(); 15994 } catch (Exception e) { 15995 if (DEBUG_BACKUP) { 15996 Slog.e(TAG, "Unable to write default apps for backup", e); 15997 } 15998 return null; 15999 } 16000 16001 return dataStream.toByteArray(); 16002 } 16003 16004 @Override 16005 public void restoreDefaultApps(byte[] backup, int userId) { 16006 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16007 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16008 } 16009 16010 try { 16011 final XmlPullParser parser = Xml.newPullParser(); 16012 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16013 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16014 new BlobXmlRestorer() { 16015 @Override 16016 public void apply(XmlPullParser parser, int userId) 16017 throws XmlPullParserException, IOException { 16018 synchronized (mPackages) { 16019 mSettings.readDefaultAppsLPw(parser, userId); 16020 } 16021 } 16022 } ); 16023 } catch (Exception e) { 16024 if (DEBUG_BACKUP) { 16025 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16026 } 16027 } 16028 } 16029 16030 @Override 16031 public byte[] getIntentFilterVerificationBackup(int userId) { 16032 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16033 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16034 } 16035 16036 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16037 try { 16038 final XmlSerializer serializer = new FastXmlSerializer(); 16039 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16040 serializer.startDocument(null, true); 16041 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16042 16043 synchronized (mPackages) { 16044 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16045 } 16046 16047 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16048 serializer.endDocument(); 16049 serializer.flush(); 16050 } catch (Exception e) { 16051 if (DEBUG_BACKUP) { 16052 Slog.e(TAG, "Unable to write default apps for backup", e); 16053 } 16054 return null; 16055 } 16056 16057 return dataStream.toByteArray(); 16058 } 16059 16060 @Override 16061 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16062 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16063 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16064 } 16065 16066 try { 16067 final XmlPullParser parser = Xml.newPullParser(); 16068 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16069 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16070 new BlobXmlRestorer() { 16071 @Override 16072 public void apply(XmlPullParser parser, int userId) 16073 throws XmlPullParserException, IOException { 16074 synchronized (mPackages) { 16075 mSettings.readAllDomainVerificationsLPr(parser, userId); 16076 mSettings.writeLPr(); 16077 } 16078 } 16079 } ); 16080 } catch (Exception e) { 16081 if (DEBUG_BACKUP) { 16082 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16083 } 16084 } 16085 } 16086 16087 @Override 16088 public byte[] getPermissionGrantBackup(int userId) { 16089 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16090 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16091 } 16092 16093 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16094 try { 16095 final XmlSerializer serializer = new FastXmlSerializer(); 16096 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16097 serializer.startDocument(null, true); 16098 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16099 16100 synchronized (mPackages) { 16101 serializeRuntimePermissionGrantsLPr(serializer, userId); 16102 } 16103 16104 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16105 serializer.endDocument(); 16106 serializer.flush(); 16107 } catch (Exception e) { 16108 if (DEBUG_BACKUP) { 16109 Slog.e(TAG, "Unable to write default apps for backup", e); 16110 } 16111 return null; 16112 } 16113 16114 return dataStream.toByteArray(); 16115 } 16116 16117 @Override 16118 public void restorePermissionGrants(byte[] backup, int userId) { 16119 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16120 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16121 } 16122 16123 try { 16124 final XmlPullParser parser = Xml.newPullParser(); 16125 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16126 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16127 new BlobXmlRestorer() { 16128 @Override 16129 public void apply(XmlPullParser parser, int userId) 16130 throws XmlPullParserException, IOException { 16131 synchronized (mPackages) { 16132 processRestoredPermissionGrantsLPr(parser, userId); 16133 } 16134 } 16135 } ); 16136 } catch (Exception e) { 16137 if (DEBUG_BACKUP) { 16138 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16139 } 16140 } 16141 } 16142 16143 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16144 throws IOException { 16145 serializer.startTag(null, TAG_ALL_GRANTS); 16146 16147 final int N = mSettings.mPackages.size(); 16148 for (int i = 0; i < N; i++) { 16149 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16150 boolean pkgGrantsKnown = false; 16151 16152 PermissionsState packagePerms = ps.getPermissionsState(); 16153 16154 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16155 final int grantFlags = state.getFlags(); 16156 // only look at grants that are not system/policy fixed 16157 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16158 final boolean isGranted = state.isGranted(); 16159 // And only back up the user-twiddled state bits 16160 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16161 final String packageName = mSettings.mPackages.keyAt(i); 16162 if (!pkgGrantsKnown) { 16163 serializer.startTag(null, TAG_GRANT); 16164 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16165 pkgGrantsKnown = true; 16166 } 16167 16168 final boolean userSet = 16169 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16170 final boolean userFixed = 16171 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16172 final boolean revoke = 16173 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16174 16175 serializer.startTag(null, TAG_PERMISSION); 16176 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16177 if (isGranted) { 16178 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16179 } 16180 if (userSet) { 16181 serializer.attribute(null, ATTR_USER_SET, "true"); 16182 } 16183 if (userFixed) { 16184 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16185 } 16186 if (revoke) { 16187 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16188 } 16189 serializer.endTag(null, TAG_PERMISSION); 16190 } 16191 } 16192 } 16193 16194 if (pkgGrantsKnown) { 16195 serializer.endTag(null, TAG_GRANT); 16196 } 16197 } 16198 16199 serializer.endTag(null, TAG_ALL_GRANTS); 16200 } 16201 16202 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16203 throws XmlPullParserException, IOException { 16204 String pkgName = null; 16205 int outerDepth = parser.getDepth(); 16206 int type; 16207 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16208 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16209 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16210 continue; 16211 } 16212 16213 final String tagName = parser.getName(); 16214 if (tagName.equals(TAG_GRANT)) { 16215 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16216 if (DEBUG_BACKUP) { 16217 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16218 } 16219 } else if (tagName.equals(TAG_PERMISSION)) { 16220 16221 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16222 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16223 16224 int newFlagSet = 0; 16225 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16226 newFlagSet |= FLAG_PERMISSION_USER_SET; 16227 } 16228 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16229 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16230 } 16231 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16232 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16233 } 16234 if (DEBUG_BACKUP) { 16235 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16236 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16237 } 16238 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16239 if (ps != null) { 16240 // Already installed so we apply the grant immediately 16241 if (DEBUG_BACKUP) { 16242 Slog.v(TAG, " + already installed; applying"); 16243 } 16244 PermissionsState perms = ps.getPermissionsState(); 16245 BasePermission bp = mSettings.mPermissions.get(permName); 16246 if (bp != null) { 16247 if (isGranted) { 16248 perms.grantRuntimePermission(bp, userId); 16249 } 16250 if (newFlagSet != 0) { 16251 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16252 } 16253 } 16254 } else { 16255 // Need to wait for post-restore install to apply the grant 16256 if (DEBUG_BACKUP) { 16257 Slog.v(TAG, " - not yet installed; saving for later"); 16258 } 16259 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16260 isGranted, newFlagSet, userId); 16261 } 16262 } else { 16263 PackageManagerService.reportSettingsProblem(Log.WARN, 16264 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16265 XmlUtils.skipCurrentTag(parser); 16266 } 16267 } 16268 16269 scheduleWriteSettingsLocked(); 16270 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16271 } 16272 16273 @Override 16274 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16275 int sourceUserId, int targetUserId, int flags) { 16276 mContext.enforceCallingOrSelfPermission( 16277 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16278 int callingUid = Binder.getCallingUid(); 16279 enforceOwnerRights(ownerPackage, callingUid); 16280 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16281 if (intentFilter.countActions() == 0) { 16282 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16283 return; 16284 } 16285 synchronized (mPackages) { 16286 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16287 ownerPackage, targetUserId, flags); 16288 CrossProfileIntentResolver resolver = 16289 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16290 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16291 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16292 if (existing != null) { 16293 int size = existing.size(); 16294 for (int i = 0; i < size; i++) { 16295 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16296 return; 16297 } 16298 } 16299 } 16300 resolver.addFilter(newFilter); 16301 scheduleWritePackageRestrictionsLocked(sourceUserId); 16302 } 16303 } 16304 16305 @Override 16306 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16307 mContext.enforceCallingOrSelfPermission( 16308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16309 int callingUid = Binder.getCallingUid(); 16310 enforceOwnerRights(ownerPackage, callingUid); 16311 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16312 synchronized (mPackages) { 16313 CrossProfileIntentResolver resolver = 16314 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16315 ArraySet<CrossProfileIntentFilter> set = 16316 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16317 for (CrossProfileIntentFilter filter : set) { 16318 if (filter.getOwnerPackage().equals(ownerPackage)) { 16319 resolver.removeFilter(filter); 16320 } 16321 } 16322 scheduleWritePackageRestrictionsLocked(sourceUserId); 16323 } 16324 } 16325 16326 // Enforcing that callingUid is owning pkg on userId 16327 private void enforceOwnerRights(String pkg, int callingUid) { 16328 // The system owns everything. 16329 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16330 return; 16331 } 16332 int callingUserId = UserHandle.getUserId(callingUid); 16333 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16334 if (pi == null) { 16335 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16336 + callingUserId); 16337 } 16338 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16339 throw new SecurityException("Calling uid " + callingUid 16340 + " does not own package " + pkg); 16341 } 16342 } 16343 16344 @Override 16345 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16346 Intent intent = new Intent(Intent.ACTION_MAIN); 16347 intent.addCategory(Intent.CATEGORY_HOME); 16348 16349 final int callingUserId = UserHandle.getCallingUserId(); 16350 List<ResolveInfo> list = queryIntentActivities(intent, null, 16351 PackageManager.GET_META_DATA, callingUserId); 16352 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16353 true, false, false, callingUserId); 16354 16355 allHomeCandidates.clear(); 16356 if (list != null) { 16357 for (ResolveInfo ri : list) { 16358 allHomeCandidates.add(ri); 16359 } 16360 } 16361 return (preferred == null || preferred.activityInfo == null) 16362 ? null 16363 : new ComponentName(preferred.activityInfo.packageName, 16364 preferred.activityInfo.name); 16365 } 16366 16367 @Override 16368 public void setApplicationEnabledSetting(String appPackageName, 16369 int newState, int flags, int userId, String callingPackage) { 16370 if (!sUserManager.exists(userId)) return; 16371 if (callingPackage == null) { 16372 callingPackage = Integer.toString(Binder.getCallingUid()); 16373 } 16374 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16375 } 16376 16377 @Override 16378 public void setComponentEnabledSetting(ComponentName componentName, 16379 int newState, int flags, int userId) { 16380 if (!sUserManager.exists(userId)) return; 16381 setEnabledSetting(componentName.getPackageName(), 16382 componentName.getClassName(), newState, flags, userId, null); 16383 } 16384 16385 private void setEnabledSetting(final String packageName, String className, int newState, 16386 final int flags, int userId, String callingPackage) { 16387 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16388 || newState == COMPONENT_ENABLED_STATE_ENABLED 16389 || newState == COMPONENT_ENABLED_STATE_DISABLED 16390 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16391 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16392 throw new IllegalArgumentException("Invalid new component state: " 16393 + newState); 16394 } 16395 PackageSetting pkgSetting; 16396 final int uid = Binder.getCallingUid(); 16397 final int permission = mContext.checkCallingOrSelfPermission( 16398 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16399 enforceCrossUserPermission(uid, userId, 16400 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16401 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16402 boolean sendNow = false; 16403 boolean isApp = (className == null); 16404 String componentName = isApp ? packageName : className; 16405 int packageUid = -1; 16406 ArrayList<String> components; 16407 16408 // writer 16409 synchronized (mPackages) { 16410 pkgSetting = mSettings.mPackages.get(packageName); 16411 if (pkgSetting == null) { 16412 if (className == null) { 16413 throw new IllegalArgumentException("Unknown package: " + packageName); 16414 } 16415 throw new IllegalArgumentException( 16416 "Unknown component: " + packageName + "/" + className); 16417 } 16418 // Allow root and verify that userId is not being specified by a different user 16419 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16420 throw new SecurityException( 16421 "Permission Denial: attempt to change component state from pid=" 16422 + Binder.getCallingPid() 16423 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16424 } 16425 if (className == null) { 16426 // We're dealing with an application/package level state change 16427 if (pkgSetting.getEnabled(userId) == newState) { 16428 // Nothing to do 16429 return; 16430 } 16431 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16432 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16433 // Don't care about who enables an app. 16434 callingPackage = null; 16435 } 16436 pkgSetting.setEnabled(newState, userId, callingPackage); 16437 // pkgSetting.pkg.mSetEnabled = newState; 16438 } else { 16439 // We're dealing with a component level state change 16440 // First, verify that this is a valid class name. 16441 PackageParser.Package pkg = pkgSetting.pkg; 16442 if (pkg == null || !pkg.hasComponentClassName(className)) { 16443 if (pkg != null && 16444 pkg.applicationInfo.targetSdkVersion >= 16445 Build.VERSION_CODES.JELLY_BEAN) { 16446 throw new IllegalArgumentException("Component class " + className 16447 + " does not exist in " + packageName); 16448 } else { 16449 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16450 + className + " does not exist in " + packageName); 16451 } 16452 } 16453 switch (newState) { 16454 case COMPONENT_ENABLED_STATE_ENABLED: 16455 if (!pkgSetting.enableComponentLPw(className, userId)) { 16456 return; 16457 } 16458 break; 16459 case COMPONENT_ENABLED_STATE_DISABLED: 16460 if (!pkgSetting.disableComponentLPw(className, userId)) { 16461 return; 16462 } 16463 break; 16464 case COMPONENT_ENABLED_STATE_DEFAULT: 16465 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16466 return; 16467 } 16468 break; 16469 default: 16470 Slog.e(TAG, "Invalid new component state: " + newState); 16471 return; 16472 } 16473 } 16474 scheduleWritePackageRestrictionsLocked(userId); 16475 components = mPendingBroadcasts.get(userId, packageName); 16476 final boolean newPackage = components == null; 16477 if (newPackage) { 16478 components = new ArrayList<String>(); 16479 } 16480 if (!components.contains(componentName)) { 16481 components.add(componentName); 16482 } 16483 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16484 sendNow = true; 16485 // Purge entry from pending broadcast list if another one exists already 16486 // since we are sending one right away. 16487 mPendingBroadcasts.remove(userId, packageName); 16488 } else { 16489 if (newPackage) { 16490 mPendingBroadcasts.put(userId, packageName, components); 16491 } 16492 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16493 // Schedule a message 16494 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16495 } 16496 } 16497 } 16498 16499 long callingId = Binder.clearCallingIdentity(); 16500 try { 16501 if (sendNow) { 16502 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16503 sendPackageChangedBroadcast(packageName, 16504 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16505 } 16506 } finally { 16507 Binder.restoreCallingIdentity(callingId); 16508 } 16509 } 16510 16511 private void sendPackageChangedBroadcast(String packageName, 16512 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16513 if (DEBUG_INSTALL) 16514 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16515 + componentNames); 16516 Bundle extras = new Bundle(4); 16517 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16518 String nameList[] = new String[componentNames.size()]; 16519 componentNames.toArray(nameList); 16520 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16521 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16522 extras.putInt(Intent.EXTRA_UID, packageUid); 16523 // If this is not reporting a change of the overall package, then only send it 16524 // to registered receivers. We don't want to launch a swath of apps for every 16525 // little component state change. 16526 final int flags = !componentNames.contains(packageName) 16527 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16528 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16529 new int[] {UserHandle.getUserId(packageUid)}); 16530 } 16531 16532 @Override 16533 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16534 if (!sUserManager.exists(userId)) return; 16535 final int uid = Binder.getCallingUid(); 16536 final int permission = mContext.checkCallingOrSelfPermission( 16537 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16538 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16539 enforceCrossUserPermission(uid, userId, 16540 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16541 // writer 16542 synchronized (mPackages) { 16543 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16544 allowedByPermission, uid, userId)) { 16545 scheduleWritePackageRestrictionsLocked(userId); 16546 } 16547 } 16548 } 16549 16550 @Override 16551 public String getInstallerPackageName(String packageName) { 16552 // reader 16553 synchronized (mPackages) { 16554 return mSettings.getInstallerPackageNameLPr(packageName); 16555 } 16556 } 16557 16558 @Override 16559 public int getApplicationEnabledSetting(String packageName, int userId) { 16560 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16561 int uid = Binder.getCallingUid(); 16562 enforceCrossUserPermission(uid, userId, 16563 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16564 // reader 16565 synchronized (mPackages) { 16566 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16567 } 16568 } 16569 16570 @Override 16571 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16572 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16573 int uid = Binder.getCallingUid(); 16574 enforceCrossUserPermission(uid, userId, 16575 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16576 // reader 16577 synchronized (mPackages) { 16578 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16579 } 16580 } 16581 16582 @Override 16583 public void enterSafeMode() { 16584 enforceSystemOrRoot("Only the system can request entering safe mode"); 16585 16586 if (!mSystemReady) { 16587 mSafeMode = true; 16588 } 16589 } 16590 16591 @Override 16592 public void systemReady() { 16593 mSystemReady = true; 16594 16595 // Read the compatibilty setting when the system is ready. 16596 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16597 mContext.getContentResolver(), 16598 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16599 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16600 if (DEBUG_SETTINGS) { 16601 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16602 } 16603 16604 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16605 16606 synchronized (mPackages) { 16607 // Verify that all of the preferred activity components actually 16608 // exist. It is possible for applications to be updated and at 16609 // that point remove a previously declared activity component that 16610 // had been set as a preferred activity. We try to clean this up 16611 // the next time we encounter that preferred activity, but it is 16612 // possible for the user flow to never be able to return to that 16613 // situation so here we do a sanity check to make sure we haven't 16614 // left any junk around. 16615 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16616 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16617 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16618 removed.clear(); 16619 for (PreferredActivity pa : pir.filterSet()) { 16620 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16621 removed.add(pa); 16622 } 16623 } 16624 if (removed.size() > 0) { 16625 for (int r=0; r<removed.size(); r++) { 16626 PreferredActivity pa = removed.get(r); 16627 Slog.w(TAG, "Removing dangling preferred activity: " 16628 + pa.mPref.mComponent); 16629 pir.removeFilter(pa); 16630 } 16631 mSettings.writePackageRestrictionsLPr( 16632 mSettings.mPreferredActivities.keyAt(i)); 16633 } 16634 } 16635 16636 for (int userId : UserManagerService.getInstance().getUserIds()) { 16637 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16638 grantPermissionsUserIds = ArrayUtils.appendInt( 16639 grantPermissionsUserIds, userId); 16640 } 16641 } 16642 } 16643 sUserManager.systemReady(); 16644 16645 // If we upgraded grant all default permissions before kicking off. 16646 for (int userId : grantPermissionsUserIds) { 16647 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16648 } 16649 16650 // Kick off any messages waiting for system ready 16651 if (mPostSystemReadyMessages != null) { 16652 for (Message msg : mPostSystemReadyMessages) { 16653 msg.sendToTarget(); 16654 } 16655 mPostSystemReadyMessages = null; 16656 } 16657 16658 // Watch for external volumes that come and go over time 16659 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16660 storage.registerListener(mStorageListener); 16661 16662 mInstallerService.systemReady(); 16663 mPackageDexOptimizer.systemReady(); 16664 16665 MountServiceInternal mountServiceInternal = LocalServices.getService( 16666 MountServiceInternal.class); 16667 mountServiceInternal.addExternalStoragePolicy( 16668 new MountServiceInternal.ExternalStorageMountPolicy() { 16669 @Override 16670 public int getMountMode(int uid, String packageName) { 16671 if (Process.isIsolated(uid)) { 16672 return Zygote.MOUNT_EXTERNAL_NONE; 16673 } 16674 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16675 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16676 } 16677 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16678 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16679 } 16680 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16681 return Zygote.MOUNT_EXTERNAL_READ; 16682 } 16683 return Zygote.MOUNT_EXTERNAL_WRITE; 16684 } 16685 16686 @Override 16687 public boolean hasExternalStorage(int uid, String packageName) { 16688 return true; 16689 } 16690 }); 16691 } 16692 16693 @Override 16694 public boolean isSafeMode() { 16695 return mSafeMode; 16696 } 16697 16698 @Override 16699 public boolean hasSystemUidErrors() { 16700 return mHasSystemUidErrors; 16701 } 16702 16703 static String arrayToString(int[] array) { 16704 StringBuffer buf = new StringBuffer(128); 16705 buf.append('['); 16706 if (array != null) { 16707 for (int i=0; i<array.length; i++) { 16708 if (i > 0) buf.append(", "); 16709 buf.append(array[i]); 16710 } 16711 } 16712 buf.append(']'); 16713 return buf.toString(); 16714 } 16715 16716 static class DumpState { 16717 public static final int DUMP_LIBS = 1 << 0; 16718 public static final int DUMP_FEATURES = 1 << 1; 16719 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16720 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16721 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16722 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16723 public static final int DUMP_PERMISSIONS = 1 << 6; 16724 public static final int DUMP_PACKAGES = 1 << 7; 16725 public static final int DUMP_SHARED_USERS = 1 << 8; 16726 public static final int DUMP_MESSAGES = 1 << 9; 16727 public static final int DUMP_PROVIDERS = 1 << 10; 16728 public static final int DUMP_VERIFIERS = 1 << 11; 16729 public static final int DUMP_PREFERRED = 1 << 12; 16730 public static final int DUMP_PREFERRED_XML = 1 << 13; 16731 public static final int DUMP_KEYSETS = 1 << 14; 16732 public static final int DUMP_VERSION = 1 << 15; 16733 public static final int DUMP_INSTALLS = 1 << 16; 16734 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16735 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16736 16737 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16738 16739 private int mTypes; 16740 16741 private int mOptions; 16742 16743 private boolean mTitlePrinted; 16744 16745 private SharedUserSetting mSharedUser; 16746 16747 public boolean isDumping(int type) { 16748 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16749 return true; 16750 } 16751 16752 return (mTypes & type) != 0; 16753 } 16754 16755 public void setDump(int type) { 16756 mTypes |= type; 16757 } 16758 16759 public boolean isOptionEnabled(int option) { 16760 return (mOptions & option) != 0; 16761 } 16762 16763 public void setOptionEnabled(int option) { 16764 mOptions |= option; 16765 } 16766 16767 public boolean onTitlePrinted() { 16768 final boolean printed = mTitlePrinted; 16769 mTitlePrinted = true; 16770 return printed; 16771 } 16772 16773 public boolean getTitlePrinted() { 16774 return mTitlePrinted; 16775 } 16776 16777 public void setTitlePrinted(boolean enabled) { 16778 mTitlePrinted = enabled; 16779 } 16780 16781 public SharedUserSetting getSharedUser() { 16782 return mSharedUser; 16783 } 16784 16785 public void setSharedUser(SharedUserSetting user) { 16786 mSharedUser = user; 16787 } 16788 } 16789 16790 @Override 16791 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16792 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16793 (new PackageManagerShellCommand(this)).exec( 16794 this, in, out, err, args, resultReceiver); 16795 } 16796 16797 @Override 16798 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16799 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16800 != PackageManager.PERMISSION_GRANTED) { 16801 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16802 + Binder.getCallingPid() 16803 + ", uid=" + Binder.getCallingUid() 16804 + " without permission " 16805 + android.Manifest.permission.DUMP); 16806 return; 16807 } 16808 16809 DumpState dumpState = new DumpState(); 16810 boolean fullPreferred = false; 16811 boolean checkin = false; 16812 16813 String packageName = null; 16814 ArraySet<String> permissionNames = null; 16815 16816 int opti = 0; 16817 while (opti < args.length) { 16818 String opt = args[opti]; 16819 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16820 break; 16821 } 16822 opti++; 16823 16824 if ("-a".equals(opt)) { 16825 // Right now we only know how to print all. 16826 } else if ("-h".equals(opt)) { 16827 pw.println("Package manager dump options:"); 16828 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16829 pw.println(" --checkin: dump for a checkin"); 16830 pw.println(" -f: print details of intent filters"); 16831 pw.println(" -h: print this help"); 16832 pw.println(" cmd may be one of:"); 16833 pw.println(" l[ibraries]: list known shared libraries"); 16834 pw.println(" f[eatures]: list device features"); 16835 pw.println(" k[eysets]: print known keysets"); 16836 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16837 pw.println(" perm[issions]: dump permissions"); 16838 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16839 pw.println(" pref[erred]: print preferred package settings"); 16840 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16841 pw.println(" prov[iders]: dump content providers"); 16842 pw.println(" p[ackages]: dump installed packages"); 16843 pw.println(" s[hared-users]: dump shared user IDs"); 16844 pw.println(" m[essages]: print collected runtime messages"); 16845 pw.println(" v[erifiers]: print package verifier info"); 16846 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16847 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16848 pw.println(" version: print database version info"); 16849 pw.println(" write: write current settings now"); 16850 pw.println(" installs: details about install sessions"); 16851 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16852 pw.println(" <package.name>: info about given package"); 16853 return; 16854 } else if ("--checkin".equals(opt)) { 16855 checkin = true; 16856 } else if ("-f".equals(opt)) { 16857 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16858 } else { 16859 pw.println("Unknown argument: " + opt + "; use -h for help"); 16860 } 16861 } 16862 16863 // Is the caller requesting to dump a particular piece of data? 16864 if (opti < args.length) { 16865 String cmd = args[opti]; 16866 opti++; 16867 // Is this a package name? 16868 if ("android".equals(cmd) || cmd.contains(".")) { 16869 packageName = cmd; 16870 // When dumping a single package, we always dump all of its 16871 // filter information since the amount of data will be reasonable. 16872 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16873 } else if ("check-permission".equals(cmd)) { 16874 if (opti >= args.length) { 16875 pw.println("Error: check-permission missing permission argument"); 16876 return; 16877 } 16878 String perm = args[opti]; 16879 opti++; 16880 if (opti >= args.length) { 16881 pw.println("Error: check-permission missing package argument"); 16882 return; 16883 } 16884 String pkg = args[opti]; 16885 opti++; 16886 int user = UserHandle.getUserId(Binder.getCallingUid()); 16887 if (opti < args.length) { 16888 try { 16889 user = Integer.parseInt(args[opti]); 16890 } catch (NumberFormatException e) { 16891 pw.println("Error: check-permission user argument is not a number: " 16892 + args[opti]); 16893 return; 16894 } 16895 } 16896 pw.println(checkPermission(perm, pkg, user)); 16897 return; 16898 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16899 dumpState.setDump(DumpState.DUMP_LIBS); 16900 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16901 dumpState.setDump(DumpState.DUMP_FEATURES); 16902 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16903 if (opti >= args.length) { 16904 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16905 | DumpState.DUMP_SERVICE_RESOLVERS 16906 | DumpState.DUMP_RECEIVER_RESOLVERS 16907 | DumpState.DUMP_CONTENT_RESOLVERS); 16908 } else { 16909 while (opti < args.length) { 16910 String name = args[opti]; 16911 if ("a".equals(name) || "activity".equals(name)) { 16912 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16913 } else if ("s".equals(name) || "service".equals(name)) { 16914 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16915 } else if ("r".equals(name) || "receiver".equals(name)) { 16916 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16917 } else if ("c".equals(name) || "content".equals(name)) { 16918 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16919 } else { 16920 pw.println("Error: unknown resolver table type: " + name); 16921 return; 16922 } 16923 opti++; 16924 } 16925 } 16926 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16927 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16928 } else if ("permission".equals(cmd)) { 16929 if (opti >= args.length) { 16930 pw.println("Error: permission requires permission name"); 16931 return; 16932 } 16933 permissionNames = new ArraySet<>(); 16934 while (opti < args.length) { 16935 permissionNames.add(args[opti]); 16936 opti++; 16937 } 16938 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16939 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16940 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16941 dumpState.setDump(DumpState.DUMP_PREFERRED); 16942 } else if ("preferred-xml".equals(cmd)) { 16943 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16944 if (opti < args.length && "--full".equals(args[opti])) { 16945 fullPreferred = true; 16946 opti++; 16947 } 16948 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16949 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16950 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16951 dumpState.setDump(DumpState.DUMP_PACKAGES); 16952 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16953 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16954 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16955 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16956 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16957 dumpState.setDump(DumpState.DUMP_MESSAGES); 16958 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16959 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16960 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16961 || "intent-filter-verifiers".equals(cmd)) { 16962 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16963 } else if ("version".equals(cmd)) { 16964 dumpState.setDump(DumpState.DUMP_VERSION); 16965 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16966 dumpState.setDump(DumpState.DUMP_KEYSETS); 16967 } else if ("installs".equals(cmd)) { 16968 dumpState.setDump(DumpState.DUMP_INSTALLS); 16969 } else if ("write".equals(cmd)) { 16970 synchronized (mPackages) { 16971 mSettings.writeLPr(); 16972 pw.println("Settings written."); 16973 return; 16974 } 16975 } 16976 } 16977 16978 if (checkin) { 16979 pw.println("vers,1"); 16980 } 16981 16982 // reader 16983 synchronized (mPackages) { 16984 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16985 if (!checkin) { 16986 if (dumpState.onTitlePrinted()) 16987 pw.println(); 16988 pw.println("Database versions:"); 16989 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16990 } 16991 } 16992 16993 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16994 if (!checkin) { 16995 if (dumpState.onTitlePrinted()) 16996 pw.println(); 16997 pw.println("Verifiers:"); 16998 pw.print(" Required: "); 16999 pw.print(mRequiredVerifierPackage); 17000 pw.print(" (uid="); 17001 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17002 UserHandle.USER_SYSTEM)); 17003 pw.println(")"); 17004 } else if (mRequiredVerifierPackage != null) { 17005 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17006 pw.print(","); 17007 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17008 UserHandle.USER_SYSTEM)); 17009 } 17010 } 17011 17012 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17013 packageName == null) { 17014 if (mIntentFilterVerifierComponent != null) { 17015 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17016 if (!checkin) { 17017 if (dumpState.onTitlePrinted()) 17018 pw.println(); 17019 pw.println("Intent Filter Verifier:"); 17020 pw.print(" Using: "); 17021 pw.print(verifierPackageName); 17022 pw.print(" (uid="); 17023 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17024 UserHandle.USER_SYSTEM)); 17025 pw.println(")"); 17026 } else if (verifierPackageName != null) { 17027 pw.print("ifv,"); pw.print(verifierPackageName); 17028 pw.print(","); 17029 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17030 UserHandle.USER_SYSTEM)); 17031 } 17032 } else { 17033 pw.println(); 17034 pw.println("No Intent Filter Verifier available!"); 17035 } 17036 } 17037 17038 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17039 boolean printedHeader = false; 17040 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17041 while (it.hasNext()) { 17042 String name = it.next(); 17043 SharedLibraryEntry ent = mSharedLibraries.get(name); 17044 if (!checkin) { 17045 if (!printedHeader) { 17046 if (dumpState.onTitlePrinted()) 17047 pw.println(); 17048 pw.println("Libraries:"); 17049 printedHeader = true; 17050 } 17051 pw.print(" "); 17052 } else { 17053 pw.print("lib,"); 17054 } 17055 pw.print(name); 17056 if (!checkin) { 17057 pw.print(" -> "); 17058 } 17059 if (ent.path != null) { 17060 if (!checkin) { 17061 pw.print("(jar) "); 17062 pw.print(ent.path); 17063 } else { 17064 pw.print(",jar,"); 17065 pw.print(ent.path); 17066 } 17067 } else { 17068 if (!checkin) { 17069 pw.print("(apk) "); 17070 pw.print(ent.apk); 17071 } else { 17072 pw.print(",apk,"); 17073 pw.print(ent.apk); 17074 } 17075 } 17076 pw.println(); 17077 } 17078 } 17079 17080 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17081 if (dumpState.onTitlePrinted()) 17082 pw.println(); 17083 if (!checkin) { 17084 pw.println("Features:"); 17085 } 17086 17087 for (FeatureInfo feat : mAvailableFeatures.values()) { 17088 if (checkin) { 17089 pw.print("feat,"); 17090 pw.print(feat.name); 17091 pw.print(","); 17092 pw.println(feat.version); 17093 } else { 17094 pw.print(" "); 17095 pw.print(feat.name); 17096 if (feat.version > 0) { 17097 pw.print(" version="); 17098 pw.print(feat.version); 17099 } 17100 pw.println(); 17101 } 17102 } 17103 } 17104 17105 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17106 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17107 : "Activity Resolver Table:", " ", packageName, 17108 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17109 dumpState.setTitlePrinted(true); 17110 } 17111 } 17112 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17113 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17114 : "Receiver Resolver Table:", " ", packageName, 17115 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17116 dumpState.setTitlePrinted(true); 17117 } 17118 } 17119 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17120 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17121 : "Service Resolver Table:", " ", packageName, 17122 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17123 dumpState.setTitlePrinted(true); 17124 } 17125 } 17126 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17127 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17128 : "Provider Resolver Table:", " ", packageName, 17129 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17130 dumpState.setTitlePrinted(true); 17131 } 17132 } 17133 17134 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17135 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17136 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17137 int user = mSettings.mPreferredActivities.keyAt(i); 17138 if (pir.dump(pw, 17139 dumpState.getTitlePrinted() 17140 ? "\nPreferred Activities User " + user + ":" 17141 : "Preferred Activities User " + user + ":", " ", 17142 packageName, true, false)) { 17143 dumpState.setTitlePrinted(true); 17144 } 17145 } 17146 } 17147 17148 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17149 pw.flush(); 17150 FileOutputStream fout = new FileOutputStream(fd); 17151 BufferedOutputStream str = new BufferedOutputStream(fout); 17152 XmlSerializer serializer = new FastXmlSerializer(); 17153 try { 17154 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17155 serializer.startDocument(null, true); 17156 serializer.setFeature( 17157 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17158 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17159 serializer.endDocument(); 17160 serializer.flush(); 17161 } catch (IllegalArgumentException e) { 17162 pw.println("Failed writing: " + e); 17163 } catch (IllegalStateException e) { 17164 pw.println("Failed writing: " + e); 17165 } catch (IOException e) { 17166 pw.println("Failed writing: " + e); 17167 } 17168 } 17169 17170 if (!checkin 17171 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17172 && packageName == null) { 17173 pw.println(); 17174 int count = mSettings.mPackages.size(); 17175 if (count == 0) { 17176 pw.println("No applications!"); 17177 pw.println(); 17178 } else { 17179 final String prefix = " "; 17180 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17181 if (allPackageSettings.size() == 0) { 17182 pw.println("No domain preferred apps!"); 17183 pw.println(); 17184 } else { 17185 pw.println("App verification status:"); 17186 pw.println(); 17187 count = 0; 17188 for (PackageSetting ps : allPackageSettings) { 17189 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17190 if (ivi == null || ivi.getPackageName() == null) continue; 17191 pw.println(prefix + "Package: " + ivi.getPackageName()); 17192 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17193 pw.println(prefix + "Status: " + ivi.getStatusString()); 17194 pw.println(); 17195 count++; 17196 } 17197 if (count == 0) { 17198 pw.println(prefix + "No app verification established."); 17199 pw.println(); 17200 } 17201 for (int userId : sUserManager.getUserIds()) { 17202 pw.println("App linkages for user " + userId + ":"); 17203 pw.println(); 17204 count = 0; 17205 for (PackageSetting ps : allPackageSettings) { 17206 final long status = ps.getDomainVerificationStatusForUser(userId); 17207 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17208 continue; 17209 } 17210 pw.println(prefix + "Package: " + ps.name); 17211 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17212 String statusStr = IntentFilterVerificationInfo. 17213 getStatusStringFromValue(status); 17214 pw.println(prefix + "Status: " + statusStr); 17215 pw.println(); 17216 count++; 17217 } 17218 if (count == 0) { 17219 pw.println(prefix + "No configured app linkages."); 17220 pw.println(); 17221 } 17222 } 17223 } 17224 } 17225 } 17226 17227 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17228 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17229 if (packageName == null && permissionNames == null) { 17230 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17231 if (iperm == 0) { 17232 if (dumpState.onTitlePrinted()) 17233 pw.println(); 17234 pw.println("AppOp Permissions:"); 17235 } 17236 pw.print(" AppOp Permission "); 17237 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17238 pw.println(":"); 17239 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17240 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17241 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17242 } 17243 } 17244 } 17245 } 17246 17247 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17248 boolean printedSomething = false; 17249 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17250 if (packageName != null && !packageName.equals(p.info.packageName)) { 17251 continue; 17252 } 17253 if (!printedSomething) { 17254 if (dumpState.onTitlePrinted()) 17255 pw.println(); 17256 pw.println("Registered ContentProviders:"); 17257 printedSomething = true; 17258 } 17259 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17260 pw.print(" "); pw.println(p.toString()); 17261 } 17262 printedSomething = false; 17263 for (Map.Entry<String, PackageParser.Provider> entry : 17264 mProvidersByAuthority.entrySet()) { 17265 PackageParser.Provider p = entry.getValue(); 17266 if (packageName != null && !packageName.equals(p.info.packageName)) { 17267 continue; 17268 } 17269 if (!printedSomething) { 17270 if (dumpState.onTitlePrinted()) 17271 pw.println(); 17272 pw.println("ContentProvider Authorities:"); 17273 printedSomething = true; 17274 } 17275 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17276 pw.print(" "); pw.println(p.toString()); 17277 if (p.info != null && p.info.applicationInfo != null) { 17278 final String appInfo = p.info.applicationInfo.toString(); 17279 pw.print(" applicationInfo="); pw.println(appInfo); 17280 } 17281 } 17282 } 17283 17284 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17285 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17286 } 17287 17288 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17289 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17290 } 17291 17292 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17293 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17294 } 17295 17296 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17297 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17298 } 17299 17300 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17301 // XXX should handle packageName != null by dumping only install data that 17302 // the given package is involved with. 17303 if (dumpState.onTitlePrinted()) pw.println(); 17304 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17305 } 17306 17307 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17308 if (dumpState.onTitlePrinted()) pw.println(); 17309 mSettings.dumpReadMessagesLPr(pw, dumpState); 17310 17311 pw.println(); 17312 pw.println("Package warning messages:"); 17313 BufferedReader in = null; 17314 String line = null; 17315 try { 17316 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17317 while ((line = in.readLine()) != null) { 17318 if (line.contains("ignored: updated version")) continue; 17319 pw.println(line); 17320 } 17321 } catch (IOException ignored) { 17322 } finally { 17323 IoUtils.closeQuietly(in); 17324 } 17325 } 17326 17327 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17328 BufferedReader in = null; 17329 String line = null; 17330 try { 17331 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17332 while ((line = in.readLine()) != null) { 17333 if (line.contains("ignored: updated version")) continue; 17334 pw.print("msg,"); 17335 pw.println(line); 17336 } 17337 } catch (IOException ignored) { 17338 } finally { 17339 IoUtils.closeQuietly(in); 17340 } 17341 } 17342 } 17343 } 17344 17345 private String dumpDomainString(String packageName) { 17346 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 17347 List<IntentFilter> filters = getAllIntentFilters(packageName); 17348 17349 ArraySet<String> result = new ArraySet<>(); 17350 if (iviList.size() > 0) { 17351 for (IntentFilterVerificationInfo ivi : iviList) { 17352 for (String host : ivi.getDomains()) { 17353 result.add(host); 17354 } 17355 } 17356 } 17357 if (filters != null && filters.size() > 0) { 17358 for (IntentFilter filter : filters) { 17359 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17360 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17361 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17362 result.addAll(filter.getHostsList()); 17363 } 17364 } 17365 } 17366 17367 StringBuilder sb = new StringBuilder(result.size() * 16); 17368 for (String domain : result) { 17369 if (sb.length() > 0) sb.append(" "); 17370 sb.append(domain); 17371 } 17372 return sb.toString(); 17373 } 17374 17375 // ------- apps on sdcard specific code ------- 17376 static final boolean DEBUG_SD_INSTALL = false; 17377 17378 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17379 17380 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17381 17382 private boolean mMediaMounted = false; 17383 17384 static String getEncryptKey() { 17385 try { 17386 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17387 SD_ENCRYPTION_KEYSTORE_NAME); 17388 if (sdEncKey == null) { 17389 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17390 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17391 if (sdEncKey == null) { 17392 Slog.e(TAG, "Failed to create encryption keys"); 17393 return null; 17394 } 17395 } 17396 return sdEncKey; 17397 } catch (NoSuchAlgorithmException nsae) { 17398 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17399 return null; 17400 } catch (IOException ioe) { 17401 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17402 return null; 17403 } 17404 } 17405 17406 /* 17407 * Update media status on PackageManager. 17408 */ 17409 @Override 17410 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17411 int callingUid = Binder.getCallingUid(); 17412 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17413 throw new SecurityException("Media status can only be updated by the system"); 17414 } 17415 // reader; this apparently protects mMediaMounted, but should probably 17416 // be a different lock in that case. 17417 synchronized (mPackages) { 17418 Log.i(TAG, "Updating external media status from " 17419 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17420 + (mediaStatus ? "mounted" : "unmounted")); 17421 if (DEBUG_SD_INSTALL) 17422 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17423 + ", mMediaMounted=" + mMediaMounted); 17424 if (mediaStatus == mMediaMounted) { 17425 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17426 : 0, -1); 17427 mHandler.sendMessage(msg); 17428 return; 17429 } 17430 mMediaMounted = mediaStatus; 17431 } 17432 // Queue up an async operation since the package installation may take a 17433 // little while. 17434 mHandler.post(new Runnable() { 17435 public void run() { 17436 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17437 } 17438 }); 17439 } 17440 17441 /** 17442 * Called by MountService when the initial ASECs to scan are available. 17443 * Should block until all the ASEC containers are finished being scanned. 17444 */ 17445 public void scanAvailableAsecs() { 17446 updateExternalMediaStatusInner(true, false, false); 17447 } 17448 17449 /* 17450 * Collect information of applications on external media, map them against 17451 * existing containers and update information based on current mount status. 17452 * Please note that we always have to report status if reportStatus has been 17453 * set to true especially when unloading packages. 17454 */ 17455 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17456 boolean externalStorage) { 17457 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17458 int[] uidArr = EmptyArray.INT; 17459 17460 final String[] list = PackageHelper.getSecureContainerList(); 17461 if (ArrayUtils.isEmpty(list)) { 17462 Log.i(TAG, "No secure containers found"); 17463 } else { 17464 // Process list of secure containers and categorize them 17465 // as active or stale based on their package internal state. 17466 17467 // reader 17468 synchronized (mPackages) { 17469 for (String cid : list) { 17470 // Leave stages untouched for now; installer service owns them 17471 if (PackageInstallerService.isStageName(cid)) continue; 17472 17473 if (DEBUG_SD_INSTALL) 17474 Log.i(TAG, "Processing container " + cid); 17475 String pkgName = getAsecPackageName(cid); 17476 if (pkgName == null) { 17477 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17478 continue; 17479 } 17480 if (DEBUG_SD_INSTALL) 17481 Log.i(TAG, "Looking for pkg : " + pkgName); 17482 17483 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17484 if (ps == null) { 17485 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17486 continue; 17487 } 17488 17489 /* 17490 * Skip packages that are not external if we're unmounting 17491 * external storage. 17492 */ 17493 if (externalStorage && !isMounted && !isExternal(ps)) { 17494 continue; 17495 } 17496 17497 final AsecInstallArgs args = new AsecInstallArgs(cid, 17498 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17499 // The package status is changed only if the code path 17500 // matches between settings and the container id. 17501 if (ps.codePathString != null 17502 && ps.codePathString.startsWith(args.getCodePath())) { 17503 if (DEBUG_SD_INSTALL) { 17504 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17505 + " at code path: " + ps.codePathString); 17506 } 17507 17508 // We do have a valid package installed on sdcard 17509 processCids.put(args, ps.codePathString); 17510 final int uid = ps.appId; 17511 if (uid != -1) { 17512 uidArr = ArrayUtils.appendInt(uidArr, uid); 17513 } 17514 } else { 17515 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17516 + ps.codePathString); 17517 } 17518 } 17519 } 17520 17521 Arrays.sort(uidArr); 17522 } 17523 17524 // Process packages with valid entries. 17525 if (isMounted) { 17526 if (DEBUG_SD_INSTALL) 17527 Log.i(TAG, "Loading packages"); 17528 loadMediaPackages(processCids, uidArr, externalStorage); 17529 startCleaningPackages(); 17530 mInstallerService.onSecureContainersAvailable(); 17531 } else { 17532 if (DEBUG_SD_INSTALL) 17533 Log.i(TAG, "Unloading packages"); 17534 unloadMediaPackages(processCids, uidArr, reportStatus); 17535 } 17536 } 17537 17538 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17539 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17540 final int size = infos.size(); 17541 final String[] packageNames = new String[size]; 17542 final int[] packageUids = new int[size]; 17543 for (int i = 0; i < size; i++) { 17544 final ApplicationInfo info = infos.get(i); 17545 packageNames[i] = info.packageName; 17546 packageUids[i] = info.uid; 17547 } 17548 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17549 finishedReceiver); 17550 } 17551 17552 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17553 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17554 sendResourcesChangedBroadcast(mediaStatus, replacing, 17555 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17556 } 17557 17558 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17559 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17560 int size = pkgList.length; 17561 if (size > 0) { 17562 // Send broadcasts here 17563 Bundle extras = new Bundle(); 17564 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17565 if (uidArr != null) { 17566 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17567 } 17568 if (replacing) { 17569 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17570 } 17571 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17572 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17573 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17574 } 17575 } 17576 17577 /* 17578 * Look at potentially valid container ids from processCids If package 17579 * information doesn't match the one on record or package scanning fails, 17580 * the cid is added to list of removeCids. We currently don't delete stale 17581 * containers. 17582 */ 17583 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17584 boolean externalStorage) { 17585 ArrayList<String> pkgList = new ArrayList<String>(); 17586 Set<AsecInstallArgs> keys = processCids.keySet(); 17587 17588 for (AsecInstallArgs args : keys) { 17589 String codePath = processCids.get(args); 17590 if (DEBUG_SD_INSTALL) 17591 Log.i(TAG, "Loading container : " + args.cid); 17592 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17593 try { 17594 // Make sure there are no container errors first. 17595 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17596 Slog.e(TAG, "Failed to mount cid : " + args.cid 17597 + " when installing from sdcard"); 17598 continue; 17599 } 17600 // Check code path here. 17601 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17602 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17603 + " does not match one in settings " + codePath); 17604 continue; 17605 } 17606 // Parse package 17607 int parseFlags = mDefParseFlags; 17608 if (args.isExternalAsec()) { 17609 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17610 } 17611 if (args.isFwdLocked()) { 17612 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17613 } 17614 17615 synchronized (mInstallLock) { 17616 PackageParser.Package pkg = null; 17617 try { 17618 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17619 } catch (PackageManagerException e) { 17620 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17621 } 17622 // Scan the package 17623 if (pkg != null) { 17624 /* 17625 * TODO why is the lock being held? doPostInstall is 17626 * called in other places without the lock. This needs 17627 * to be straightened out. 17628 */ 17629 // writer 17630 synchronized (mPackages) { 17631 retCode = PackageManager.INSTALL_SUCCEEDED; 17632 pkgList.add(pkg.packageName); 17633 // Post process args 17634 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17635 pkg.applicationInfo.uid); 17636 } 17637 } else { 17638 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17639 } 17640 } 17641 17642 } finally { 17643 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17644 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17645 } 17646 } 17647 } 17648 // writer 17649 synchronized (mPackages) { 17650 // If the platform SDK has changed since the last time we booted, 17651 // we need to re-grant app permission to catch any new ones that 17652 // appear. This is really a hack, and means that apps can in some 17653 // cases get permissions that the user didn't initially explicitly 17654 // allow... it would be nice to have some better way to handle 17655 // this situation. 17656 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17657 : mSettings.getInternalVersion(); 17658 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17659 : StorageManager.UUID_PRIVATE_INTERNAL; 17660 17661 int updateFlags = UPDATE_PERMISSIONS_ALL; 17662 if (ver.sdkVersion != mSdkVersion) { 17663 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17664 + mSdkVersion + "; regranting permissions for external"); 17665 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17666 } 17667 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17668 17669 // Yay, everything is now upgraded 17670 ver.forceCurrent(); 17671 17672 // can downgrade to reader 17673 // Persist settings 17674 mSettings.writeLPr(); 17675 } 17676 // Send a broadcast to let everyone know we are done processing 17677 if (pkgList.size() > 0) { 17678 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17679 } 17680 } 17681 17682 /* 17683 * Utility method to unload a list of specified containers 17684 */ 17685 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17686 // Just unmount all valid containers. 17687 for (AsecInstallArgs arg : cidArgs) { 17688 synchronized (mInstallLock) { 17689 arg.doPostDeleteLI(false); 17690 } 17691 } 17692 } 17693 17694 /* 17695 * Unload packages mounted on external media. This involves deleting package 17696 * data from internal structures, sending broadcasts about disabled packages, 17697 * gc'ing to free up references, unmounting all secure containers 17698 * corresponding to packages on external media, and posting a 17699 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17700 * that we always have to post this message if status has been requested no 17701 * matter what. 17702 */ 17703 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17704 final boolean reportStatus) { 17705 if (DEBUG_SD_INSTALL) 17706 Log.i(TAG, "unloading media packages"); 17707 ArrayList<String> pkgList = new ArrayList<String>(); 17708 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17709 final Set<AsecInstallArgs> keys = processCids.keySet(); 17710 for (AsecInstallArgs args : keys) { 17711 String pkgName = args.getPackageName(); 17712 if (DEBUG_SD_INSTALL) 17713 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17714 // Delete package internally 17715 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17716 synchronized (mInstallLock) { 17717 boolean res = deletePackageLI(pkgName, null, false, null, 17718 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17719 if (res) { 17720 pkgList.add(pkgName); 17721 } else { 17722 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17723 failedList.add(args); 17724 } 17725 } 17726 } 17727 17728 // reader 17729 synchronized (mPackages) { 17730 // We didn't update the settings after removing each package; 17731 // write them now for all packages. 17732 mSettings.writeLPr(); 17733 } 17734 17735 // We have to absolutely send UPDATED_MEDIA_STATUS only 17736 // after confirming that all the receivers processed the ordered 17737 // broadcast when packages get disabled, force a gc to clean things up. 17738 // and unload all the containers. 17739 if (pkgList.size() > 0) { 17740 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17741 new IIntentReceiver.Stub() { 17742 public void performReceive(Intent intent, int resultCode, String data, 17743 Bundle extras, boolean ordered, boolean sticky, 17744 int sendingUser) throws RemoteException { 17745 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17746 reportStatus ? 1 : 0, 1, keys); 17747 mHandler.sendMessage(msg); 17748 } 17749 }); 17750 } else { 17751 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17752 keys); 17753 mHandler.sendMessage(msg); 17754 } 17755 } 17756 17757 private void loadPrivatePackages(final VolumeInfo vol) { 17758 mHandler.post(new Runnable() { 17759 @Override 17760 public void run() { 17761 loadPrivatePackagesInner(vol); 17762 } 17763 }); 17764 } 17765 17766 private void loadPrivatePackagesInner(VolumeInfo vol) { 17767 final String volumeUuid = vol.fsUuid; 17768 if (TextUtils.isEmpty(volumeUuid)) { 17769 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17770 return; 17771 } 17772 17773 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17774 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17775 17776 final VersionInfo ver; 17777 final List<PackageSetting> packages; 17778 synchronized (mPackages) { 17779 ver = mSettings.findOrCreateVersion(volumeUuid); 17780 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17781 } 17782 17783 // TODO: introduce a new concept similar to "frozen" to prevent these 17784 // apps from being launched until after data has been fully reconciled 17785 for (PackageSetting ps : packages) { 17786 synchronized (mInstallLock) { 17787 final PackageParser.Package pkg; 17788 try { 17789 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17790 loaded.add(pkg.applicationInfo); 17791 17792 } catch (PackageManagerException e) { 17793 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17794 } 17795 17796 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17797 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17798 } 17799 } 17800 } 17801 17802 // Reconcile app data for all started/unlocked users 17803 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17804 final UserManager um = mContext.getSystemService(UserManager.class); 17805 for (UserInfo user : um.getUsers()) { 17806 final int flags; 17807 if (um.isUserUnlocked(user.id)) { 17808 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17809 } else if (um.isUserRunning(user.id)) { 17810 flags = StorageManager.FLAG_STORAGE_DE; 17811 } else { 17812 continue; 17813 } 17814 17815 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17816 reconcileAppsData(volumeUuid, user.id, flags); 17817 } 17818 17819 synchronized (mPackages) { 17820 int updateFlags = UPDATE_PERMISSIONS_ALL; 17821 if (ver.sdkVersion != mSdkVersion) { 17822 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17823 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17824 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17825 } 17826 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17827 17828 // Yay, everything is now upgraded 17829 ver.forceCurrent(); 17830 17831 mSettings.writeLPr(); 17832 } 17833 17834 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17835 sendResourcesChangedBroadcast(true, false, loaded, null); 17836 } 17837 17838 private void unloadPrivatePackages(final VolumeInfo vol) { 17839 mHandler.post(new Runnable() { 17840 @Override 17841 public void run() { 17842 unloadPrivatePackagesInner(vol); 17843 } 17844 }); 17845 } 17846 17847 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17848 final String volumeUuid = vol.fsUuid; 17849 if (TextUtils.isEmpty(volumeUuid)) { 17850 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17851 return; 17852 } 17853 17854 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17855 synchronized (mInstallLock) { 17856 synchronized (mPackages) { 17857 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17858 for (PackageSetting ps : packages) { 17859 if (ps.pkg == null) continue; 17860 17861 final ApplicationInfo info = ps.pkg.applicationInfo; 17862 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17863 if (deletePackageLI(ps.name, null, false, null, 17864 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17865 unloaded.add(info); 17866 } else { 17867 Slog.w(TAG, "Failed to unload " + ps.codePath); 17868 } 17869 } 17870 17871 mSettings.writeLPr(); 17872 } 17873 } 17874 17875 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17876 sendResourcesChangedBroadcast(false, false, unloaded, null); 17877 } 17878 17879 /** 17880 * Examine all users present on given mounted volume, and destroy data 17881 * belonging to users that are no longer valid, or whose user ID has been 17882 * recycled. 17883 */ 17884 private void reconcileUsers(String volumeUuid) { 17885 // TODO: also reconcile DE directories 17886 final File[] files = FileUtils 17887 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17888 for (File file : files) { 17889 if (!file.isDirectory()) continue; 17890 17891 final int userId; 17892 final UserInfo info; 17893 try { 17894 userId = Integer.parseInt(file.getName()); 17895 info = sUserManager.getUserInfo(userId); 17896 } catch (NumberFormatException e) { 17897 Slog.w(TAG, "Invalid user directory " + file); 17898 continue; 17899 } 17900 17901 boolean destroyUser = false; 17902 if (info == null) { 17903 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17904 + " because no matching user was found"); 17905 destroyUser = true; 17906 } else { 17907 try { 17908 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17909 } catch (IOException e) { 17910 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17911 + " because we failed to enforce serial number: " + e); 17912 destroyUser = true; 17913 } 17914 } 17915 17916 if (destroyUser) { 17917 synchronized (mInstallLock) { 17918 try { 17919 mInstaller.removeUserDataDirs(volumeUuid, userId); 17920 } catch (InstallerException e) { 17921 Slog.w(TAG, "Failed to clean up user dirs", e); 17922 } 17923 } 17924 } 17925 } 17926 } 17927 17928 private void assertPackageKnown(String volumeUuid, String packageName) 17929 throws PackageManagerException { 17930 synchronized (mPackages) { 17931 final PackageSetting ps = mSettings.mPackages.get(packageName); 17932 if (ps == null) { 17933 throw new PackageManagerException("Package " + packageName + " is unknown"); 17934 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17935 throw new PackageManagerException( 17936 "Package " + packageName + " found on unknown volume " + volumeUuid 17937 + "; expected volume " + ps.volumeUuid); 17938 } 17939 } 17940 } 17941 17942 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17943 throws PackageManagerException { 17944 synchronized (mPackages) { 17945 final PackageSetting ps = mSettings.mPackages.get(packageName); 17946 if (ps == null) { 17947 throw new PackageManagerException("Package " + packageName + " is unknown"); 17948 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17949 throw new PackageManagerException( 17950 "Package " + packageName + " found on unknown volume " + volumeUuid 17951 + "; expected volume " + ps.volumeUuid); 17952 } else if (!ps.getInstalled(userId)) { 17953 throw new PackageManagerException( 17954 "Package " + packageName + " not installed for user " + userId); 17955 } 17956 } 17957 } 17958 17959 /** 17960 * Examine all apps present on given mounted volume, and destroy apps that 17961 * aren't expected, either due to uninstallation or reinstallation on 17962 * another volume. 17963 */ 17964 private void reconcileApps(String volumeUuid) { 17965 final File[] files = FileUtils 17966 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17967 for (File file : files) { 17968 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17969 && !PackageInstallerService.isStageName(file.getName()); 17970 if (!isPackage) { 17971 // Ignore entries which are not packages 17972 continue; 17973 } 17974 17975 try { 17976 final PackageLite pkg = PackageParser.parsePackageLite(file, 17977 PackageParser.PARSE_MUST_BE_APK); 17978 assertPackageKnown(volumeUuid, pkg.packageName); 17979 17980 } catch (PackageParserException | PackageManagerException e) { 17981 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17982 synchronized (mInstallLock) { 17983 removeCodePathLI(file); 17984 } 17985 } 17986 } 17987 } 17988 17989 /** 17990 * Reconcile all app data for the given user. 17991 * <p> 17992 * Verifies that directories exist and that ownership and labeling is 17993 * correct for all installed apps on all mounted volumes. 17994 */ 17995 void reconcileAppsData(int userId, int flags) { 17996 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17997 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17998 final String volumeUuid = vol.getFsUuid(); 17999 reconcileAppsData(volumeUuid, userId, flags); 18000 } 18001 } 18002 18003 /** 18004 * Reconcile all app data on given mounted volume. 18005 * <p> 18006 * Destroys app data that isn't expected, either due to uninstallation or 18007 * reinstallation on another volume. 18008 * <p> 18009 * Verifies that directories exist and that ownership and labeling is 18010 * correct for all installed apps. 18011 */ 18012 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18013 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18014 + Integer.toHexString(flags)); 18015 18016 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18017 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18018 18019 boolean restoreconNeeded = false; 18020 18021 // First look for stale data that doesn't belong, and check if things 18022 // have changed since we did our last restorecon 18023 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18024 if (!isUserKeyUnlocked(userId)) { 18025 throw new RuntimeException( 18026 "Yikes, someone asked us to reconcile CE storage while " + userId 18027 + " was still locked; this would have caused massive data loss!"); 18028 } 18029 18030 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18031 18032 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18033 for (File file : files) { 18034 final String packageName = file.getName(); 18035 try { 18036 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18037 } catch (PackageManagerException e) { 18038 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18039 synchronized (mInstallLock) { 18040 destroyAppDataLI(volumeUuid, packageName, userId, 18041 StorageManager.FLAG_STORAGE_CE); 18042 } 18043 } 18044 } 18045 } 18046 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18047 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18048 18049 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18050 for (File file : files) { 18051 final String packageName = file.getName(); 18052 try { 18053 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18054 } catch (PackageManagerException e) { 18055 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18056 synchronized (mInstallLock) { 18057 destroyAppDataLI(volumeUuid, packageName, userId, 18058 StorageManager.FLAG_STORAGE_DE); 18059 } 18060 } 18061 } 18062 } 18063 18064 // Ensure that data directories are ready to roll for all packages 18065 // installed for this volume and user 18066 final List<PackageSetting> packages; 18067 synchronized (mPackages) { 18068 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18069 } 18070 int preparedCount = 0; 18071 for (PackageSetting ps : packages) { 18072 final String packageName = ps.name; 18073 if (ps.pkg == null) { 18074 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18075 // TODO: might be due to legacy ASEC apps; we should circle back 18076 // and reconcile again once they're scanned 18077 continue; 18078 } 18079 18080 if (ps.getInstalled(userId)) { 18081 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18082 18083 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18084 // We may have just shuffled around app data directories, so 18085 // prepare them one more time 18086 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18087 } 18088 18089 preparedCount++; 18090 } 18091 } 18092 18093 if (restoreconNeeded) { 18094 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18095 SELinuxMMAC.setRestoreconDone(ceDir); 18096 } 18097 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18098 SELinuxMMAC.setRestoreconDone(deDir); 18099 } 18100 } 18101 18102 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18103 + " packages; restoreconNeeded was " + restoreconNeeded); 18104 } 18105 18106 /** 18107 * Prepare app data for the given app just after it was installed or 18108 * upgraded. This method carefully only touches users that it's installed 18109 * for, and it forces a restorecon to handle any seinfo changes. 18110 * <p> 18111 * Verifies that directories exist and that ownership and labeling is 18112 * correct for all installed apps. If there is an ownership mismatch, it 18113 * will try recovering system apps by wiping data; third-party app data is 18114 * left intact. 18115 * <p> 18116 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18117 */ 18118 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18119 prepareAppDataAfterInstallInternal(pkg); 18120 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18121 for (int i = 0; i < childCount; i++) { 18122 PackageParser.Package childPackage = pkg.childPackages.get(i); 18123 prepareAppDataAfterInstallInternal(childPackage); 18124 } 18125 } 18126 18127 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18128 final PackageSetting ps; 18129 synchronized (mPackages) { 18130 ps = mSettings.mPackages.get(pkg.packageName); 18131 mSettings.writeKernelMappingLPr(ps); 18132 } 18133 18134 final UserManager um = mContext.getSystemService(UserManager.class); 18135 for (UserInfo user : um.getUsers()) { 18136 final int flags; 18137 if (um.isUserUnlocked(user.id)) { 18138 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18139 } else if (um.isUserRunning(user.id)) { 18140 flags = StorageManager.FLAG_STORAGE_DE; 18141 } else { 18142 continue; 18143 } 18144 18145 if (ps.getInstalled(user.id)) { 18146 // Whenever an app changes, force a restorecon of its data 18147 // TODO: when user data is locked, mark that we're still dirty 18148 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18149 } 18150 } 18151 } 18152 18153 /** 18154 * Prepare app data for the given app. 18155 * <p> 18156 * Verifies that directories exist and that ownership and labeling is 18157 * correct for all installed apps. If there is an ownership mismatch, this 18158 * will try recovering system apps by wiping data; third-party app data is 18159 * left intact. 18160 */ 18161 private void prepareAppData(String volumeUuid, int userId, int flags, 18162 PackageParser.Package pkg, boolean restoreconNeeded) { 18163 if (DEBUG_APP_DATA) { 18164 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18165 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18166 } 18167 18168 final String packageName = pkg.packageName; 18169 final ApplicationInfo app = pkg.applicationInfo; 18170 final int appId = UserHandle.getAppId(app.uid); 18171 18172 Preconditions.checkNotNull(app.seinfo); 18173 18174 synchronized (mInstallLock) { 18175 try { 18176 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18177 appId, app.seinfo, app.targetSdkVersion); 18178 } catch (InstallerException e) { 18179 if (app.isSystemApp()) { 18180 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18181 + ", but trying to recover: " + e); 18182 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18183 try { 18184 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18185 appId, app.seinfo, app.targetSdkVersion); 18186 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18187 } catch (InstallerException e2) { 18188 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18189 } 18190 } else { 18191 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18192 } 18193 } 18194 18195 if (restoreconNeeded) { 18196 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18197 } 18198 18199 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18200 // Create a native library symlink only if we have native libraries 18201 // and if the native libraries are 32 bit libraries. We do not provide 18202 // this symlink for 64 bit libraries. 18203 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18204 final String nativeLibPath = app.nativeLibraryDir; 18205 try { 18206 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18207 nativeLibPath, userId); 18208 } catch (InstallerException e) { 18209 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18210 } 18211 } 18212 } 18213 } 18214 } 18215 18216 /** 18217 * For system apps on non-FBE devices, this method migrates any existing 18218 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18219 * the app. 18220 */ 18221 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18222 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18223 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18224 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18225 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18226 synchronized (mInstallLock) { 18227 try { 18228 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18229 } catch (InstallerException e) { 18230 logCriticalInfo(Log.WARN, 18231 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18232 } 18233 } 18234 return true; 18235 } else { 18236 return false; 18237 } 18238 } 18239 18240 private void unfreezePackage(String packageName) { 18241 synchronized (mPackages) { 18242 final PackageSetting ps = mSettings.mPackages.get(packageName); 18243 if (ps != null) { 18244 ps.frozen = false; 18245 } 18246 } 18247 } 18248 18249 @Override 18250 public int movePackage(final String packageName, final String volumeUuid) { 18251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18252 18253 final int moveId = mNextMoveId.getAndIncrement(); 18254 mHandler.post(new Runnable() { 18255 @Override 18256 public void run() { 18257 try { 18258 movePackageInternal(packageName, volumeUuid, moveId); 18259 } catch (PackageManagerException e) { 18260 Slog.w(TAG, "Failed to move " + packageName, e); 18261 mMoveCallbacks.notifyStatusChanged(moveId, 18262 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18263 } 18264 } 18265 }); 18266 return moveId; 18267 } 18268 18269 private void movePackageInternal(final String packageName, final String volumeUuid, 18270 final int moveId) throws PackageManagerException { 18271 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18272 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18273 final PackageManager pm = mContext.getPackageManager(); 18274 18275 final boolean currentAsec; 18276 final String currentVolumeUuid; 18277 final File codeFile; 18278 final String installerPackageName; 18279 final String packageAbiOverride; 18280 final int appId; 18281 final String seinfo; 18282 final String label; 18283 final int targetSdkVersion; 18284 18285 // reader 18286 synchronized (mPackages) { 18287 final PackageParser.Package pkg = mPackages.get(packageName); 18288 final PackageSetting ps = mSettings.mPackages.get(packageName); 18289 if (pkg == null || ps == null) { 18290 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18291 } 18292 18293 if (pkg.applicationInfo.isSystemApp()) { 18294 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18295 "Cannot move system application"); 18296 } 18297 18298 if (pkg.applicationInfo.isExternalAsec()) { 18299 currentAsec = true; 18300 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18301 } else if (pkg.applicationInfo.isForwardLocked()) { 18302 currentAsec = true; 18303 currentVolumeUuid = "forward_locked"; 18304 } else { 18305 currentAsec = false; 18306 currentVolumeUuid = ps.volumeUuid; 18307 18308 final File probe = new File(pkg.codePath); 18309 final File probeOat = new File(probe, "oat"); 18310 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18311 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18312 "Move only supported for modern cluster style installs"); 18313 } 18314 } 18315 18316 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18317 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18318 "Package already moved to " + volumeUuid); 18319 } 18320 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18321 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18322 "Device admin cannot be moved"); 18323 } 18324 18325 if (ps.frozen) { 18326 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18327 "Failed to move already frozen package"); 18328 } 18329 ps.frozen = true; 18330 18331 codeFile = new File(pkg.codePath); 18332 installerPackageName = ps.installerPackageName; 18333 packageAbiOverride = ps.cpuAbiOverrideString; 18334 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18335 seinfo = pkg.applicationInfo.seinfo; 18336 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18337 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18338 } 18339 18340 // Now that we're guarded by frozen state, kill app during move 18341 final long token = Binder.clearCallingIdentity(); 18342 try { 18343 killApplication(packageName, appId, "move pkg"); 18344 } finally { 18345 Binder.restoreCallingIdentity(token); 18346 } 18347 18348 final Bundle extras = new Bundle(); 18349 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18350 extras.putString(Intent.EXTRA_TITLE, label); 18351 mMoveCallbacks.notifyCreated(moveId, extras); 18352 18353 int installFlags; 18354 final boolean moveCompleteApp; 18355 final File measurePath; 18356 18357 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18358 installFlags = INSTALL_INTERNAL; 18359 moveCompleteApp = !currentAsec; 18360 measurePath = Environment.getDataAppDirectory(volumeUuid); 18361 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18362 installFlags = INSTALL_EXTERNAL; 18363 moveCompleteApp = false; 18364 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18365 } else { 18366 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18367 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18368 || !volume.isMountedWritable()) { 18369 unfreezePackage(packageName); 18370 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18371 "Move location not mounted private volume"); 18372 } 18373 18374 Preconditions.checkState(!currentAsec); 18375 18376 installFlags = INSTALL_INTERNAL; 18377 moveCompleteApp = true; 18378 measurePath = Environment.getDataAppDirectory(volumeUuid); 18379 } 18380 18381 final PackageStats stats = new PackageStats(null, -1); 18382 synchronized (mInstaller) { 18383 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18384 unfreezePackage(packageName); 18385 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18386 "Failed to measure package size"); 18387 } 18388 } 18389 18390 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18391 + stats.dataSize); 18392 18393 final long startFreeBytes = measurePath.getFreeSpace(); 18394 final long sizeBytes; 18395 if (moveCompleteApp) { 18396 sizeBytes = stats.codeSize + stats.dataSize; 18397 } else { 18398 sizeBytes = stats.codeSize; 18399 } 18400 18401 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18402 unfreezePackage(packageName); 18403 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18404 "Not enough free space to move"); 18405 } 18406 18407 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18408 18409 final CountDownLatch installedLatch = new CountDownLatch(1); 18410 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18411 @Override 18412 public void onUserActionRequired(Intent intent) throws RemoteException { 18413 throw new IllegalStateException(); 18414 } 18415 18416 @Override 18417 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18418 Bundle extras) throws RemoteException { 18419 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18420 + PackageManager.installStatusToString(returnCode, msg)); 18421 18422 installedLatch.countDown(); 18423 18424 // Regardless of success or failure of the move operation, 18425 // always unfreeze the package 18426 unfreezePackage(packageName); 18427 18428 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18429 switch (status) { 18430 case PackageInstaller.STATUS_SUCCESS: 18431 mMoveCallbacks.notifyStatusChanged(moveId, 18432 PackageManager.MOVE_SUCCEEDED); 18433 break; 18434 case PackageInstaller.STATUS_FAILURE_STORAGE: 18435 mMoveCallbacks.notifyStatusChanged(moveId, 18436 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18437 break; 18438 default: 18439 mMoveCallbacks.notifyStatusChanged(moveId, 18440 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18441 break; 18442 } 18443 } 18444 }; 18445 18446 final MoveInfo move; 18447 if (moveCompleteApp) { 18448 // Kick off a thread to report progress estimates 18449 new Thread() { 18450 @Override 18451 public void run() { 18452 while (true) { 18453 try { 18454 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18455 break; 18456 } 18457 } catch (InterruptedException ignored) { 18458 } 18459 18460 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18461 final int progress = 10 + (int) MathUtils.constrain( 18462 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18463 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18464 } 18465 } 18466 }.start(); 18467 18468 final String dataAppName = codeFile.getName(); 18469 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18470 dataAppName, appId, seinfo, targetSdkVersion); 18471 } else { 18472 move = null; 18473 } 18474 18475 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18476 18477 final Message msg = mHandler.obtainMessage(INIT_COPY); 18478 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18479 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18480 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18481 packageAbiOverride, null); 18482 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18483 msg.obj = params; 18484 18485 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18486 System.identityHashCode(msg.obj)); 18487 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18488 System.identityHashCode(msg.obj)); 18489 18490 mHandler.sendMessage(msg); 18491 } 18492 18493 @Override 18494 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18496 18497 final int realMoveId = mNextMoveId.getAndIncrement(); 18498 final Bundle extras = new Bundle(); 18499 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18500 mMoveCallbacks.notifyCreated(realMoveId, extras); 18501 18502 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18503 @Override 18504 public void onCreated(int moveId, Bundle extras) { 18505 // Ignored 18506 } 18507 18508 @Override 18509 public void onStatusChanged(int moveId, int status, long estMillis) { 18510 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18511 } 18512 }; 18513 18514 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18515 storage.setPrimaryStorageUuid(volumeUuid, callback); 18516 return realMoveId; 18517 } 18518 18519 @Override 18520 public int getMoveStatus(int moveId) { 18521 mContext.enforceCallingOrSelfPermission( 18522 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18523 return mMoveCallbacks.mLastStatus.get(moveId); 18524 } 18525 18526 @Override 18527 public void registerMoveCallback(IPackageMoveObserver callback) { 18528 mContext.enforceCallingOrSelfPermission( 18529 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18530 mMoveCallbacks.register(callback); 18531 } 18532 18533 @Override 18534 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18535 mContext.enforceCallingOrSelfPermission( 18536 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18537 mMoveCallbacks.unregister(callback); 18538 } 18539 18540 @Override 18541 public boolean setInstallLocation(int loc) { 18542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18543 null); 18544 if (getInstallLocation() == loc) { 18545 return true; 18546 } 18547 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18548 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18549 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18550 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18551 return true; 18552 } 18553 return false; 18554 } 18555 18556 @Override 18557 public int getInstallLocation() { 18558 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18559 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18560 PackageHelper.APP_INSTALL_AUTO); 18561 } 18562 18563 /** Called by UserManagerService */ 18564 void cleanUpUser(UserManagerService userManager, int userHandle) { 18565 synchronized (mPackages) { 18566 mDirtyUsers.remove(userHandle); 18567 mUserNeedsBadging.delete(userHandle); 18568 mSettings.removeUserLPw(userHandle); 18569 mPendingBroadcasts.remove(userHandle); 18570 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18571 } 18572 synchronized (mInstallLock) { 18573 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18574 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18575 final String volumeUuid = vol.getFsUuid(); 18576 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18577 try { 18578 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18579 } catch (InstallerException e) { 18580 Slog.w(TAG, "Failed to remove user data", e); 18581 } 18582 } 18583 synchronized (mPackages) { 18584 removeUnusedPackagesLILPw(userManager, userHandle); 18585 } 18586 } 18587 } 18588 18589 /** 18590 * We're removing userHandle and would like to remove any downloaded packages 18591 * that are no longer in use by any other user. 18592 * @param userHandle the user being removed 18593 */ 18594 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18595 final boolean DEBUG_CLEAN_APKS = false; 18596 int [] users = userManager.getUserIds(); 18597 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18598 while (psit.hasNext()) { 18599 PackageSetting ps = psit.next(); 18600 if (ps.pkg == null) { 18601 continue; 18602 } 18603 final String packageName = ps.pkg.packageName; 18604 // Skip over if system app 18605 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18606 continue; 18607 } 18608 if (DEBUG_CLEAN_APKS) { 18609 Slog.i(TAG, "Checking package " + packageName); 18610 } 18611 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18612 if (keep) { 18613 if (DEBUG_CLEAN_APKS) { 18614 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18615 } 18616 } else { 18617 for (int i = 0; i < users.length; i++) { 18618 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18619 keep = true; 18620 if (DEBUG_CLEAN_APKS) { 18621 Slog.i(TAG, " Keeping package " + packageName + " for user " 18622 + users[i]); 18623 } 18624 break; 18625 } 18626 } 18627 } 18628 if (!keep) { 18629 if (DEBUG_CLEAN_APKS) { 18630 Slog.i(TAG, " Removing package " + packageName); 18631 } 18632 mHandler.post(new Runnable() { 18633 public void run() { 18634 deletePackageX(packageName, userHandle, 0); 18635 } //end run 18636 }); 18637 } 18638 } 18639 } 18640 18641 /** Called by UserManagerService */ 18642 void createNewUser(int userHandle) { 18643 synchronized (mInstallLock) { 18644 try { 18645 mInstaller.createUserConfig(userHandle); 18646 } catch (InstallerException e) { 18647 Slog.w(TAG, "Failed to create user config", e); 18648 } 18649 mSettings.createNewUserLI(this, mInstaller, userHandle); 18650 } 18651 synchronized (mPackages) { 18652 applyFactoryDefaultBrowserLPw(userHandle); 18653 primeDomainVerificationsLPw(userHandle); 18654 } 18655 } 18656 18657 void newUserCreated(final int userHandle) { 18658 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18659 // If permission review for legacy apps is required, we represent 18660 // dagerous permissions for such apps as always granted runtime 18661 // permissions to keep per user flag state whether review is needed. 18662 // Hence, if a new user is added we have to propagate dangerous 18663 // permission grants for these legacy apps. 18664 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18665 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18666 | UPDATE_PERMISSIONS_REPLACE_ALL); 18667 } 18668 } 18669 18670 @Override 18671 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18672 mContext.enforceCallingOrSelfPermission( 18673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18674 "Only package verification agents can read the verifier device identity"); 18675 18676 synchronized (mPackages) { 18677 return mSettings.getVerifierDeviceIdentityLPw(); 18678 } 18679 } 18680 18681 @Override 18682 public void setPermissionEnforced(String permission, boolean enforced) { 18683 // TODO: Now that we no longer change GID for storage, this should to away. 18684 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18685 "setPermissionEnforced"); 18686 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18687 synchronized (mPackages) { 18688 if (mSettings.mReadExternalStorageEnforced == null 18689 || mSettings.mReadExternalStorageEnforced != enforced) { 18690 mSettings.mReadExternalStorageEnforced = enforced; 18691 mSettings.writeLPr(); 18692 } 18693 } 18694 // kill any non-foreground processes so we restart them and 18695 // grant/revoke the GID. 18696 final IActivityManager am = ActivityManagerNative.getDefault(); 18697 if (am != null) { 18698 final long token = Binder.clearCallingIdentity(); 18699 try { 18700 am.killProcessesBelowForeground("setPermissionEnforcement"); 18701 } catch (RemoteException e) { 18702 } finally { 18703 Binder.restoreCallingIdentity(token); 18704 } 18705 } 18706 } else { 18707 throw new IllegalArgumentException("No selective enforcement for " + permission); 18708 } 18709 } 18710 18711 @Override 18712 @Deprecated 18713 public boolean isPermissionEnforced(String permission) { 18714 return true; 18715 } 18716 18717 @Override 18718 public boolean isStorageLow() { 18719 final long token = Binder.clearCallingIdentity(); 18720 try { 18721 final DeviceStorageMonitorInternal 18722 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18723 if (dsm != null) { 18724 return dsm.isMemoryLow(); 18725 } else { 18726 return false; 18727 } 18728 } finally { 18729 Binder.restoreCallingIdentity(token); 18730 } 18731 } 18732 18733 @Override 18734 public IPackageInstaller getPackageInstaller() { 18735 return mInstallerService; 18736 } 18737 18738 private boolean userNeedsBadging(int userId) { 18739 int index = mUserNeedsBadging.indexOfKey(userId); 18740 if (index < 0) { 18741 final UserInfo userInfo; 18742 final long token = Binder.clearCallingIdentity(); 18743 try { 18744 userInfo = sUserManager.getUserInfo(userId); 18745 } finally { 18746 Binder.restoreCallingIdentity(token); 18747 } 18748 final boolean b; 18749 if (userInfo != null && userInfo.isManagedProfile()) { 18750 b = true; 18751 } else { 18752 b = false; 18753 } 18754 mUserNeedsBadging.put(userId, b); 18755 return b; 18756 } 18757 return mUserNeedsBadging.valueAt(index); 18758 } 18759 18760 @Override 18761 public KeySet getKeySetByAlias(String packageName, String alias) { 18762 if (packageName == null || alias == null) { 18763 return null; 18764 } 18765 synchronized(mPackages) { 18766 final PackageParser.Package pkg = mPackages.get(packageName); 18767 if (pkg == null) { 18768 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18769 throw new IllegalArgumentException("Unknown package: " + packageName); 18770 } 18771 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18772 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18773 } 18774 } 18775 18776 @Override 18777 public KeySet getSigningKeySet(String packageName) { 18778 if (packageName == null) { 18779 return null; 18780 } 18781 synchronized(mPackages) { 18782 final PackageParser.Package pkg = mPackages.get(packageName); 18783 if (pkg == null) { 18784 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18785 throw new IllegalArgumentException("Unknown package: " + packageName); 18786 } 18787 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18788 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18789 throw new SecurityException("May not access signing KeySet of other apps."); 18790 } 18791 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18792 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18793 } 18794 } 18795 18796 @Override 18797 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18798 if (packageName == null || ks == null) { 18799 return false; 18800 } 18801 synchronized(mPackages) { 18802 final PackageParser.Package pkg = mPackages.get(packageName); 18803 if (pkg == null) { 18804 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18805 throw new IllegalArgumentException("Unknown package: " + packageName); 18806 } 18807 IBinder ksh = ks.getToken(); 18808 if (ksh instanceof KeySetHandle) { 18809 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18810 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18811 } 18812 return false; 18813 } 18814 } 18815 18816 @Override 18817 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18818 if (packageName == null || ks == null) { 18819 return false; 18820 } 18821 synchronized(mPackages) { 18822 final PackageParser.Package pkg = mPackages.get(packageName); 18823 if (pkg == null) { 18824 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18825 throw new IllegalArgumentException("Unknown package: " + packageName); 18826 } 18827 IBinder ksh = ks.getToken(); 18828 if (ksh instanceof KeySetHandle) { 18829 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18830 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18831 } 18832 return false; 18833 } 18834 } 18835 18836 private void deletePackageIfUnusedLPr(final String packageName) { 18837 PackageSetting ps = mSettings.mPackages.get(packageName); 18838 if (ps == null) { 18839 return; 18840 } 18841 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18842 // TODO Implement atomic delete if package is unused 18843 // It is currently possible that the package will be deleted even if it is installed 18844 // after this method returns. 18845 mHandler.post(new Runnable() { 18846 public void run() { 18847 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18848 } 18849 }); 18850 } 18851 } 18852 18853 /** 18854 * Check and throw if the given before/after packages would be considered a 18855 * downgrade. 18856 */ 18857 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18858 throws PackageManagerException { 18859 if (after.versionCode < before.mVersionCode) { 18860 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18861 "Update version code " + after.versionCode + " is older than current " 18862 + before.mVersionCode); 18863 } else if (after.versionCode == before.mVersionCode) { 18864 if (after.baseRevisionCode < before.baseRevisionCode) { 18865 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18866 "Update base revision code " + after.baseRevisionCode 18867 + " is older than current " + before.baseRevisionCode); 18868 } 18869 18870 if (!ArrayUtils.isEmpty(after.splitNames)) { 18871 for (int i = 0; i < after.splitNames.length; i++) { 18872 final String splitName = after.splitNames[i]; 18873 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18874 if (j != -1) { 18875 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18876 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18877 "Update split " + splitName + " revision code " 18878 + after.splitRevisionCodes[i] + " is older than current " 18879 + before.splitRevisionCodes[j]); 18880 } 18881 } 18882 } 18883 } 18884 } 18885 } 18886 18887 private static class MoveCallbacks extends Handler { 18888 private static final int MSG_CREATED = 1; 18889 private static final int MSG_STATUS_CHANGED = 2; 18890 18891 private final RemoteCallbackList<IPackageMoveObserver> 18892 mCallbacks = new RemoteCallbackList<>(); 18893 18894 private final SparseIntArray mLastStatus = new SparseIntArray(); 18895 18896 public MoveCallbacks(Looper looper) { 18897 super(looper); 18898 } 18899 18900 public void register(IPackageMoveObserver callback) { 18901 mCallbacks.register(callback); 18902 } 18903 18904 public void unregister(IPackageMoveObserver callback) { 18905 mCallbacks.unregister(callback); 18906 } 18907 18908 @Override 18909 public void handleMessage(Message msg) { 18910 final SomeArgs args = (SomeArgs) msg.obj; 18911 final int n = mCallbacks.beginBroadcast(); 18912 for (int i = 0; i < n; i++) { 18913 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18914 try { 18915 invokeCallback(callback, msg.what, args); 18916 } catch (RemoteException ignored) { 18917 } 18918 } 18919 mCallbacks.finishBroadcast(); 18920 args.recycle(); 18921 } 18922 18923 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18924 throws RemoteException { 18925 switch (what) { 18926 case MSG_CREATED: { 18927 callback.onCreated(args.argi1, (Bundle) args.arg2); 18928 break; 18929 } 18930 case MSG_STATUS_CHANGED: { 18931 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18932 break; 18933 } 18934 } 18935 } 18936 18937 private void notifyCreated(int moveId, Bundle extras) { 18938 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18939 18940 final SomeArgs args = SomeArgs.obtain(); 18941 args.argi1 = moveId; 18942 args.arg2 = extras; 18943 obtainMessage(MSG_CREATED, args).sendToTarget(); 18944 } 18945 18946 private void notifyStatusChanged(int moveId, int status) { 18947 notifyStatusChanged(moveId, status, -1); 18948 } 18949 18950 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18951 Slog.v(TAG, "Move " + moveId + " status " + status); 18952 18953 final SomeArgs args = SomeArgs.obtain(); 18954 args.argi1 = moveId; 18955 args.argi2 = status; 18956 args.arg3 = estMillis; 18957 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18958 18959 synchronized (mLastStatus) { 18960 mLastStatus.put(moveId, status); 18961 } 18962 } 18963 } 18964 18965 private final static class OnPermissionChangeListeners extends Handler { 18966 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18967 18968 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18969 new RemoteCallbackList<>(); 18970 18971 public OnPermissionChangeListeners(Looper looper) { 18972 super(looper); 18973 } 18974 18975 @Override 18976 public void handleMessage(Message msg) { 18977 switch (msg.what) { 18978 case MSG_ON_PERMISSIONS_CHANGED: { 18979 final int uid = msg.arg1; 18980 handleOnPermissionsChanged(uid); 18981 } break; 18982 } 18983 } 18984 18985 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18986 mPermissionListeners.register(listener); 18987 18988 } 18989 18990 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18991 mPermissionListeners.unregister(listener); 18992 } 18993 18994 public void onPermissionsChanged(int uid) { 18995 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18996 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18997 } 18998 } 18999 19000 private void handleOnPermissionsChanged(int uid) { 19001 final int count = mPermissionListeners.beginBroadcast(); 19002 try { 19003 for (int i = 0; i < count; i++) { 19004 IOnPermissionsChangeListener callback = mPermissionListeners 19005 .getBroadcastItem(i); 19006 try { 19007 callback.onPermissionsChanged(uid); 19008 } catch (RemoteException e) { 19009 Log.e(TAG, "Permission listener is dead", e); 19010 } 19011 } 19012 } finally { 19013 mPermissionListeners.finishBroadcast(); 19014 } 19015 } 19016 } 19017 19018 private class PackageManagerInternalImpl extends PackageManagerInternal { 19019 @Override 19020 public void setLocationPackagesProvider(PackagesProvider provider) { 19021 synchronized (mPackages) { 19022 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19023 } 19024 } 19025 19026 @Override 19027 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19028 synchronized (mPackages) { 19029 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19030 } 19031 } 19032 19033 @Override 19034 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19035 synchronized (mPackages) { 19036 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19037 } 19038 } 19039 19040 @Override 19041 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19042 synchronized (mPackages) { 19043 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19044 } 19045 } 19046 19047 @Override 19048 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19049 synchronized (mPackages) { 19050 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19051 } 19052 } 19053 19054 @Override 19055 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19056 synchronized (mPackages) { 19057 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19058 } 19059 } 19060 19061 @Override 19062 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19063 synchronized (mPackages) { 19064 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19065 packageName, userId); 19066 } 19067 } 19068 19069 @Override 19070 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19071 synchronized (mPackages) { 19072 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19073 packageName, userId); 19074 } 19075 } 19076 19077 @Override 19078 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19079 synchronized (mPackages) { 19080 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19081 packageName, userId); 19082 } 19083 } 19084 19085 @Override 19086 public void setKeepUninstalledPackages(final List<String> packageList) { 19087 Preconditions.checkNotNull(packageList); 19088 List<String> removedFromList = null; 19089 synchronized (mPackages) { 19090 if (mKeepUninstalledPackages != null) { 19091 final int packagesCount = mKeepUninstalledPackages.size(); 19092 for (int i = 0; i < packagesCount; i++) { 19093 String oldPackage = mKeepUninstalledPackages.get(i); 19094 if (packageList != null && packageList.contains(oldPackage)) { 19095 continue; 19096 } 19097 if (removedFromList == null) { 19098 removedFromList = new ArrayList<>(); 19099 } 19100 removedFromList.add(oldPackage); 19101 } 19102 } 19103 mKeepUninstalledPackages = new ArrayList<>(packageList); 19104 if (removedFromList != null) { 19105 final int removedCount = removedFromList.size(); 19106 for (int i = 0; i < removedCount; i++) { 19107 deletePackageIfUnusedLPr(removedFromList.get(i)); 19108 } 19109 } 19110 } 19111 } 19112 19113 @Override 19114 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19115 synchronized (mPackages) { 19116 // If we do not support permission review, done. 19117 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19118 return false; 19119 } 19120 19121 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19122 if (packageSetting == null) { 19123 return false; 19124 } 19125 19126 // Permission review applies only to apps not supporting the new permission model. 19127 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19128 return false; 19129 } 19130 19131 // Legacy apps have the permission and get user consent on launch. 19132 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19133 return permissionsState.isPermissionReviewRequired(userId); 19134 } 19135 } 19136 } 19137 19138 @Override 19139 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19140 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19141 synchronized (mPackages) { 19142 final long identity = Binder.clearCallingIdentity(); 19143 try { 19144 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19145 packageNames, userId); 19146 } finally { 19147 Binder.restoreCallingIdentity(identity); 19148 } 19149 } 19150 } 19151 19152 private static void enforceSystemOrPhoneCaller(String tag) { 19153 int callingUid = Binder.getCallingUid(); 19154 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19155 throw new SecurityException( 19156 "Cannot call " + tag + " from UID " + callingUid); 19157 } 19158 } 19159 19160 boolean isHistoricalPackageUsageAvailable() { 19161 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19162 } 19163} 19164