PackageManagerService.java revision 990fb6b5c91be62078a698ee1c01e24d33364c85
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.DevicePolicyManagerInternal; 107import android.app.admin.IDevicePolicyManager; 108import android.app.backup.IBackupManager; 109import android.content.BroadcastReceiver; 110import android.content.ComponentName; 111import android.content.Context; 112import android.content.IIntentReceiver; 113import android.content.Intent; 114import android.content.IntentFilter; 115import android.content.IntentSender; 116import android.content.IntentSender.SendIntentException; 117import android.content.ServiceConnection; 118import android.content.pm.ActivityInfo; 119import android.content.pm.ApplicationInfo; 120import android.content.pm.AppsQueryHelper; 121import android.content.pm.ComponentInfo; 122import android.content.pm.EphemeralApplicationInfo; 123import android.content.pm.EphemeralResolveInfo; 124import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 125import android.content.pm.FeatureInfo; 126import android.content.pm.IOnPermissionsChangeListener; 127import android.content.pm.IPackageDataObserver; 128import android.content.pm.IPackageDeleteObserver; 129import android.content.pm.IPackageDeleteObserver2; 130import android.content.pm.IPackageInstallObserver2; 131import android.content.pm.IPackageInstaller; 132import android.content.pm.IPackageManager; 133import android.content.pm.IPackageMoveObserver; 134import android.content.pm.IPackageStatsObserver; 135import android.content.pm.InstrumentationInfo; 136import android.content.pm.IntentFilterVerificationInfo; 137import android.content.pm.KeySet; 138import android.content.pm.PackageCleanItem; 139import android.content.pm.PackageInfo; 140import android.content.pm.PackageInfoLite; 141import android.content.pm.PackageInstaller; 142import android.content.pm.PackageManager; 143import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 144import android.content.pm.PackageManagerInternal; 145import android.content.pm.PackageParser; 146import android.content.pm.PackageParser.ActivityIntentInfo; 147import android.content.pm.PackageParser.PackageLite; 148import android.content.pm.PackageParser.PackageParserException; 149import android.content.pm.PackageStats; 150import android.content.pm.PackageUserState; 151import android.content.pm.ParceledListSlice; 152import android.content.pm.PermissionGroupInfo; 153import android.content.pm.PermissionInfo; 154import android.content.pm.ProviderInfo; 155import android.content.pm.ResolveInfo; 156import android.content.pm.ServiceInfo; 157import android.content.pm.Signature; 158import android.content.pm.UserInfo; 159import android.content.pm.VerifierDeviceIdentity; 160import android.content.pm.VerifierInfo; 161import android.content.res.Resources; 162import android.graphics.Bitmap; 163import android.hardware.display.DisplayManager; 164import android.net.Uri; 165import android.os.Binder; 166import android.os.Build; 167import android.os.Bundle; 168import android.os.Debug; 169import android.os.Environment; 170import android.os.Environment.UserEnvironment; 171import android.os.FileUtils; 172import android.os.Handler; 173import android.os.IBinder; 174import android.os.Looper; 175import android.os.Message; 176import android.os.Parcel; 177import android.os.ParcelFileDescriptor; 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 static final int SCAN_DONT_KILL_APP = 1<<17; 364 365 static final int REMOVE_CHATTY = 1<<16; 366 367 private static final int[] EMPTY_INT_ARRAY = new int[0]; 368 369 /** 370 * Timeout (in milliseconds) after which the watchdog should declare that 371 * our handler thread is wedged. The usual default for such things is one 372 * minute but we sometimes do very lengthy I/O operations on this thread, 373 * such as installing multi-gigabyte applications, so ours needs to be longer. 374 */ 375 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 376 377 /** 378 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 379 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 380 * settings entry if available, otherwise we use the hardcoded default. If it's been 381 * more than this long since the last fstrim, we force one during the boot sequence. 382 * 383 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 384 * one gets run at the next available charging+idle time. This final mandatory 385 * no-fstrim check kicks in only of the other scheduling criteria is never met. 386 */ 387 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 388 389 /** 390 * Whether verification is enabled by default. 391 */ 392 private static final boolean DEFAULT_VERIFY_ENABLE = true; 393 394 /** 395 * The default maximum time to wait for the verification agent to return in 396 * milliseconds. 397 */ 398 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 399 400 /** 401 * The default response for package verification timeout. 402 * 403 * This can be either PackageManager.VERIFICATION_ALLOW or 404 * PackageManager.VERIFICATION_REJECT. 405 */ 406 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 407 408 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 409 410 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 411 DEFAULT_CONTAINER_PACKAGE, 412 "com.android.defcontainer.DefaultContainerService"); 413 414 private static final String KILL_APP_REASON_GIDS_CHANGED = 415 "permission grant or revoke changed gids"; 416 417 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 418 "permissions revoked"; 419 420 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 421 422 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 423 424 /** Permission grant: not grant the permission. */ 425 private static final int GRANT_DENIED = 1; 426 427 /** Permission grant: grant the permission as an install permission. */ 428 private static final int GRANT_INSTALL = 2; 429 430 /** Permission grant: grant the permission as a runtime one. */ 431 private static final int GRANT_RUNTIME = 3; 432 433 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 434 private static final int GRANT_UPGRADE = 4; 435 436 /** Canonical intent used to identify what counts as a "web browser" app */ 437 private static final Intent sBrowserIntent; 438 static { 439 sBrowserIntent = new Intent(); 440 sBrowserIntent.setAction(Intent.ACTION_VIEW); 441 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 442 sBrowserIntent.setData(Uri.parse("http:")); 443 } 444 445 final ServiceThread mHandlerThread; 446 447 final PackageHandler mHandler; 448 449 /** 450 * Messages for {@link #mHandler} that need to wait for system ready before 451 * being dispatched. 452 */ 453 private ArrayList<Message> mPostSystemReadyMessages; 454 455 final int mSdkVersion = Build.VERSION.SDK_INT; 456 457 final Context mContext; 458 final boolean mFactoryTest; 459 final boolean mOnlyCore; 460 final DisplayMetrics mMetrics; 461 final int mDefParseFlags; 462 final String[] mSeparateProcesses; 463 final boolean mIsUpgrade; 464 465 /** The location for ASEC container files on internal storage. */ 466 final String mAsecInternalPath; 467 468 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 469 // LOCK HELD. Can be called with mInstallLock held. 470 @GuardedBy("mInstallLock") 471 final Installer mInstaller; 472 473 /** Directory where installed third-party apps stored */ 474 final File mAppInstallDir; 475 final File mEphemeralInstallDir; 476 477 /** 478 * Directory to which applications installed internally have their 479 * 32 bit native libraries copied. 480 */ 481 private File mAppLib32InstallDir; 482 483 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 484 // apps. 485 final File mDrmAppPrivateInstallDir; 486 487 // ---------------------------------------------------------------- 488 489 // Lock for state used when installing and doing other long running 490 // operations. Methods that must be called with this lock held have 491 // the suffix "LI". 492 final Object mInstallLock = new Object(); 493 494 // ---------------------------------------------------------------- 495 496 // Keys are String (package name), values are Package. This also serves 497 // as the lock for the global state. Methods that must be called with 498 // this lock held have the prefix "LP". 499 @GuardedBy("mPackages") 500 final ArrayMap<String, PackageParser.Package> mPackages = 501 new ArrayMap<String, PackageParser.Package>(); 502 503 final ArrayMap<String, Set<String>> mKnownCodebase = 504 new ArrayMap<String, Set<String>>(); 505 506 // Tracks available target package names -> overlay package paths. 507 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 508 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 509 510 /** 511 * Tracks new system packages [received in an OTA] that we expect to 512 * find updated user-installed versions. Keys are package name, values 513 * are package location. 514 */ 515 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 516 517 /** 518 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 519 */ 520 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 521 /** 522 * Whether or not system app permissions should be promoted from install to runtime. 523 */ 524 boolean mPromoteSystemApps; 525 526 final Settings mSettings; 527 boolean mRestoredSettings; 528 529 // System configuration read by SystemConfig. 530 final int[] mGlobalGids; 531 final SparseArray<ArraySet<String>> mSystemPermissions; 532 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 533 534 // If mac_permissions.xml was found for seinfo labeling. 535 boolean mFoundPolicyFile; 536 537 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 538 539 public static final class SharedLibraryEntry { 540 public final String path; 541 public final String apk; 542 543 SharedLibraryEntry(String _path, String _apk) { 544 path = _path; 545 apk = _apk; 546 } 547 } 548 549 // Currently known shared libraries. 550 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 551 new ArrayMap<String, SharedLibraryEntry>(); 552 553 // All available activities, for your resolving pleasure. 554 final ActivityIntentResolver mActivities = 555 new ActivityIntentResolver(); 556 557 // All available receivers, for your resolving pleasure. 558 final ActivityIntentResolver mReceivers = 559 new ActivityIntentResolver(); 560 561 // All available services, for your resolving pleasure. 562 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 563 564 // All available providers, for your resolving pleasure. 565 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 566 567 // Mapping from provider base names (first directory in content URI codePath) 568 // to the provider information. 569 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 570 new ArrayMap<String, PackageParser.Provider>(); 571 572 // Mapping from instrumentation class names to info about them. 573 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 574 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 575 576 // Mapping from permission names to info about them. 577 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 578 new ArrayMap<String, PackageParser.PermissionGroup>(); 579 580 // Packages whose data we have transfered into another package, thus 581 // should no longer exist. 582 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 583 584 // Broadcast actions that are only available to the system. 585 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 586 587 /** List of packages waiting for verification. */ 588 final SparseArray<PackageVerificationState> mPendingVerification 589 = new SparseArray<PackageVerificationState>(); 590 591 /** Set of packages associated with each app op permission. */ 592 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 593 594 final PackageInstallerService mInstallerService; 595 596 private final PackageDexOptimizer mPackageDexOptimizer; 597 598 private AtomicInteger mNextMoveId = new AtomicInteger(); 599 private final MoveCallbacks mMoveCallbacks; 600 601 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 602 603 // Cache of users who need badging. 604 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 605 606 /** Token for keys in mPendingVerification. */ 607 private int mPendingVerificationToken = 0; 608 609 volatile boolean mSystemReady; 610 volatile boolean mSafeMode; 611 volatile boolean mHasSystemUidErrors; 612 613 ApplicationInfo mAndroidApplication; 614 final ActivityInfo mResolveActivity = new ActivityInfo(); 615 final ResolveInfo mResolveInfo = new ResolveInfo(); 616 ComponentName mResolveComponentName; 617 PackageParser.Package mPlatformPackage; 618 ComponentName mCustomResolverComponentName; 619 620 boolean mResolverReplaced = false; 621 622 private final @Nullable ComponentName mIntentFilterVerifierComponent; 623 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 624 625 private int mIntentFilterVerificationToken = 0; 626 627 /** Component that knows whether or not an ephemeral application exists */ 628 final ComponentName mEphemeralResolverComponent; 629 /** The service connection to the ephemeral resolver */ 630 final EphemeralResolverConnection mEphemeralResolverConnection; 631 632 /** Component used to install ephemeral applications */ 633 final ComponentName mEphemeralInstallerComponent; 634 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 635 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 636 637 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 638 = new SparseArray<IntentFilterVerificationState>(); 639 640 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 641 new DefaultPermissionGrantPolicy(this); 642 643 // List of packages names to keep cached, even if they are uninstalled for all users 644 private List<String> mKeepUninstalledPackages; 645 646 private static class IFVerificationParams { 647 PackageParser.Package pkg; 648 boolean replacing; 649 int userId; 650 int verifierUid; 651 652 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 653 int _userId, int _verifierUid) { 654 pkg = _pkg; 655 replacing = _replacing; 656 userId = _userId; 657 replacing = _replacing; 658 verifierUid = _verifierUid; 659 } 660 } 661 662 private interface IntentFilterVerifier<T extends IntentFilter> { 663 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 664 T filter, String packageName); 665 void startVerifications(int userId); 666 void receiveVerificationResponse(int verificationId); 667 } 668 669 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 670 private Context mContext; 671 private ComponentName mIntentFilterVerifierComponent; 672 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 673 674 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 675 mContext = context; 676 mIntentFilterVerifierComponent = verifierComponent; 677 } 678 679 private String getDefaultScheme() { 680 return IntentFilter.SCHEME_HTTPS; 681 } 682 683 @Override 684 public void startVerifications(int userId) { 685 // Launch verifications requests 686 int count = mCurrentIntentFilterVerifications.size(); 687 for (int n=0; n<count; n++) { 688 int verificationId = mCurrentIntentFilterVerifications.get(n); 689 final IntentFilterVerificationState ivs = 690 mIntentFilterVerificationStates.get(verificationId); 691 692 String packageName = ivs.getPackageName(); 693 694 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 695 final int filterCount = filters.size(); 696 ArraySet<String> domainsSet = new ArraySet<>(); 697 for (int m=0; m<filterCount; m++) { 698 PackageParser.ActivityIntentInfo filter = filters.get(m); 699 domainsSet.addAll(filter.getHostsList()); 700 } 701 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 702 synchronized (mPackages) { 703 if (mSettings.createIntentFilterVerificationIfNeededLPw( 704 packageName, domainsList) != null) { 705 scheduleWriteSettingsLocked(); 706 } 707 } 708 sendVerificationRequest(userId, verificationId, ivs); 709 } 710 mCurrentIntentFilterVerifications.clear(); 711 } 712 713 private void sendVerificationRequest(int userId, int verificationId, 714 IntentFilterVerificationState ivs) { 715 716 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 717 verificationIntent.putExtra( 718 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 719 verificationId); 720 verificationIntent.putExtra( 721 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 722 getDefaultScheme()); 723 verificationIntent.putExtra( 724 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 725 ivs.getHostsString()); 726 verificationIntent.putExtra( 727 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 728 ivs.getPackageName()); 729 verificationIntent.setComponent(mIntentFilterVerifierComponent); 730 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 731 732 UserHandle user = new UserHandle(userId); 733 mContext.sendBroadcastAsUser(verificationIntent, user); 734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 735 "Sending IntentFilter verification broadcast"); 736 } 737 738 public void receiveVerificationResponse(int verificationId) { 739 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 740 741 final boolean verified = ivs.isVerified(); 742 743 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 744 final int count = filters.size(); 745 if (DEBUG_DOMAIN_VERIFICATION) { 746 Slog.i(TAG, "Received verification response " + verificationId 747 + " for " + count + " filters, verified=" + verified); 748 } 749 for (int n=0; n<count; n++) { 750 PackageParser.ActivityIntentInfo filter = filters.get(n); 751 filter.setVerified(verified); 752 753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 754 + " verified with result:" + verified + " and hosts:" 755 + ivs.getHostsString()); 756 } 757 758 mIntentFilterVerificationStates.remove(verificationId); 759 760 final String packageName = ivs.getPackageName(); 761 IntentFilterVerificationInfo ivi = null; 762 763 synchronized (mPackages) { 764 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 765 } 766 if (ivi == null) { 767 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 768 + verificationId + " packageName:" + packageName); 769 return; 770 } 771 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 772 "Updating IntentFilterVerificationInfo for package " + packageName 773 +" verificationId:" + verificationId); 774 775 synchronized (mPackages) { 776 if (verified) { 777 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 778 } else { 779 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 780 } 781 scheduleWriteSettingsLocked(); 782 783 final int userId = ivs.getUserId(); 784 if (userId != UserHandle.USER_ALL) { 785 final int userStatus = 786 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 787 788 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 789 boolean needUpdate = false; 790 791 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 792 // already been set by the User thru the Disambiguation dialog 793 switch (userStatus) { 794 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 795 if (verified) { 796 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 797 } else { 798 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 799 } 800 needUpdate = true; 801 break; 802 803 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 804 if (verified) { 805 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 806 needUpdate = true; 807 } 808 break; 809 810 default: 811 // Nothing to do 812 } 813 814 if (needUpdate) { 815 mSettings.updateIntentFilterVerificationStatusLPw( 816 packageName, updatedStatus, userId); 817 scheduleWritePackageRestrictionsLocked(userId); 818 } 819 } 820 } 821 } 822 823 @Override 824 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 825 ActivityIntentInfo filter, String packageName) { 826 if (!hasValidDomains(filter)) { 827 return false; 828 } 829 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 830 if (ivs == null) { 831 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 832 packageName); 833 } 834 if (DEBUG_DOMAIN_VERIFICATION) { 835 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 836 } 837 ivs.addFilter(filter); 838 return true; 839 } 840 841 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 842 int userId, int verificationId, String packageName) { 843 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 844 verifierUid, userId, packageName); 845 ivs.setPendingState(); 846 synchronized (mPackages) { 847 mIntentFilterVerificationStates.append(verificationId, ivs); 848 mCurrentIntentFilterVerifications.add(verificationId); 849 } 850 return ivs; 851 } 852 } 853 854 private static boolean hasValidDomains(ActivityIntentInfo filter) { 855 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 856 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 857 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 858 } 859 860 // Set of pending broadcasts for aggregating enable/disable of components. 861 static class PendingPackageBroadcasts { 862 // for each user id, a map of <package name -> components within that package> 863 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 864 865 public PendingPackageBroadcasts() { 866 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 867 } 868 869 public ArrayList<String> get(int userId, String packageName) { 870 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 871 return packages.get(packageName); 872 } 873 874 public void put(int userId, String packageName, ArrayList<String> components) { 875 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 876 packages.put(packageName, components); 877 } 878 879 public void remove(int userId, String packageName) { 880 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 881 if (packages != null) { 882 packages.remove(packageName); 883 } 884 } 885 886 public void remove(int userId) { 887 mUidMap.remove(userId); 888 } 889 890 public int userIdCount() { 891 return mUidMap.size(); 892 } 893 894 public int userIdAt(int n) { 895 return mUidMap.keyAt(n); 896 } 897 898 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 899 return mUidMap.get(userId); 900 } 901 902 public int size() { 903 // total number of pending broadcast entries across all userIds 904 int num = 0; 905 for (int i = 0; i< mUidMap.size(); i++) { 906 num += mUidMap.valueAt(i).size(); 907 } 908 return num; 909 } 910 911 public void clear() { 912 mUidMap.clear(); 913 } 914 915 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 916 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 917 if (map == null) { 918 map = new ArrayMap<String, ArrayList<String>>(); 919 mUidMap.put(userId, map); 920 } 921 return map; 922 } 923 } 924 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 925 926 // Service Connection to remote media container service to copy 927 // package uri's from external media onto secure containers 928 // or internal storage. 929 private IMediaContainerService mContainerService = null; 930 931 static final int SEND_PENDING_BROADCAST = 1; 932 static final int MCS_BOUND = 3; 933 static final int END_COPY = 4; 934 static final int INIT_COPY = 5; 935 static final int MCS_UNBIND = 6; 936 static final int START_CLEANING_PACKAGE = 7; 937 static final int FIND_INSTALL_LOC = 8; 938 static final int POST_INSTALL = 9; 939 static final int MCS_RECONNECT = 10; 940 static final int MCS_GIVE_UP = 11; 941 static final int UPDATED_MEDIA_STATUS = 12; 942 static final int WRITE_SETTINGS = 13; 943 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 944 static final int PACKAGE_VERIFIED = 15; 945 static final int CHECK_PENDING_VERIFICATION = 16; 946 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 947 static final int INTENT_FILTER_VERIFIED = 18; 948 949 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 950 951 // Delay time in millisecs 952 static final int BROADCAST_DELAY = 10 * 1000; 953 954 static UserManagerService sUserManager; 955 956 // Stores a list of users whose package restrictions file needs to be updated 957 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 958 959 final private DefaultContainerConnection mDefContainerConn = 960 new DefaultContainerConnection(); 961 class DefaultContainerConnection implements ServiceConnection { 962 public void onServiceConnected(ComponentName name, IBinder service) { 963 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 964 IMediaContainerService imcs = 965 IMediaContainerService.Stub.asInterface(service); 966 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 967 } 968 969 public void onServiceDisconnected(ComponentName name) { 970 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 971 } 972 } 973 974 // Recordkeeping of restore-after-install operations that are currently in flight 975 // between the Package Manager and the Backup Manager 976 static class PostInstallData { 977 public InstallArgs args; 978 public PackageInstalledInfo res; 979 980 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 981 args = _a; 982 res = _r; 983 } 984 } 985 986 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 987 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 988 989 // XML tags for backup/restore of various bits of state 990 private static final String TAG_PREFERRED_BACKUP = "pa"; 991 private static final String TAG_DEFAULT_APPS = "da"; 992 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 993 994 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 995 private static final String TAG_ALL_GRANTS = "rt-grants"; 996 private static final String TAG_GRANT = "grant"; 997 private static final String ATTR_PACKAGE_NAME = "pkg"; 998 999 private static final String TAG_PERMISSION = "perm"; 1000 private static final String ATTR_PERMISSION_NAME = "name"; 1001 private static final String ATTR_IS_GRANTED = "g"; 1002 private static final String ATTR_USER_SET = "set"; 1003 private static final String ATTR_USER_FIXED = "fixed"; 1004 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1005 1006 // System/policy permission grants are not backed up 1007 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1008 FLAG_PERMISSION_POLICY_FIXED 1009 | FLAG_PERMISSION_SYSTEM_FIXED 1010 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1011 1012 // And we back up these user-adjusted states 1013 private static final int USER_RUNTIME_GRANT_MASK = 1014 FLAG_PERMISSION_USER_SET 1015 | FLAG_PERMISSION_USER_FIXED 1016 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1017 1018 final @Nullable String mRequiredVerifierPackage; 1019 final @Nullable String mRequiredInstallerPackage; 1020 1021 private final PackageUsage mPackageUsage = new PackageUsage(); 1022 1023 private class PackageUsage { 1024 private static final int WRITE_INTERVAL 1025 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1026 1027 private final Object mFileLock = new Object(); 1028 private final AtomicLong mLastWritten = new AtomicLong(0); 1029 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1030 1031 private boolean mIsHistoricalPackageUsageAvailable = true; 1032 1033 boolean isHistoricalPackageUsageAvailable() { 1034 return mIsHistoricalPackageUsageAvailable; 1035 } 1036 1037 void write(boolean force) { 1038 if (force) { 1039 writeInternal(); 1040 return; 1041 } 1042 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1043 && !DEBUG_DEXOPT) { 1044 return; 1045 } 1046 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1047 new Thread("PackageUsage_DiskWriter") { 1048 @Override 1049 public void run() { 1050 try { 1051 writeInternal(); 1052 } finally { 1053 mBackgroundWriteRunning.set(false); 1054 } 1055 } 1056 }.start(); 1057 } 1058 } 1059 1060 private void writeInternal() { 1061 synchronized (mPackages) { 1062 synchronized (mFileLock) { 1063 AtomicFile file = getFile(); 1064 FileOutputStream f = null; 1065 try { 1066 f = file.startWrite(); 1067 BufferedOutputStream out = new BufferedOutputStream(f); 1068 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1069 StringBuilder sb = new StringBuilder(); 1070 for (PackageParser.Package pkg : mPackages.values()) { 1071 if (pkg.mLastPackageUsageTimeInMills == 0) { 1072 continue; 1073 } 1074 sb.setLength(0); 1075 sb.append(pkg.packageName); 1076 sb.append(' '); 1077 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1078 sb.append('\n'); 1079 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1080 } 1081 out.flush(); 1082 file.finishWrite(f); 1083 } catch (IOException e) { 1084 if (f != null) { 1085 file.failWrite(f); 1086 } 1087 Log.e(TAG, "Failed to write package usage times", e); 1088 } 1089 } 1090 } 1091 mLastWritten.set(SystemClock.elapsedRealtime()); 1092 } 1093 1094 void readLP() { 1095 synchronized (mFileLock) { 1096 AtomicFile file = getFile(); 1097 BufferedInputStream in = null; 1098 try { 1099 in = new BufferedInputStream(file.openRead()); 1100 StringBuffer sb = new StringBuffer(); 1101 while (true) { 1102 String packageName = readToken(in, sb, ' '); 1103 if (packageName == null) { 1104 break; 1105 } 1106 String timeInMillisString = readToken(in, sb, '\n'); 1107 if (timeInMillisString == null) { 1108 throw new IOException("Failed to find last usage time for package " 1109 + packageName); 1110 } 1111 PackageParser.Package pkg = mPackages.get(packageName); 1112 if (pkg == null) { 1113 continue; 1114 } 1115 long timeInMillis; 1116 try { 1117 timeInMillis = Long.parseLong(timeInMillisString); 1118 } catch (NumberFormatException e) { 1119 throw new IOException("Failed to parse " + timeInMillisString 1120 + " as a long.", e); 1121 } 1122 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1123 } 1124 } catch (FileNotFoundException expected) { 1125 mIsHistoricalPackageUsageAvailable = false; 1126 } catch (IOException e) { 1127 Log.w(TAG, "Failed to read package usage times", e); 1128 } finally { 1129 IoUtils.closeQuietly(in); 1130 } 1131 } 1132 mLastWritten.set(SystemClock.elapsedRealtime()); 1133 } 1134 1135 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1136 throws IOException { 1137 sb.setLength(0); 1138 while (true) { 1139 int ch = in.read(); 1140 if (ch == -1) { 1141 if (sb.length() == 0) { 1142 return null; 1143 } 1144 throw new IOException("Unexpected EOF"); 1145 } 1146 if (ch == endOfToken) { 1147 return sb.toString(); 1148 } 1149 sb.append((char)ch); 1150 } 1151 } 1152 1153 private AtomicFile getFile() { 1154 File dataDir = Environment.getDataDirectory(); 1155 File systemDir = new File(dataDir, "system"); 1156 File fname = new File(systemDir, "package-usage.list"); 1157 return new AtomicFile(fname); 1158 } 1159 } 1160 1161 class PackageHandler extends Handler { 1162 private boolean mBound = false; 1163 final ArrayList<HandlerParams> mPendingInstalls = 1164 new ArrayList<HandlerParams>(); 1165 1166 private boolean connectToService() { 1167 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1168 " DefaultContainerService"); 1169 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1170 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1171 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1172 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 mBound = true; 1175 return true; 1176 } 1177 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1178 return false; 1179 } 1180 1181 private void disconnectService() { 1182 mContainerService = null; 1183 mBound = false; 1184 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1185 mContext.unbindService(mDefContainerConn); 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 1189 PackageHandler(Looper looper) { 1190 super(looper); 1191 } 1192 1193 public void handleMessage(Message msg) { 1194 try { 1195 doHandleMessage(msg); 1196 } finally { 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1198 } 1199 } 1200 1201 void doHandleMessage(Message msg) { 1202 switch (msg.what) { 1203 case INIT_COPY: { 1204 HandlerParams params = (HandlerParams) msg.obj; 1205 int idx = mPendingInstalls.size(); 1206 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1207 // If a bind was already initiated we dont really 1208 // need to do anything. The pending install 1209 // will be processed later on. 1210 if (!mBound) { 1211 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1212 System.identityHashCode(mHandler)); 1213 // If this is the only one pending we might 1214 // have to bind to the service again. 1215 if (!connectToService()) { 1216 Slog.e(TAG, "Failed to bind to media container service"); 1217 params.serviceError(); 1218 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1219 System.identityHashCode(mHandler)); 1220 if (params.traceMethod != null) { 1221 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1222 params.traceCookie); 1223 } 1224 return; 1225 } else { 1226 // Once we bind to the service, the first 1227 // pending request will be processed. 1228 mPendingInstalls.add(idx, params); 1229 } 1230 } else { 1231 mPendingInstalls.add(idx, params); 1232 // Already bound to the service. Just make 1233 // sure we trigger off processing the first request. 1234 if (idx == 0) { 1235 mHandler.sendEmptyMessage(MCS_BOUND); 1236 } 1237 } 1238 break; 1239 } 1240 case MCS_BOUND: { 1241 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1242 if (msg.obj != null) { 1243 mContainerService = (IMediaContainerService) msg.obj; 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1245 System.identityHashCode(mHandler)); 1246 } 1247 if (mContainerService == null) { 1248 if (!mBound) { 1249 // Something seriously wrong since we are not bound and we are not 1250 // waiting for connection. Bail out. 1251 Slog.e(TAG, "Cannot bind to media container service"); 1252 for (HandlerParams params : mPendingInstalls) { 1253 // Indicate service bind error 1254 params.serviceError(); 1255 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1256 System.identityHashCode(params)); 1257 if (params.traceMethod != null) { 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1259 params.traceMethod, params.traceCookie); 1260 } 1261 return; 1262 } 1263 mPendingInstalls.clear(); 1264 } else { 1265 Slog.w(TAG, "Waiting to connect to media container service"); 1266 } 1267 } else if (mPendingInstalls.size() > 0) { 1268 HandlerParams params = mPendingInstalls.get(0); 1269 if (params != null) { 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1271 System.identityHashCode(params)); 1272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1273 if (params.startCopy()) { 1274 // We are done... look for more work or to 1275 // go idle. 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Checking for more work or unbind..."); 1278 // Delete pending install 1279 if (mPendingInstalls.size() > 0) { 1280 mPendingInstalls.remove(0); 1281 } 1282 if (mPendingInstalls.size() == 0) { 1283 if (mBound) { 1284 if (DEBUG_SD_INSTALL) Log.i(TAG, 1285 "Posting delayed MCS_UNBIND"); 1286 removeMessages(MCS_UNBIND); 1287 Message ubmsg = obtainMessage(MCS_UNBIND); 1288 // Unbind after a little delay, to avoid 1289 // continual thrashing. 1290 sendMessageDelayed(ubmsg, 10000); 1291 } 1292 } else { 1293 // There are more pending requests in queue. 1294 // Just post MCS_BOUND message to trigger processing 1295 // of next pending install. 1296 if (DEBUG_SD_INSTALL) Log.i(TAG, 1297 "Posting MCS_BOUND for next work"); 1298 mHandler.sendEmptyMessage(MCS_BOUND); 1299 } 1300 } 1301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1302 } 1303 } else { 1304 // Should never happen ideally. 1305 Slog.w(TAG, "Empty queue"); 1306 } 1307 break; 1308 } 1309 case MCS_RECONNECT: { 1310 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1311 if (mPendingInstalls.size() > 0) { 1312 if (mBound) { 1313 disconnectService(); 1314 } 1315 if (!connectToService()) { 1316 Slog.e(TAG, "Failed to bind to media container service"); 1317 for (HandlerParams params : mPendingInstalls) { 1318 // Indicate service bind error 1319 params.serviceError(); 1320 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1321 System.identityHashCode(params)); 1322 } 1323 mPendingInstalls.clear(); 1324 } 1325 } 1326 break; 1327 } 1328 case MCS_UNBIND: { 1329 // If there is no actual work left, then time to unbind. 1330 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1331 1332 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1333 if (mBound) { 1334 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1335 1336 disconnectService(); 1337 } 1338 } else if (mPendingInstalls.size() > 0) { 1339 // There are more pending requests in queue. 1340 // Just post MCS_BOUND message to trigger processing 1341 // of next pending install. 1342 mHandler.sendEmptyMessage(MCS_BOUND); 1343 } 1344 1345 break; 1346 } 1347 case MCS_GIVE_UP: { 1348 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1349 HandlerParams params = mPendingInstalls.remove(0); 1350 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1351 System.identityHashCode(params)); 1352 break; 1353 } 1354 case SEND_PENDING_BROADCAST: { 1355 String packages[]; 1356 ArrayList<String> components[]; 1357 int size = 0; 1358 int uids[]; 1359 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1360 synchronized (mPackages) { 1361 if (mPendingBroadcasts == null) { 1362 return; 1363 } 1364 size = mPendingBroadcasts.size(); 1365 if (size <= 0) { 1366 // Nothing to be done. Just return 1367 return; 1368 } 1369 packages = new String[size]; 1370 components = new ArrayList[size]; 1371 uids = new int[size]; 1372 int i = 0; // filling out the above arrays 1373 1374 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1375 int packageUserId = mPendingBroadcasts.userIdAt(n); 1376 Iterator<Map.Entry<String, ArrayList<String>>> it 1377 = mPendingBroadcasts.packagesForUserId(packageUserId) 1378 .entrySet().iterator(); 1379 while (it.hasNext() && i < size) { 1380 Map.Entry<String, ArrayList<String>> ent = it.next(); 1381 packages[i] = ent.getKey(); 1382 components[i] = ent.getValue(); 1383 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1384 uids[i] = (ps != null) 1385 ? UserHandle.getUid(packageUserId, ps.appId) 1386 : -1; 1387 i++; 1388 } 1389 } 1390 size = i; 1391 mPendingBroadcasts.clear(); 1392 } 1393 // Send broadcasts 1394 for (int i = 0; i < size; i++) { 1395 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1396 } 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1398 break; 1399 } 1400 case START_CLEANING_PACKAGE: { 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 final String packageName = (String)msg.obj; 1403 final int userId = msg.arg1; 1404 final boolean andCode = msg.arg2 != 0; 1405 synchronized (mPackages) { 1406 if (userId == UserHandle.USER_ALL) { 1407 int[] users = sUserManager.getUserIds(); 1408 for (int user : users) { 1409 mSettings.addPackageToCleanLPw( 1410 new PackageCleanItem(user, packageName, andCode)); 1411 } 1412 } else { 1413 mSettings.addPackageToCleanLPw( 1414 new PackageCleanItem(userId, packageName, andCode)); 1415 } 1416 } 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1418 startCleaningPackages(); 1419 } break; 1420 case POST_INSTALL: { 1421 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1422 1423 PostInstallData data = mRunningInstalls.get(msg.arg1); 1424 mRunningInstalls.delete(msg.arg1); 1425 1426 if (data != null) { 1427 InstallArgs args = data.args; 1428 PackageInstalledInfo parentRes = data.res; 1429 1430 final boolean grantPermissions = (args.installFlags 1431 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1432 final boolean killApp = (args.installFlags 1433 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1434 final String[] grantedPermissions = args.installGrantPermissions; 1435 1436 // Handle the parent package 1437 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1438 grantedPermissions, args.observer); 1439 1440 // Handle the child packages 1441 final int childCount = (parentRes.addedChildPackages != null) 1442 ? parentRes.addedChildPackages.size() : 0; 1443 for (int i = 0; i < childCount; i++) { 1444 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1445 handlePackagePostInstall(childRes, grantPermissions, killApp, 1446 grantedPermissions, args.observer); 1447 } 1448 1449 // Log tracing if needed 1450 if (args.traceMethod != null) { 1451 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1452 args.traceCookie); 1453 } 1454 } else { 1455 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1456 } 1457 1458 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1459 } break; 1460 case UPDATED_MEDIA_STATUS: { 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1462 boolean reportStatus = msg.arg1 == 1; 1463 boolean doGc = msg.arg2 == 1; 1464 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1465 if (doGc) { 1466 // Force a gc to clear up stale containers. 1467 Runtime.getRuntime().gc(); 1468 } 1469 if (msg.obj != null) { 1470 @SuppressWarnings("unchecked") 1471 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1473 // Unload containers 1474 unloadAllContainers(args); 1475 } 1476 if (reportStatus) { 1477 try { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1479 PackageHelper.getMountService().finishMediaUpdate(); 1480 } catch (RemoteException e) { 1481 Log.e(TAG, "MountService not running?"); 1482 } 1483 } 1484 } break; 1485 case WRITE_SETTINGS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_SETTINGS); 1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1490 mSettings.writeLPr(); 1491 mDirtyUsers.clear(); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 } break; 1495 case WRITE_PACKAGE_RESTRICTIONS: { 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1497 synchronized (mPackages) { 1498 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1499 for (int userId : mDirtyUsers) { 1500 mSettings.writePackageRestrictionsLPr(userId); 1501 } 1502 mDirtyUsers.clear(); 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 } break; 1506 case CHECK_PENDING_VERIFICATION: { 1507 final int verificationId = msg.arg1; 1508 final PackageVerificationState state = mPendingVerification.get(verificationId); 1509 1510 if ((state != null) && !state.timeoutExtended()) { 1511 final InstallArgs args = state.getInstallArgs(); 1512 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1513 1514 Slog.i(TAG, "Verification timed out for " + originUri); 1515 mPendingVerification.remove(verificationId); 1516 1517 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1518 1519 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1520 Slog.i(TAG, "Continuing with installation of " + originUri); 1521 state.setVerifierResponse(Binder.getCallingUid(), 1522 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1523 broadcastPackageVerified(verificationId, originUri, 1524 PackageManager.VERIFICATION_ALLOW, 1525 state.getInstallArgs().getUser()); 1526 try { 1527 ret = args.copyApk(mContainerService, true); 1528 } catch (RemoteException e) { 1529 Slog.e(TAG, "Could not contact the ContainerService"); 1530 } 1531 } else { 1532 broadcastPackageVerified(verificationId, originUri, 1533 PackageManager.VERIFICATION_REJECT, 1534 state.getInstallArgs().getUser()); 1535 } 1536 1537 Trace.asyncTraceEnd( 1538 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1539 1540 processPendingInstall(args, ret); 1541 mHandler.sendEmptyMessage(MCS_UNBIND); 1542 } 1543 break; 1544 } 1545 case PACKAGE_VERIFIED: { 1546 final int verificationId = msg.arg1; 1547 1548 final PackageVerificationState state = mPendingVerification.get(verificationId); 1549 if (state == null) { 1550 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1551 break; 1552 } 1553 1554 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1555 1556 state.setVerifierResponse(response.callerUid, response.code); 1557 1558 if (state.isVerificationComplete()) { 1559 mPendingVerification.remove(verificationId); 1560 1561 final InstallArgs args = state.getInstallArgs(); 1562 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1563 1564 int ret; 1565 if (state.isInstallAllowed()) { 1566 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1567 broadcastPackageVerified(verificationId, originUri, 1568 response.code, state.getInstallArgs().getUser()); 1569 try { 1570 ret = args.copyApk(mContainerService, true); 1571 } catch (RemoteException e) { 1572 Slog.e(TAG, "Could not contact the ContainerService"); 1573 } 1574 } else { 1575 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1576 } 1577 1578 Trace.asyncTraceEnd( 1579 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1580 1581 processPendingInstall(args, ret); 1582 mHandler.sendEmptyMessage(MCS_UNBIND); 1583 } 1584 1585 break; 1586 } 1587 case START_INTENT_FILTER_VERIFICATIONS: { 1588 IFVerificationParams params = (IFVerificationParams) msg.obj; 1589 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1590 params.replacing, params.pkg); 1591 break; 1592 } 1593 case INTENT_FILTER_VERIFIED: { 1594 final int verificationId = msg.arg1; 1595 1596 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1597 verificationId); 1598 if (state == null) { 1599 Slog.w(TAG, "Invalid IntentFilter verification token " 1600 + verificationId + " received"); 1601 break; 1602 } 1603 1604 final int userId = state.getUserId(); 1605 1606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1607 "Processing IntentFilter verification with token:" 1608 + verificationId + " and userId:" + userId); 1609 1610 final IntentFilterVerificationResponse response = 1611 (IntentFilterVerificationResponse) msg.obj; 1612 1613 state.setVerifierResponse(response.callerUid, response.code); 1614 1615 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1616 "IntentFilter verification with token:" + verificationId 1617 + " and userId:" + userId 1618 + " is settings verifier response with response code:" 1619 + response.code); 1620 1621 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1622 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1623 + response.getFailedDomainsString()); 1624 } 1625 1626 if (state.isVerificationComplete()) { 1627 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1628 } else { 1629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1630 "IntentFilter verification with token:" + verificationId 1631 + " was not said to be complete"); 1632 } 1633 1634 break; 1635 } 1636 } 1637 } 1638 } 1639 1640 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1641 boolean killApp, String[] grantedPermissions, 1642 IPackageInstallObserver2 installObserver) { 1643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1644 // Send the removed broadcasts 1645 if (res.removedInfo != null) { 1646 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1647 } 1648 1649 // Now that we successfully installed the package, grant runtime 1650 // permissions if requested before broadcasting the install. 1651 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1652 >= Build.VERSION_CODES.M) { 1653 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1654 } 1655 1656 final boolean update = res.removedInfo != null 1657 && res.removedInfo.removedPackage != null; 1658 1659 // If this is the first time we have child packages for a disabled privileged 1660 // app that had no children, we grant requested runtime permissions to the new 1661 // children if the parent on the system image had them already granted. 1662 if (res.pkg.parentPackage != null) { 1663 synchronized (mPackages) { 1664 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1665 } 1666 } 1667 1668 synchronized (mPackages) { 1669 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1670 } 1671 1672 final String packageName = res.pkg.applicationInfo.packageName; 1673 Bundle extras = new Bundle(1); 1674 extras.putInt(Intent.EXTRA_UID, res.uid); 1675 1676 // Determine the set of users who are adding this package for 1677 // the first time vs. those who are seeing an update. 1678 int[] firstUsers = EMPTY_INT_ARRAY; 1679 int[] updateUsers = EMPTY_INT_ARRAY; 1680 if (res.origUsers == null || res.origUsers.length == 0) { 1681 firstUsers = res.newUsers; 1682 } else { 1683 for (int newUser : res.newUsers) { 1684 boolean isNew = true; 1685 for (int origUser : res.origUsers) { 1686 if (origUser == newUser) { 1687 isNew = false; 1688 break; 1689 } 1690 } 1691 if (isNew) { 1692 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1693 } else { 1694 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1695 } 1696 } 1697 } 1698 1699 // Send installed broadcasts if the install/update is not ephemeral 1700 if (!isEphemeral(res.pkg)) { 1701 // Send added for users that see the package for the first time 1702 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1703 extras, 0 /*flags*/, null /*targetPackage*/, 1704 null /*finishedReceiver*/, firstUsers); 1705 1706 // Send added for users that don't see the package for the first time 1707 if (update) { 1708 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1709 } 1710 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1711 extras, 0 /*flags*/, null /*targetPackage*/, 1712 null /*finishedReceiver*/, updateUsers); 1713 1714 // Send replaced for users that don't see the package for the first time 1715 if (update) { 1716 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1717 packageName, extras, 0 /*flags*/, 1718 null /*targetPackage*/, null /*finishedReceiver*/, 1719 updateUsers); 1720 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1721 null /*package*/, null /*extras*/, 0 /*flags*/, 1722 packageName /*targetPackage*/, 1723 null /*finishedReceiver*/, updateUsers); 1724 } 1725 1726 // Send broadcast package appeared if forward locked/external for all users 1727 // treat asec-hosted packages like removable media on upgrade 1728 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1729 if (DEBUG_INSTALL) { 1730 Slog.i(TAG, "upgrading pkg " + res.pkg 1731 + " is ASEC-hosted -> AVAILABLE"); 1732 } 1733 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1734 ArrayList<String> pkgList = new ArrayList<>(1); 1735 pkgList.add(packageName); 1736 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1737 } 1738 } 1739 1740 // Work that needs to happen on first install within each user 1741 if (firstUsers != null && firstUsers.length > 0) { 1742 synchronized (mPackages) { 1743 for (int userId : firstUsers) { 1744 // If this app is a browser and it's newly-installed for some 1745 // users, clear any default-browser state in those users. The 1746 // app's nature doesn't depend on the user, so we can just check 1747 // its browser nature in any user and generalize. 1748 if (packageIsBrowser(packageName, userId)) { 1749 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1750 } 1751 1752 // We may also need to apply pending (restored) runtime 1753 // permission grants within these users. 1754 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1755 } 1756 } 1757 } 1758 1759 // Log current value of "unknown sources" setting 1760 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1761 getUnknownSourcesSettings()); 1762 1763 // Force a gc to clear up things 1764 Runtime.getRuntime().gc(); 1765 1766 // Remove the replaced package's older resources safely now 1767 // We delete after a gc for applications on sdcard. 1768 if (res.removedInfo != null && res.removedInfo.args != null) { 1769 synchronized (mInstallLock) { 1770 res.removedInfo.args.doPostDeleteLI(true); 1771 } 1772 } 1773 } 1774 1775 // If someone is watching installs - notify them 1776 if (installObserver != null) { 1777 try { 1778 Bundle extras = extrasForInstallResult(res); 1779 installObserver.onPackageInstalled(res.name, res.returnCode, 1780 res.returnMsg, extras); 1781 } catch (RemoteException e) { 1782 Slog.i(TAG, "Observer no longer exists."); 1783 } 1784 } 1785 } 1786 1787 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1788 PackageParser.Package pkg) { 1789 if (pkg.parentPackage == null) { 1790 return; 1791 } 1792 if (pkg.requestedPermissions == null) { 1793 return; 1794 } 1795 final PackageSetting disabledSysParentPs = mSettings 1796 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1797 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1798 || !disabledSysParentPs.isPrivileged() 1799 || (disabledSysParentPs.childPackageNames != null 1800 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1801 return; 1802 } 1803 final int[] allUserIds = sUserManager.getUserIds(); 1804 final int permCount = pkg.requestedPermissions.size(); 1805 for (int i = 0; i < permCount; i++) { 1806 String permission = pkg.requestedPermissions.get(i); 1807 BasePermission bp = mSettings.mPermissions.get(permission); 1808 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1809 continue; 1810 } 1811 for (int userId : allUserIds) { 1812 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1813 permission, userId)) { 1814 grantRuntimePermission(pkg.packageName, permission, userId); 1815 } 1816 } 1817 } 1818 } 1819 1820 private StorageEventListener mStorageListener = new StorageEventListener() { 1821 @Override 1822 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1823 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1824 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1825 final String volumeUuid = vol.getFsUuid(); 1826 1827 // Clean up any users or apps that were removed or recreated 1828 // while this volume was missing 1829 reconcileUsers(volumeUuid); 1830 reconcileApps(volumeUuid); 1831 1832 // Clean up any install sessions that expired or were 1833 // cancelled while this volume was missing 1834 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1835 1836 loadPrivatePackages(vol); 1837 1838 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1839 unloadPrivatePackages(vol); 1840 } 1841 } 1842 1843 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1844 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1845 updateExternalMediaStatus(true, false); 1846 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1847 updateExternalMediaStatus(false, false); 1848 } 1849 } 1850 } 1851 1852 @Override 1853 public void onVolumeForgotten(String fsUuid) { 1854 if (TextUtils.isEmpty(fsUuid)) { 1855 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1856 return; 1857 } 1858 1859 // Remove any apps installed on the forgotten volume 1860 synchronized (mPackages) { 1861 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1862 for (PackageSetting ps : packages) { 1863 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1864 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1865 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1866 } 1867 1868 mSettings.onVolumeForgotten(fsUuid); 1869 mSettings.writeLPr(); 1870 } 1871 } 1872 }; 1873 1874 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1875 String[] grantedPermissions) { 1876 for (int userId : userIds) { 1877 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1878 } 1879 1880 // We could have touched GID membership, so flush out packages.list 1881 synchronized (mPackages) { 1882 mSettings.writePackageListLPr(); 1883 } 1884 } 1885 1886 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1887 String[] grantedPermissions) { 1888 SettingBase sb = (SettingBase) pkg.mExtras; 1889 if (sb == null) { 1890 return; 1891 } 1892 1893 PermissionsState permissionsState = sb.getPermissionsState(); 1894 1895 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1896 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1897 1898 synchronized (mPackages) { 1899 for (String permission : pkg.requestedPermissions) { 1900 BasePermission bp = mSettings.mPermissions.get(permission); 1901 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1902 && (grantedPermissions == null 1903 || ArrayUtils.contains(grantedPermissions, permission))) { 1904 final int flags = permissionsState.getPermissionFlags(permission, userId); 1905 // Installer cannot change immutable permissions. 1906 if ((flags & immutableFlags) == 0) { 1907 grantRuntimePermission(pkg.packageName, permission, userId); 1908 } 1909 } 1910 } 1911 } 1912 } 1913 1914 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1915 Bundle extras = null; 1916 switch (res.returnCode) { 1917 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1918 extras = new Bundle(); 1919 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1920 res.origPermission); 1921 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1922 res.origPackage); 1923 break; 1924 } 1925 case PackageManager.INSTALL_SUCCEEDED: { 1926 extras = new Bundle(); 1927 extras.putBoolean(Intent.EXTRA_REPLACING, 1928 res.removedInfo != null && res.removedInfo.removedPackage != null); 1929 break; 1930 } 1931 } 1932 return extras; 1933 } 1934 1935 void scheduleWriteSettingsLocked() { 1936 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1937 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1938 } 1939 } 1940 1941 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1942 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1943 scheduleWritePackageRestrictionsLocked(userId); 1944 } 1945 1946 void scheduleWritePackageRestrictionsLocked(int userId) { 1947 final int[] userIds = (userId == UserHandle.USER_ALL) 1948 ? sUserManager.getUserIds() : new int[]{userId}; 1949 for (int nextUserId : userIds) { 1950 if (!sUserManager.exists(nextUserId)) return; 1951 mDirtyUsers.add(nextUserId); 1952 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1953 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1954 } 1955 } 1956 } 1957 1958 public static PackageManagerService main(Context context, Installer installer, 1959 boolean factoryTest, boolean onlyCore) { 1960 PackageManagerService m = new PackageManagerService(context, installer, 1961 factoryTest, onlyCore); 1962 m.enableSystemUserPackages(); 1963 ServiceManager.addService("package", m); 1964 return m; 1965 } 1966 1967 private void enableSystemUserPackages() { 1968 if (!UserManager.isSplitSystemUser()) { 1969 return; 1970 } 1971 // For system user, enable apps based on the following conditions: 1972 // - app is whitelisted or belong to one of these groups: 1973 // -- system app which has no launcher icons 1974 // -- system app which has INTERACT_ACROSS_USERS permission 1975 // -- system IME app 1976 // - app is not in the blacklist 1977 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1978 Set<String> enableApps = new ArraySet<>(); 1979 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1980 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1981 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1982 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1983 enableApps.addAll(wlApps); 1984 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1985 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1986 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1987 enableApps.removeAll(blApps); 1988 Log.i(TAG, "Applications installed for system user: " + enableApps); 1989 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1990 UserHandle.SYSTEM); 1991 final int allAppsSize = allAps.size(); 1992 synchronized (mPackages) { 1993 for (int i = 0; i < allAppsSize; i++) { 1994 String pName = allAps.get(i); 1995 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1996 // Should not happen, but we shouldn't be failing if it does 1997 if (pkgSetting == null) { 1998 continue; 1999 } 2000 boolean install = enableApps.contains(pName); 2001 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2002 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2003 + " for system user"); 2004 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2005 } 2006 } 2007 } 2008 } 2009 2010 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2011 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2012 Context.DISPLAY_SERVICE); 2013 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2014 } 2015 2016 public PackageManagerService(Context context, Installer installer, 2017 boolean factoryTest, boolean onlyCore) { 2018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2019 SystemClock.uptimeMillis()); 2020 2021 if (mSdkVersion <= 0) { 2022 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2023 } 2024 2025 mContext = context; 2026 mFactoryTest = factoryTest; 2027 mOnlyCore = onlyCore; 2028 mMetrics = new DisplayMetrics(); 2029 mSettings = new Settings(mPackages); 2030 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2031 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2032 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2033 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2034 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2035 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2036 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2037 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2038 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2039 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2040 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2041 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2042 2043 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2044 if (separateProcesses != null && separateProcesses.length() > 0) { 2045 if ("*".equals(separateProcesses)) { 2046 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2047 mSeparateProcesses = null; 2048 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2049 } else { 2050 mDefParseFlags = 0; 2051 mSeparateProcesses = separateProcesses.split(","); 2052 Slog.w(TAG, "Running with debug.separate_processes: " 2053 + separateProcesses); 2054 } 2055 } else { 2056 mDefParseFlags = 0; 2057 mSeparateProcesses = null; 2058 } 2059 2060 mInstaller = installer; 2061 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2062 "*dexopt*"); 2063 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2064 2065 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2066 FgThread.get().getLooper()); 2067 2068 getDefaultDisplayMetrics(context, mMetrics); 2069 2070 SystemConfig systemConfig = SystemConfig.getInstance(); 2071 mGlobalGids = systemConfig.getGlobalGids(); 2072 mSystemPermissions = systemConfig.getSystemPermissions(); 2073 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2074 2075 synchronized (mInstallLock) { 2076 // writer 2077 synchronized (mPackages) { 2078 mHandlerThread = new ServiceThread(TAG, 2079 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2080 mHandlerThread.start(); 2081 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2082 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2083 2084 File dataDir = Environment.getDataDirectory(); 2085 mAppInstallDir = new File(dataDir, "app"); 2086 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2087 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2088 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2089 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2090 2091 sUserManager = new UserManagerService(context, this, mPackages); 2092 2093 // Propagate permission configuration in to package manager. 2094 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2095 = systemConfig.getPermissions(); 2096 for (int i=0; i<permConfig.size(); i++) { 2097 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2098 BasePermission bp = mSettings.mPermissions.get(perm.name); 2099 if (bp == null) { 2100 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2101 mSettings.mPermissions.put(perm.name, bp); 2102 } 2103 if (perm.gids != null) { 2104 bp.setGids(perm.gids, perm.perUser); 2105 } 2106 } 2107 2108 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2109 for (int i=0; i<libConfig.size(); i++) { 2110 mSharedLibraries.put(libConfig.keyAt(i), 2111 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2112 } 2113 2114 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2115 2116 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2117 2118 String customResolverActivity = Resources.getSystem().getString( 2119 R.string.config_customResolverActivity); 2120 if (TextUtils.isEmpty(customResolverActivity)) { 2121 customResolverActivity = null; 2122 } else { 2123 mCustomResolverComponentName = ComponentName.unflattenFromString( 2124 customResolverActivity); 2125 } 2126 2127 long startTime = SystemClock.uptimeMillis(); 2128 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2130 startTime); 2131 2132 // Set flag to monitor and not change apk file paths when 2133 // scanning install directories. 2134 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2135 2136 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2137 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2138 2139 if (bootClassPath == null) { 2140 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2141 } 2142 2143 if (systemServerClassPath == null) { 2144 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2145 } 2146 2147 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2148 final String[] dexCodeInstructionSets = 2149 getDexCodeInstructionSets( 2150 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2151 2152 /** 2153 * Ensure all external libraries have had dexopt run on them. 2154 */ 2155 if (mSharedLibraries.size() > 0) { 2156 // NOTE: For now, we're compiling these system "shared libraries" 2157 // (and framework jars) into all available architectures. It's possible 2158 // to compile them only when we come across an app that uses them (there's 2159 // already logic for that in scanPackageLI) but that adds some complexity. 2160 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2161 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2162 final String lib = libEntry.path; 2163 if (lib == null) { 2164 continue; 2165 } 2166 2167 try { 2168 // Shared libraries do not have profiles so we perform a full 2169 // AOT compilation (if needed). 2170 int dexoptNeeded = DexFile.getDexOptNeeded( 2171 lib, dexCodeInstructionSet, 2172 DexFile.COMPILATION_TYPE_FULL); 2173 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2174 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2175 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2176 StorageManager.UUID_PRIVATE_INTERNAL, 2177 false /*useProfiles*/); 2178 } 2179 } catch (FileNotFoundException e) { 2180 Slog.w(TAG, "Library not found: " + lib); 2181 } catch (IOException | InstallerException e) { 2182 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2183 + e.getMessage()); 2184 } 2185 } 2186 } 2187 } 2188 2189 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2190 2191 final VersionInfo ver = mSettings.getInternalVersion(); 2192 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2193 // when upgrading from pre-M, promote system app permissions from install to runtime 2194 mPromoteSystemApps = 2195 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2196 2197 // save off the names of pre-existing system packages prior to scanning; we don't 2198 // want to automatically grant runtime permissions for new system apps 2199 if (mPromoteSystemApps) { 2200 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2201 while (pkgSettingIter.hasNext()) { 2202 PackageSetting ps = pkgSettingIter.next(); 2203 if (isSystemApp(ps)) { 2204 mExistingSystemPackages.add(ps.name); 2205 } 2206 } 2207 } 2208 2209 // Collect vendor overlay packages. 2210 // (Do this before scanning any apps.) 2211 // For security and version matching reason, only consider 2212 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2213 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2214 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2215 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2216 2217 // Find base frameworks (resource packages without code). 2218 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2219 | PackageParser.PARSE_IS_SYSTEM_DIR 2220 | PackageParser.PARSE_IS_PRIVILEGED, 2221 scanFlags | SCAN_NO_DEX, 0); 2222 2223 // Collected privileged system packages. 2224 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2225 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2226 | PackageParser.PARSE_IS_SYSTEM_DIR 2227 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2228 2229 // Collect ordinary system packages. 2230 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2231 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2232 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2233 2234 // Collect all vendor packages. 2235 File vendorAppDir = new File("/vendor/app"); 2236 try { 2237 vendorAppDir = vendorAppDir.getCanonicalFile(); 2238 } catch (IOException e) { 2239 // failed to look up canonical path, continue with original one 2240 } 2241 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2242 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2243 2244 // Collect all OEM packages. 2245 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2246 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2247 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2248 2249 // Prune any system packages that no longer exist. 2250 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2251 if (!mOnlyCore) { 2252 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2253 while (psit.hasNext()) { 2254 PackageSetting ps = psit.next(); 2255 2256 /* 2257 * If this is not a system app, it can't be a 2258 * disable system app. 2259 */ 2260 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2261 continue; 2262 } 2263 2264 /* 2265 * If the package is scanned, it's not erased. 2266 */ 2267 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2268 if (scannedPkg != null) { 2269 /* 2270 * If the system app is both scanned and in the 2271 * disabled packages list, then it must have been 2272 * added via OTA. Remove it from the currently 2273 * scanned package so the previously user-installed 2274 * application can be scanned. 2275 */ 2276 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2277 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2278 + ps.name + "; removing system app. Last known codePath=" 2279 + ps.codePathString + ", installStatus=" + ps.installStatus 2280 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2281 + scannedPkg.mVersionCode); 2282 removePackageLI(scannedPkg, true); 2283 mExpectingBetter.put(ps.name, ps.codePath); 2284 } 2285 2286 continue; 2287 } 2288 2289 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2290 psit.remove(); 2291 logCriticalInfo(Log.WARN, "System package " + ps.name 2292 + " no longer exists; wiping its data"); 2293 removeDataDirsLI(null, ps.name); 2294 } else { 2295 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2296 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2297 possiblyDeletedUpdatedSystemApps.add(ps.name); 2298 } 2299 } 2300 } 2301 } 2302 2303 //look for any incomplete package installations 2304 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2305 //clean up list 2306 for(int i = 0; i < deletePkgsList.size(); i++) { 2307 //clean up here 2308 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2309 } 2310 //delete tmp files 2311 deleteTempPackageFiles(); 2312 2313 // Remove any shared userIDs that have no associated packages 2314 mSettings.pruneSharedUsersLPw(); 2315 2316 if (!mOnlyCore) { 2317 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2318 SystemClock.uptimeMillis()); 2319 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2320 2321 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2322 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2323 2324 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2325 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2326 2327 /** 2328 * Remove disable package settings for any updated system 2329 * apps that were removed via an OTA. If they're not a 2330 * previously-updated app, remove them completely. 2331 * Otherwise, just revoke their system-level permissions. 2332 */ 2333 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2334 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2335 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2336 2337 String msg; 2338 if (deletedPkg == null) { 2339 msg = "Updated system package " + deletedAppName 2340 + " no longer exists; wiping its data"; 2341 removeDataDirsLI(null, deletedAppName); 2342 } else { 2343 msg = "Updated system app + " + deletedAppName 2344 + " no longer present; removing system privileges for " 2345 + deletedAppName; 2346 2347 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2348 2349 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2350 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2351 } 2352 logCriticalInfo(Log.WARN, msg); 2353 } 2354 2355 /** 2356 * Make sure all system apps that we expected to appear on 2357 * the userdata partition actually showed up. If they never 2358 * appeared, crawl back and revive the system version. 2359 */ 2360 for (int i = 0; i < mExpectingBetter.size(); i++) { 2361 final String packageName = mExpectingBetter.keyAt(i); 2362 if (!mPackages.containsKey(packageName)) { 2363 final File scanFile = mExpectingBetter.valueAt(i); 2364 2365 logCriticalInfo(Log.WARN, "Expected better " + packageName 2366 + " but never showed up; reverting to system"); 2367 2368 final int reparseFlags; 2369 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2370 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2371 | PackageParser.PARSE_IS_SYSTEM_DIR 2372 | PackageParser.PARSE_IS_PRIVILEGED; 2373 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2374 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2375 | PackageParser.PARSE_IS_SYSTEM_DIR; 2376 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2377 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2378 | PackageParser.PARSE_IS_SYSTEM_DIR; 2379 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2380 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2381 | PackageParser.PARSE_IS_SYSTEM_DIR; 2382 } else { 2383 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2384 continue; 2385 } 2386 2387 mSettings.enableSystemPackageLPw(packageName); 2388 2389 try { 2390 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2391 } catch (PackageManagerException e) { 2392 Slog.e(TAG, "Failed to parse original system package: " 2393 + e.getMessage()); 2394 } 2395 } 2396 } 2397 } 2398 mExpectingBetter.clear(); 2399 2400 // Now that we know all of the shared libraries, update all clients to have 2401 // the correct library paths. 2402 updateAllSharedLibrariesLPw(); 2403 2404 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2405 // NOTE: We ignore potential failures here during a system scan (like 2406 // the rest of the commands above) because there's precious little we 2407 // can do about it. A settings error is reported, though. 2408 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2409 false /* boot complete */); 2410 } 2411 2412 // Now that we know all the packages we are keeping, 2413 // read and update their last usage times. 2414 mPackageUsage.readLP(); 2415 2416 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2417 SystemClock.uptimeMillis()); 2418 Slog.i(TAG, "Time to scan packages: " 2419 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2420 + " seconds"); 2421 2422 // If the platform SDK has changed since the last time we booted, 2423 // we need to re-grant app permission to catch any new ones that 2424 // appear. This is really a hack, and means that apps can in some 2425 // cases get permissions that the user didn't initially explicitly 2426 // allow... it would be nice to have some better way to handle 2427 // this situation. 2428 int updateFlags = UPDATE_PERMISSIONS_ALL; 2429 if (ver.sdkVersion != mSdkVersion) { 2430 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2431 + mSdkVersion + "; regranting permissions for internal storage"); 2432 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2433 } 2434 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2435 ver.sdkVersion = mSdkVersion; 2436 2437 // If this is the first boot or an update from pre-M, and it is a normal 2438 // boot, then we need to initialize the default preferred apps across 2439 // all defined users. 2440 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2441 for (UserInfo user : sUserManager.getUsers(true)) { 2442 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2443 applyFactoryDefaultBrowserLPw(user.id); 2444 primeDomainVerificationsLPw(user.id); 2445 } 2446 } 2447 2448 // Prepare storage for system user really early during boot, 2449 // since core system apps like SettingsProvider and SystemUI 2450 // can't wait for user to start 2451 final int storageFlags; 2452 if (StorageManager.isFileBasedEncryptionEnabled()) { 2453 storageFlags = StorageManager.FLAG_STORAGE_DE; 2454 } else { 2455 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2456 } 2457 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2458 storageFlags); 2459 2460 // If this is first boot after an OTA, and a normal boot, then 2461 // we need to clear code cache directories. 2462 if (mIsUpgrade && !onlyCore) { 2463 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2464 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2465 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2466 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2467 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2468 } 2469 } 2470 ver.fingerprint = Build.FINGERPRINT; 2471 } 2472 2473 checkDefaultBrowser(); 2474 2475 // clear only after permissions and other defaults have been updated 2476 mExistingSystemPackages.clear(); 2477 mPromoteSystemApps = false; 2478 2479 // All the changes are done during package scanning. 2480 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2481 2482 // can downgrade to reader 2483 mSettings.writeLPr(); 2484 2485 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2486 SystemClock.uptimeMillis()); 2487 2488 if (!mOnlyCore) { 2489 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2490 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2491 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2492 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2493 mIntentFilterVerifierComponent); 2494 } else { 2495 mRequiredVerifierPackage = null; 2496 mRequiredInstallerPackage = null; 2497 mIntentFilterVerifierComponent = null; 2498 mIntentFilterVerifier = null; 2499 } 2500 2501 mInstallerService = new PackageInstallerService(context, this); 2502 2503 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2504 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2505 // both the installer and resolver must be present to enable ephemeral 2506 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2507 if (DEBUG_EPHEMERAL) { 2508 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2509 + " installer:" + ephemeralInstallerComponent); 2510 } 2511 mEphemeralResolverComponent = ephemeralResolverComponent; 2512 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2513 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2514 mEphemeralResolverConnection = 2515 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2516 } else { 2517 if (DEBUG_EPHEMERAL) { 2518 final String missingComponent = 2519 (ephemeralResolverComponent == null) 2520 ? (ephemeralInstallerComponent == null) 2521 ? "resolver and installer" 2522 : "resolver" 2523 : "installer"; 2524 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2525 } 2526 mEphemeralResolverComponent = null; 2527 mEphemeralInstallerComponent = null; 2528 mEphemeralResolverConnection = null; 2529 } 2530 2531 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2532 } // synchronized (mPackages) 2533 } // synchronized (mInstallLock) 2534 2535 // Now after opening every single application zip, make sure they 2536 // are all flushed. Not really needed, but keeps things nice and 2537 // tidy. 2538 Runtime.getRuntime().gc(); 2539 2540 // The initial scanning above does many calls into installd while 2541 // holding the mPackages lock, but we're mostly interested in yelling 2542 // once we have a booted system. 2543 mInstaller.setWarnIfHeld(mPackages); 2544 2545 // Expose private service for system components to use. 2546 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2547 } 2548 2549 @Override 2550 public boolean isFirstBoot() { 2551 return !mRestoredSettings; 2552 } 2553 2554 @Override 2555 public boolean isOnlyCoreApps() { 2556 return mOnlyCore; 2557 } 2558 2559 @Override 2560 public boolean isUpgrade() { 2561 return mIsUpgrade; 2562 } 2563 2564 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2565 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2566 2567 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2568 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2569 if (matches.size() == 1) { 2570 return matches.get(0).getComponentInfo().packageName; 2571 } else { 2572 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2573 return null; 2574 } 2575 } 2576 2577 private @NonNull String getRequiredInstallerLPr() { 2578 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2579 intent.addCategory(Intent.CATEGORY_DEFAULT); 2580 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2581 2582 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2583 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2584 if (matches.size() == 1) { 2585 return matches.get(0).getComponentInfo().packageName; 2586 } else { 2587 throw new RuntimeException("There must be exactly one installer; found " + matches); 2588 } 2589 } 2590 2591 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2592 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2593 2594 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2595 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2596 ResolveInfo best = null; 2597 final int N = matches.size(); 2598 for (int i = 0; i < N; i++) { 2599 final ResolveInfo cur = matches.get(i); 2600 final String packageName = cur.getComponentInfo().packageName; 2601 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2602 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2603 continue; 2604 } 2605 2606 if (best == null || cur.priority > best.priority) { 2607 best = cur; 2608 } 2609 } 2610 2611 if (best != null) { 2612 return best.getComponentInfo().getComponentName(); 2613 } else { 2614 throw new RuntimeException("There must be at least one intent filter verifier"); 2615 } 2616 } 2617 2618 private @Nullable ComponentName getEphemeralResolverLPr() { 2619 final String[] packageArray = 2620 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2621 if (packageArray.length == 0) { 2622 if (DEBUG_EPHEMERAL) { 2623 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2624 } 2625 return null; 2626 } 2627 2628 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2629 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2630 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2631 2632 final int N = resolvers.size(); 2633 if (N == 0) { 2634 if (DEBUG_EPHEMERAL) { 2635 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2636 } 2637 return null; 2638 } 2639 2640 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2641 for (int i = 0; i < N; i++) { 2642 final ResolveInfo info = resolvers.get(i); 2643 2644 if (info.serviceInfo == null) { 2645 continue; 2646 } 2647 2648 final String packageName = info.serviceInfo.packageName; 2649 if (!possiblePackages.contains(packageName)) { 2650 if (DEBUG_EPHEMERAL) { 2651 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2652 + " pkg: " + packageName + ", info:" + info); 2653 } 2654 continue; 2655 } 2656 2657 if (DEBUG_EPHEMERAL) { 2658 Slog.v(TAG, "Ephemeral resolver found;" 2659 + " pkg: " + packageName + ", info:" + info); 2660 } 2661 return new ComponentName(packageName, info.serviceInfo.name); 2662 } 2663 if (DEBUG_EPHEMERAL) { 2664 Slog.v(TAG, "Ephemeral resolver NOT found"); 2665 } 2666 return null; 2667 } 2668 2669 private @Nullable ComponentName getEphemeralInstallerLPr() { 2670 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2671 intent.addCategory(Intent.CATEGORY_DEFAULT); 2672 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2673 2674 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2675 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2676 if (matches.size() == 0) { 2677 return null; 2678 } else if (matches.size() == 1) { 2679 return matches.get(0).getComponentInfo().getComponentName(); 2680 } else { 2681 throw new RuntimeException( 2682 "There must be at most one ephemeral installer; found " + matches); 2683 } 2684 } 2685 2686 private void primeDomainVerificationsLPw(int userId) { 2687 if (DEBUG_DOMAIN_VERIFICATION) { 2688 Slog.d(TAG, "Priming domain verifications in user " + userId); 2689 } 2690 2691 SystemConfig systemConfig = SystemConfig.getInstance(); 2692 ArraySet<String> packages = systemConfig.getLinkedApps(); 2693 ArraySet<String> domains = new ArraySet<String>(); 2694 2695 for (String packageName : packages) { 2696 PackageParser.Package pkg = mPackages.get(packageName); 2697 if (pkg != null) { 2698 if (!pkg.isSystemApp()) { 2699 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2700 continue; 2701 } 2702 2703 domains.clear(); 2704 for (PackageParser.Activity a : pkg.activities) { 2705 for (ActivityIntentInfo filter : a.intents) { 2706 if (hasValidDomains(filter)) { 2707 domains.addAll(filter.getHostsList()); 2708 } 2709 } 2710 } 2711 2712 if (domains.size() > 0) { 2713 if (DEBUG_DOMAIN_VERIFICATION) { 2714 Slog.v(TAG, " + " + packageName); 2715 } 2716 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2717 // state w.r.t. the formal app-linkage "no verification attempted" state; 2718 // and then 'always' in the per-user state actually used for intent resolution. 2719 final IntentFilterVerificationInfo ivi; 2720 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2721 new ArrayList<String>(domains)); 2722 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2723 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2724 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2725 } else { 2726 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2727 + "' does not handle web links"); 2728 } 2729 } else { 2730 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2731 } 2732 } 2733 2734 scheduleWritePackageRestrictionsLocked(userId); 2735 scheduleWriteSettingsLocked(); 2736 } 2737 2738 private void applyFactoryDefaultBrowserLPw(int userId) { 2739 // The default browser app's package name is stored in a string resource, 2740 // with a product-specific overlay used for vendor customization. 2741 String browserPkg = mContext.getResources().getString( 2742 com.android.internal.R.string.default_browser); 2743 if (!TextUtils.isEmpty(browserPkg)) { 2744 // non-empty string => required to be a known package 2745 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2746 if (ps == null) { 2747 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2748 browserPkg = null; 2749 } else { 2750 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2751 } 2752 } 2753 2754 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2755 // default. If there's more than one, just leave everything alone. 2756 if (browserPkg == null) { 2757 calculateDefaultBrowserLPw(userId); 2758 } 2759 } 2760 2761 private void calculateDefaultBrowserLPw(int userId) { 2762 List<String> allBrowsers = resolveAllBrowserApps(userId); 2763 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2764 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2765 } 2766 2767 private List<String> resolveAllBrowserApps(int userId) { 2768 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2769 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2770 PackageManager.MATCH_ALL, userId); 2771 2772 final int count = list.size(); 2773 List<String> result = new ArrayList<String>(count); 2774 for (int i=0; i<count; i++) { 2775 ResolveInfo info = list.get(i); 2776 if (info.activityInfo == null 2777 || !info.handleAllWebDataURI 2778 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2779 || result.contains(info.activityInfo.packageName)) { 2780 continue; 2781 } 2782 result.add(info.activityInfo.packageName); 2783 } 2784 2785 return result; 2786 } 2787 2788 private boolean packageIsBrowser(String packageName, int userId) { 2789 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2790 PackageManager.MATCH_ALL, userId); 2791 final int N = list.size(); 2792 for (int i = 0; i < N; i++) { 2793 ResolveInfo info = list.get(i); 2794 if (packageName.equals(info.activityInfo.packageName)) { 2795 return true; 2796 } 2797 } 2798 return false; 2799 } 2800 2801 private void checkDefaultBrowser() { 2802 final int myUserId = UserHandle.myUserId(); 2803 final String packageName = getDefaultBrowserPackageName(myUserId); 2804 if (packageName != null) { 2805 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2806 if (info == null) { 2807 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2808 synchronized (mPackages) { 2809 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2810 } 2811 } 2812 } 2813 } 2814 2815 @Override 2816 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2817 throws RemoteException { 2818 try { 2819 return super.onTransact(code, data, reply, flags); 2820 } catch (RuntimeException e) { 2821 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2822 Slog.wtf(TAG, "Package Manager Crash", e); 2823 } 2824 throw e; 2825 } 2826 } 2827 2828 void cleanupInstallFailedPackage(PackageSetting ps) { 2829 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2830 2831 removeDataDirsLI(ps.volumeUuid, ps.name); 2832 if (ps.codePath != null) { 2833 removeCodePathLI(ps.codePath); 2834 } 2835 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2836 if (ps.resourcePath.isDirectory()) { 2837 FileUtils.deleteContents(ps.resourcePath); 2838 } 2839 ps.resourcePath.delete(); 2840 } 2841 mSettings.removePackageLPw(ps.name); 2842 } 2843 2844 static int[] appendInts(int[] cur, int[] add) { 2845 if (add == null) return cur; 2846 if (cur == null) return add; 2847 final int N = add.length; 2848 for (int i=0; i<N; i++) { 2849 cur = appendInt(cur, add[i]); 2850 } 2851 return cur; 2852 } 2853 2854 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2855 if (!sUserManager.exists(userId)) return null; 2856 final PackageSetting ps = (PackageSetting) p.mExtras; 2857 if (ps == null) { 2858 return null; 2859 } 2860 2861 final PermissionsState permissionsState = ps.getPermissionsState(); 2862 2863 final int[] gids = permissionsState.computeGids(userId); 2864 final Set<String> permissions = permissionsState.getPermissions(userId); 2865 final PackageUserState state = ps.readUserState(userId); 2866 2867 return PackageParser.generatePackageInfo(p, gids, flags, 2868 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2869 } 2870 2871 @Override 2872 public void checkPackageStartable(String packageName, int userId) { 2873 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2874 2875 synchronized (mPackages) { 2876 final PackageSetting ps = mSettings.mPackages.get(packageName); 2877 if (ps == null) { 2878 throw new SecurityException("Package " + packageName + " was not found!"); 2879 } 2880 2881 if (mSafeMode && !ps.isSystem()) { 2882 throw new SecurityException("Package " + packageName + " not a system app!"); 2883 } 2884 2885 if (ps.frozen) { 2886 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2887 } 2888 2889 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2890 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2891 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2892 } 2893 } 2894 } 2895 2896 @Override 2897 public boolean isPackageAvailable(String packageName, int userId) { 2898 if (!sUserManager.exists(userId)) return false; 2899 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2900 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2901 synchronized (mPackages) { 2902 PackageParser.Package p = mPackages.get(packageName); 2903 if (p != null) { 2904 final PackageSetting ps = (PackageSetting) p.mExtras; 2905 if (ps != null) { 2906 final PackageUserState state = ps.readUserState(userId); 2907 if (state != null) { 2908 return PackageParser.isAvailable(state); 2909 } 2910 } 2911 } 2912 } 2913 return false; 2914 } 2915 2916 @Override 2917 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2918 if (!sUserManager.exists(userId)) return null; 2919 flags = updateFlagsForPackage(flags, userId, packageName); 2920 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2921 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2922 // reader 2923 synchronized (mPackages) { 2924 PackageParser.Package p = mPackages.get(packageName); 2925 if (DEBUG_PACKAGE_INFO) 2926 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2927 if (p != null) { 2928 return generatePackageInfo(p, flags, userId); 2929 } 2930 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2931 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2932 } 2933 } 2934 return null; 2935 } 2936 2937 @Override 2938 public String[] currentToCanonicalPackageNames(String[] names) { 2939 String[] out = new String[names.length]; 2940 // reader 2941 synchronized (mPackages) { 2942 for (int i=names.length-1; i>=0; i--) { 2943 PackageSetting ps = mSettings.mPackages.get(names[i]); 2944 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2945 } 2946 } 2947 return out; 2948 } 2949 2950 @Override 2951 public String[] canonicalToCurrentPackageNames(String[] names) { 2952 String[] out = new String[names.length]; 2953 // reader 2954 synchronized (mPackages) { 2955 for (int i=names.length-1; i>=0; i--) { 2956 String cur = mSettings.mRenamedPackages.get(names[i]); 2957 out[i] = cur != null ? cur : names[i]; 2958 } 2959 } 2960 return out; 2961 } 2962 2963 @Override 2964 public int getPackageUid(String packageName, int flags, int userId) { 2965 if (!sUserManager.exists(userId)) return -1; 2966 flags = updateFlagsForPackage(flags, userId, packageName); 2967 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2968 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2969 2970 // reader 2971 synchronized (mPackages) { 2972 final PackageParser.Package p = mPackages.get(packageName); 2973 if (p != null && p.isMatch(flags)) { 2974 return UserHandle.getUid(userId, p.applicationInfo.uid); 2975 } 2976 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2977 final PackageSetting ps = mSettings.mPackages.get(packageName); 2978 if (ps != null && ps.isMatch(flags)) { 2979 return UserHandle.getUid(userId, ps.appId); 2980 } 2981 } 2982 } 2983 2984 return -1; 2985 } 2986 2987 @Override 2988 public int[] getPackageGids(String packageName, int flags, int userId) { 2989 if (!sUserManager.exists(userId)) return null; 2990 flags = updateFlagsForPackage(flags, userId, packageName); 2991 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2992 false /* requireFullPermission */, false /* checkShell */, 2993 "getPackageGids"); 2994 2995 // reader 2996 synchronized (mPackages) { 2997 final PackageParser.Package p = mPackages.get(packageName); 2998 if (p != null && p.isMatch(flags)) { 2999 PackageSetting ps = (PackageSetting) p.mExtras; 3000 return ps.getPermissionsState().computeGids(userId); 3001 } 3002 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3003 final PackageSetting ps = mSettings.mPackages.get(packageName); 3004 if (ps != null && ps.isMatch(flags)) { 3005 return ps.getPermissionsState().computeGids(userId); 3006 } 3007 } 3008 } 3009 3010 return null; 3011 } 3012 3013 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3014 if (bp.perm != null) { 3015 return PackageParser.generatePermissionInfo(bp.perm, flags); 3016 } 3017 PermissionInfo pi = new PermissionInfo(); 3018 pi.name = bp.name; 3019 pi.packageName = bp.sourcePackage; 3020 pi.nonLocalizedLabel = bp.name; 3021 pi.protectionLevel = bp.protectionLevel; 3022 return pi; 3023 } 3024 3025 @Override 3026 public PermissionInfo getPermissionInfo(String name, int flags) { 3027 // reader 3028 synchronized (mPackages) { 3029 final BasePermission p = mSettings.mPermissions.get(name); 3030 if (p != null) { 3031 return generatePermissionInfo(p, flags); 3032 } 3033 return null; 3034 } 3035 } 3036 3037 @Override 3038 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3039 int flags) { 3040 // reader 3041 synchronized (mPackages) { 3042 if (group != null && !mPermissionGroups.containsKey(group)) { 3043 // This is thrown as NameNotFoundException 3044 return null; 3045 } 3046 3047 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3048 for (BasePermission p : mSettings.mPermissions.values()) { 3049 if (group == null) { 3050 if (p.perm == null || p.perm.info.group == null) { 3051 out.add(generatePermissionInfo(p, flags)); 3052 } 3053 } else { 3054 if (p.perm != null && group.equals(p.perm.info.group)) { 3055 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3056 } 3057 } 3058 } 3059 return new ParceledListSlice<>(out); 3060 } 3061 } 3062 3063 @Override 3064 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3065 // reader 3066 synchronized (mPackages) { 3067 return PackageParser.generatePermissionGroupInfo( 3068 mPermissionGroups.get(name), flags); 3069 } 3070 } 3071 3072 @Override 3073 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3074 // reader 3075 synchronized (mPackages) { 3076 final int N = mPermissionGroups.size(); 3077 ArrayList<PermissionGroupInfo> out 3078 = new ArrayList<PermissionGroupInfo>(N); 3079 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3080 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3081 } 3082 return new ParceledListSlice<>(out); 3083 } 3084 } 3085 3086 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3087 int userId) { 3088 if (!sUserManager.exists(userId)) return null; 3089 PackageSetting ps = mSettings.mPackages.get(packageName); 3090 if (ps != null) { 3091 if (ps.pkg == null) { 3092 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3093 flags, userId); 3094 if (pInfo != null) { 3095 return pInfo.applicationInfo; 3096 } 3097 return null; 3098 } 3099 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3100 ps.readUserState(userId), userId); 3101 } 3102 return null; 3103 } 3104 3105 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3106 int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 PackageSetting ps = mSettings.mPackages.get(packageName); 3109 if (ps != null) { 3110 PackageParser.Package pkg = ps.pkg; 3111 if (pkg == null) { 3112 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3113 return null; 3114 } 3115 // Only data remains, so we aren't worried about code paths 3116 pkg = new PackageParser.Package(packageName); 3117 pkg.applicationInfo.packageName = packageName; 3118 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3119 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3120 pkg.applicationInfo.uid = ps.appId; 3121 pkg.applicationInfo.initForUser(userId); 3122 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3123 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3124 } 3125 return generatePackageInfo(pkg, flags, userId); 3126 } 3127 return null; 3128 } 3129 3130 @Override 3131 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3132 if (!sUserManager.exists(userId)) return null; 3133 flags = updateFlagsForApplication(flags, userId, packageName); 3134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3135 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3136 // writer 3137 synchronized (mPackages) { 3138 PackageParser.Package p = mPackages.get(packageName); 3139 if (DEBUG_PACKAGE_INFO) Log.v( 3140 TAG, "getApplicationInfo " + packageName 3141 + ": " + p); 3142 if (p != null) { 3143 PackageSetting ps = mSettings.mPackages.get(packageName); 3144 if (ps == null) return null; 3145 // Note: isEnabledLP() does not apply here - always return info 3146 return PackageParser.generateApplicationInfo( 3147 p, flags, ps.readUserState(userId), userId); 3148 } 3149 if ("android".equals(packageName)||"system".equals(packageName)) { 3150 return mAndroidApplication; 3151 } 3152 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3153 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3154 } 3155 } 3156 return null; 3157 } 3158 3159 @Override 3160 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3161 final IPackageDataObserver observer) { 3162 mContext.enforceCallingOrSelfPermission( 3163 android.Manifest.permission.CLEAR_APP_CACHE, null); 3164 // Queue up an async operation since clearing cache may take a little while. 3165 mHandler.post(new Runnable() { 3166 public void run() { 3167 mHandler.removeCallbacks(this); 3168 boolean success = true; 3169 synchronized (mInstallLock) { 3170 try { 3171 mInstaller.freeCache(volumeUuid, freeStorageSize); 3172 } catch (InstallerException e) { 3173 Slog.w(TAG, "Couldn't clear application caches: " + e); 3174 success = false; 3175 } 3176 } 3177 if (observer != null) { 3178 try { 3179 observer.onRemoveCompleted(null, success); 3180 } catch (RemoteException e) { 3181 Slog.w(TAG, "RemoveException when invoking call back"); 3182 } 3183 } 3184 } 3185 }); 3186 } 3187 3188 @Override 3189 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3190 final IntentSender pi) { 3191 mContext.enforceCallingOrSelfPermission( 3192 android.Manifest.permission.CLEAR_APP_CACHE, null); 3193 // Queue up an async operation since clearing cache may take a little while. 3194 mHandler.post(new Runnable() { 3195 public void run() { 3196 mHandler.removeCallbacks(this); 3197 boolean success = true; 3198 synchronized (mInstallLock) { 3199 try { 3200 mInstaller.freeCache(volumeUuid, freeStorageSize); 3201 } catch (InstallerException e) { 3202 Slog.w(TAG, "Couldn't clear application caches: " + e); 3203 success = false; 3204 } 3205 } 3206 if(pi != null) { 3207 try { 3208 // Callback via pending intent 3209 int code = success ? 1 : 0; 3210 pi.sendIntent(null, code, null, 3211 null, null); 3212 } catch (SendIntentException e1) { 3213 Slog.i(TAG, "Failed to send pending intent"); 3214 } 3215 } 3216 } 3217 }); 3218 } 3219 3220 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3221 synchronized (mInstallLock) { 3222 try { 3223 mInstaller.freeCache(volumeUuid, freeStorageSize); 3224 } catch (InstallerException e) { 3225 throw new IOException("Failed to free enough space", e); 3226 } 3227 } 3228 } 3229 3230 /** 3231 * Return if the user key is currently unlocked. 3232 */ 3233 private boolean isUserKeyUnlocked(int userId) { 3234 if (StorageManager.isFileBasedEncryptionEnabled()) { 3235 final IMountService mount = IMountService.Stub 3236 .asInterface(ServiceManager.getService("mount")); 3237 if (mount == null) { 3238 Slog.w(TAG, "Early during boot, assuming locked"); 3239 return false; 3240 } 3241 final long token = Binder.clearCallingIdentity(); 3242 try { 3243 return mount.isUserKeyUnlocked(userId); 3244 } catch (RemoteException e) { 3245 throw e.rethrowAsRuntimeException(); 3246 } finally { 3247 Binder.restoreCallingIdentity(token); 3248 } 3249 } else { 3250 return true; 3251 } 3252 } 3253 3254 /** 3255 * Update given flags based on encryption status of current user. 3256 */ 3257 private int updateFlags(int flags, int userId) { 3258 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3259 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3260 // Caller expressed an explicit opinion about what encryption 3261 // aware/unaware components they want to see, so fall through and 3262 // give them what they want 3263 } else { 3264 // Caller expressed no opinion, so match based on user state 3265 if (isUserKeyUnlocked(userId)) { 3266 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3267 } else { 3268 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3269 } 3270 } 3271 return flags; 3272 } 3273 3274 /** 3275 * Update given flags when being used to request {@link PackageInfo}. 3276 */ 3277 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3278 boolean triaged = true; 3279 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3280 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3281 // Caller is asking for component details, so they'd better be 3282 // asking for specific encryption matching behavior, or be triaged 3283 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3284 | PackageManager.MATCH_ENCRYPTION_AWARE 3285 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3286 triaged = false; 3287 } 3288 } 3289 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3290 | PackageManager.MATCH_SYSTEM_ONLY 3291 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3292 triaged = false; 3293 } 3294 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3295 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3296 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3297 } 3298 return updateFlags(flags, userId); 3299 } 3300 3301 /** 3302 * Update given flags when being used to request {@link ApplicationInfo}. 3303 */ 3304 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3305 return updateFlagsForPackage(flags, userId, cookie); 3306 } 3307 3308 /** 3309 * Update given flags when being used to request {@link ComponentInfo}. 3310 */ 3311 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3312 if (cookie instanceof Intent) { 3313 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3314 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3315 } 3316 } 3317 3318 boolean triaged = true; 3319 // Caller is asking for component details, so they'd better be 3320 // asking for specific encryption matching behavior, or be triaged 3321 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3322 | PackageManager.MATCH_ENCRYPTION_AWARE 3323 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3324 triaged = false; 3325 } 3326 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3327 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3328 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3329 } 3330 3331 return updateFlags(flags, userId); 3332 } 3333 3334 /** 3335 * Update given flags when being used to request {@link ResolveInfo}. 3336 */ 3337 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3338 // Safe mode means we shouldn't match any third-party components 3339 if (mSafeMode) { 3340 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3341 } 3342 3343 return updateFlagsForComponent(flags, userId, cookie); 3344 } 3345 3346 @Override 3347 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForComponent(flags, userId, component); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3351 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3352 synchronized (mPackages) { 3353 PackageParser.Activity a = mActivities.mActivities.get(component); 3354 3355 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3356 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3357 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3358 if (ps == null) return null; 3359 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3360 userId); 3361 } 3362 if (mResolveComponentName.equals(component)) { 3363 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3364 new PackageUserState(), userId); 3365 } 3366 } 3367 return null; 3368 } 3369 3370 @Override 3371 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3372 String resolvedType) { 3373 synchronized (mPackages) { 3374 if (component.equals(mResolveComponentName)) { 3375 // The resolver supports EVERYTHING! 3376 return true; 3377 } 3378 PackageParser.Activity a = mActivities.mActivities.get(component); 3379 if (a == null) { 3380 return false; 3381 } 3382 for (int i=0; i<a.intents.size(); i++) { 3383 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3384 intent.getData(), intent.getCategories(), TAG) >= 0) { 3385 return true; 3386 } 3387 } 3388 return false; 3389 } 3390 } 3391 3392 @Override 3393 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3394 if (!sUserManager.exists(userId)) return null; 3395 flags = updateFlagsForComponent(flags, userId, component); 3396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3397 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3398 synchronized (mPackages) { 3399 PackageParser.Activity a = mReceivers.mActivities.get(component); 3400 if (DEBUG_PACKAGE_INFO) Log.v( 3401 TAG, "getReceiverInfo " + component + ": " + a); 3402 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3403 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3404 if (ps == null) return null; 3405 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3406 userId); 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3414 if (!sUserManager.exists(userId)) return null; 3415 flags = updateFlagsForComponent(flags, userId, component); 3416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3417 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3418 synchronized (mPackages) { 3419 PackageParser.Service s = mServices.mServices.get(component); 3420 if (DEBUG_PACKAGE_INFO) Log.v( 3421 TAG, "getServiceInfo " + component + ": " + s); 3422 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3423 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3424 if (ps == null) return null; 3425 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3426 userId); 3427 } 3428 } 3429 return null; 3430 } 3431 3432 @Override 3433 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3434 if (!sUserManager.exists(userId)) return null; 3435 flags = updateFlagsForComponent(flags, userId, component); 3436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3437 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3438 synchronized (mPackages) { 3439 PackageParser.Provider p = mProviders.mProviders.get(component); 3440 if (DEBUG_PACKAGE_INFO) Log.v( 3441 TAG, "getProviderInfo " + component + ": " + p); 3442 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3443 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3444 if (ps == null) return null; 3445 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3446 userId); 3447 } 3448 } 3449 return null; 3450 } 3451 3452 @Override 3453 public String[] getSystemSharedLibraryNames() { 3454 Set<String> libSet; 3455 synchronized (mPackages) { 3456 libSet = mSharedLibraries.keySet(); 3457 int size = libSet.size(); 3458 if (size > 0) { 3459 String[] libs = new String[size]; 3460 libSet.toArray(libs); 3461 return libs; 3462 } 3463 } 3464 return null; 3465 } 3466 3467 @Override 3468 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3469 synchronized (mPackages) { 3470 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3471 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3472 if (libraryEntry != null) { 3473 return libraryEntry.apk; 3474 } 3475 } 3476 return null; 3477 } 3478 3479 @Override 3480 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3481 synchronized (mPackages) { 3482 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3483 3484 final FeatureInfo fi = new FeatureInfo(); 3485 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3486 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3487 res.add(fi); 3488 3489 return new ParceledListSlice<>(res); 3490 } 3491 } 3492 3493 @Override 3494 public boolean hasSystemFeature(String name, int version) { 3495 synchronized (mPackages) { 3496 final FeatureInfo feat = mAvailableFeatures.get(name); 3497 if (feat == null) { 3498 return false; 3499 } else { 3500 return feat.version >= version; 3501 } 3502 } 3503 } 3504 3505 @Override 3506 public int checkPermission(String permName, String pkgName, int userId) { 3507 if (!sUserManager.exists(userId)) { 3508 return PackageManager.PERMISSION_DENIED; 3509 } 3510 3511 synchronized (mPackages) { 3512 final PackageParser.Package p = mPackages.get(pkgName); 3513 if (p != null && p.mExtras != null) { 3514 final PackageSetting ps = (PackageSetting) p.mExtras; 3515 final PermissionsState permissionsState = ps.getPermissionsState(); 3516 if (permissionsState.hasPermission(permName, userId)) { 3517 return PackageManager.PERMISSION_GRANTED; 3518 } 3519 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3520 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3521 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3522 return PackageManager.PERMISSION_GRANTED; 3523 } 3524 } 3525 } 3526 3527 return PackageManager.PERMISSION_DENIED; 3528 } 3529 3530 @Override 3531 public int checkUidPermission(String permName, int uid) { 3532 final int userId = UserHandle.getUserId(uid); 3533 3534 if (!sUserManager.exists(userId)) { 3535 return PackageManager.PERMISSION_DENIED; 3536 } 3537 3538 synchronized (mPackages) { 3539 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3540 if (obj != null) { 3541 final SettingBase ps = (SettingBase) obj; 3542 final PermissionsState permissionsState = ps.getPermissionsState(); 3543 if (permissionsState.hasPermission(permName, userId)) { 3544 return PackageManager.PERMISSION_GRANTED; 3545 } 3546 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3547 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3548 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3549 return PackageManager.PERMISSION_GRANTED; 3550 } 3551 } else { 3552 ArraySet<String> perms = mSystemPermissions.get(uid); 3553 if (perms != null) { 3554 if (perms.contains(permName)) { 3555 return PackageManager.PERMISSION_GRANTED; 3556 } 3557 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3558 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3559 return PackageManager.PERMISSION_GRANTED; 3560 } 3561 } 3562 } 3563 } 3564 3565 return PackageManager.PERMISSION_DENIED; 3566 } 3567 3568 @Override 3569 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3570 if (UserHandle.getCallingUserId() != userId) { 3571 mContext.enforceCallingPermission( 3572 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3573 "isPermissionRevokedByPolicy for user " + userId); 3574 } 3575 3576 if (checkPermission(permission, packageName, userId) 3577 == PackageManager.PERMISSION_GRANTED) { 3578 return false; 3579 } 3580 3581 final long identity = Binder.clearCallingIdentity(); 3582 try { 3583 final int flags = getPermissionFlags(permission, packageName, userId); 3584 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3585 } finally { 3586 Binder.restoreCallingIdentity(identity); 3587 } 3588 } 3589 3590 @Override 3591 public String getPermissionControllerPackageName() { 3592 synchronized (mPackages) { 3593 return mRequiredInstallerPackage; 3594 } 3595 } 3596 3597 /** 3598 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3599 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3600 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3601 * @param message the message to log on security exception 3602 */ 3603 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3604 boolean checkShell, String message) { 3605 if (userId < 0) { 3606 throw new IllegalArgumentException("Invalid userId " + userId); 3607 } 3608 if (checkShell) { 3609 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3610 } 3611 if (userId == UserHandle.getUserId(callingUid)) return; 3612 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3613 if (requireFullPermission) { 3614 mContext.enforceCallingOrSelfPermission( 3615 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3616 } else { 3617 try { 3618 mContext.enforceCallingOrSelfPermission( 3619 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3620 } catch (SecurityException se) { 3621 mContext.enforceCallingOrSelfPermission( 3622 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3623 } 3624 } 3625 } 3626 } 3627 3628 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3629 if (callingUid == Process.SHELL_UID) { 3630 if (userHandle >= 0 3631 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3632 throw new SecurityException("Shell does not have permission to access user " 3633 + userHandle); 3634 } else if (userHandle < 0) { 3635 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3636 + Debug.getCallers(3)); 3637 } 3638 } 3639 } 3640 3641 private BasePermission findPermissionTreeLP(String permName) { 3642 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3643 if (permName.startsWith(bp.name) && 3644 permName.length() > bp.name.length() && 3645 permName.charAt(bp.name.length()) == '.') { 3646 return bp; 3647 } 3648 } 3649 return null; 3650 } 3651 3652 private BasePermission checkPermissionTreeLP(String permName) { 3653 if (permName != null) { 3654 BasePermission bp = findPermissionTreeLP(permName); 3655 if (bp != null) { 3656 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3657 return bp; 3658 } 3659 throw new SecurityException("Calling uid " 3660 + Binder.getCallingUid() 3661 + " is not allowed to add to permission tree " 3662 + bp.name + " owned by uid " + bp.uid); 3663 } 3664 } 3665 throw new SecurityException("No permission tree found for " + permName); 3666 } 3667 3668 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3669 if (s1 == null) { 3670 return s2 == null; 3671 } 3672 if (s2 == null) { 3673 return false; 3674 } 3675 if (s1.getClass() != s2.getClass()) { 3676 return false; 3677 } 3678 return s1.equals(s2); 3679 } 3680 3681 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3682 if (pi1.icon != pi2.icon) return false; 3683 if (pi1.logo != pi2.logo) return false; 3684 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3685 if (!compareStrings(pi1.name, pi2.name)) return false; 3686 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3687 // We'll take care of setting this one. 3688 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3689 // These are not currently stored in settings. 3690 //if (!compareStrings(pi1.group, pi2.group)) return false; 3691 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3692 //if (pi1.labelRes != pi2.labelRes) return false; 3693 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3694 return true; 3695 } 3696 3697 int permissionInfoFootprint(PermissionInfo info) { 3698 int size = info.name.length(); 3699 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3700 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3701 return size; 3702 } 3703 3704 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3705 int size = 0; 3706 for (BasePermission perm : mSettings.mPermissions.values()) { 3707 if (perm.uid == tree.uid) { 3708 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3709 } 3710 } 3711 return size; 3712 } 3713 3714 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3715 // We calculate the max size of permissions defined by this uid and throw 3716 // if that plus the size of 'info' would exceed our stated maximum. 3717 if (tree.uid != Process.SYSTEM_UID) { 3718 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3719 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3720 throw new SecurityException("Permission tree size cap exceeded"); 3721 } 3722 } 3723 } 3724 3725 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3726 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3727 throw new SecurityException("Label must be specified in permission"); 3728 } 3729 BasePermission tree = checkPermissionTreeLP(info.name); 3730 BasePermission bp = mSettings.mPermissions.get(info.name); 3731 boolean added = bp == null; 3732 boolean changed = true; 3733 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3734 if (added) { 3735 enforcePermissionCapLocked(info, tree); 3736 bp = new BasePermission(info.name, tree.sourcePackage, 3737 BasePermission.TYPE_DYNAMIC); 3738 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3739 throw new SecurityException( 3740 "Not allowed to modify non-dynamic permission " 3741 + info.name); 3742 } else { 3743 if (bp.protectionLevel == fixedLevel 3744 && bp.perm.owner.equals(tree.perm.owner) 3745 && bp.uid == tree.uid 3746 && comparePermissionInfos(bp.perm.info, info)) { 3747 changed = false; 3748 } 3749 } 3750 bp.protectionLevel = fixedLevel; 3751 info = new PermissionInfo(info); 3752 info.protectionLevel = fixedLevel; 3753 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3754 bp.perm.info.packageName = tree.perm.info.packageName; 3755 bp.uid = tree.uid; 3756 if (added) { 3757 mSettings.mPermissions.put(info.name, bp); 3758 } 3759 if (changed) { 3760 if (!async) { 3761 mSettings.writeLPr(); 3762 } else { 3763 scheduleWriteSettingsLocked(); 3764 } 3765 } 3766 return added; 3767 } 3768 3769 @Override 3770 public boolean addPermission(PermissionInfo info) { 3771 synchronized (mPackages) { 3772 return addPermissionLocked(info, false); 3773 } 3774 } 3775 3776 @Override 3777 public boolean addPermissionAsync(PermissionInfo info) { 3778 synchronized (mPackages) { 3779 return addPermissionLocked(info, true); 3780 } 3781 } 3782 3783 @Override 3784 public void removePermission(String name) { 3785 synchronized (mPackages) { 3786 checkPermissionTreeLP(name); 3787 BasePermission bp = mSettings.mPermissions.get(name); 3788 if (bp != null) { 3789 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3790 throw new SecurityException( 3791 "Not allowed to modify non-dynamic permission " 3792 + name); 3793 } 3794 mSettings.mPermissions.remove(name); 3795 mSettings.writeLPr(); 3796 } 3797 } 3798 } 3799 3800 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3801 BasePermission bp) { 3802 int index = pkg.requestedPermissions.indexOf(bp.name); 3803 if (index == -1) { 3804 throw new SecurityException("Package " + pkg.packageName 3805 + " has not requested permission " + bp.name); 3806 } 3807 if (!bp.isRuntime() && !bp.isDevelopment()) { 3808 throw new SecurityException("Permission " + bp.name 3809 + " is not a changeable permission type"); 3810 } 3811 } 3812 3813 @Override 3814 public void grantRuntimePermission(String packageName, String name, final int userId) { 3815 if (!sUserManager.exists(userId)) { 3816 Log.e(TAG, "No such user:" + userId); 3817 return; 3818 } 3819 3820 mContext.enforceCallingOrSelfPermission( 3821 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3822 "grantRuntimePermission"); 3823 3824 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3825 true /* requireFullPermission */, true /* checkShell */, 3826 "grantRuntimePermission"); 3827 3828 final int uid; 3829 final SettingBase sb; 3830 3831 synchronized (mPackages) { 3832 final PackageParser.Package pkg = mPackages.get(packageName); 3833 if (pkg == null) { 3834 throw new IllegalArgumentException("Unknown package: " + packageName); 3835 } 3836 3837 final BasePermission bp = mSettings.mPermissions.get(name); 3838 if (bp == null) { 3839 throw new IllegalArgumentException("Unknown permission: " + name); 3840 } 3841 3842 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3843 3844 // If a permission review is required for legacy apps we represent 3845 // their permissions as always granted runtime ones since we need 3846 // to keep the review required permission flag per user while an 3847 // install permission's state is shared across all users. 3848 if (Build.PERMISSIONS_REVIEW_REQUIRED 3849 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3850 && bp.isRuntime()) { 3851 return; 3852 } 3853 3854 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3855 sb = (SettingBase) pkg.mExtras; 3856 if (sb == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final PermissionsState permissionsState = sb.getPermissionsState(); 3861 3862 final int flags = permissionsState.getPermissionFlags(name, userId); 3863 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3864 throw new SecurityException("Cannot grant system fixed permission " 3865 + name + " for package " + packageName); 3866 } 3867 3868 if (bp.isDevelopment()) { 3869 // Development permissions must be handled specially, since they are not 3870 // normal runtime permissions. For now they apply to all users. 3871 if (permissionsState.grantInstallPermission(bp) != 3872 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3873 scheduleWriteSettingsLocked(); 3874 } 3875 return; 3876 } 3877 3878 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3879 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3880 return; 3881 } 3882 3883 final int result = permissionsState.grantRuntimePermission(bp, userId); 3884 switch (result) { 3885 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3886 return; 3887 } 3888 3889 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3890 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3891 mHandler.post(new Runnable() { 3892 @Override 3893 public void run() { 3894 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3895 } 3896 }); 3897 } 3898 break; 3899 } 3900 3901 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3902 3903 // Not critical if that is lost - app has to request again. 3904 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3905 } 3906 3907 // Only need to do this if user is initialized. Otherwise it's a new user 3908 // and there are no processes running as the user yet and there's no need 3909 // to make an expensive call to remount processes for the changed permissions. 3910 if (READ_EXTERNAL_STORAGE.equals(name) 3911 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3912 final long token = Binder.clearCallingIdentity(); 3913 try { 3914 if (sUserManager.isInitialized(userId)) { 3915 MountServiceInternal mountServiceInternal = LocalServices.getService( 3916 MountServiceInternal.class); 3917 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3918 } 3919 } finally { 3920 Binder.restoreCallingIdentity(token); 3921 } 3922 } 3923 } 3924 3925 @Override 3926 public void revokeRuntimePermission(String packageName, String name, int userId) { 3927 if (!sUserManager.exists(userId)) { 3928 Log.e(TAG, "No such user:" + userId); 3929 return; 3930 } 3931 3932 mContext.enforceCallingOrSelfPermission( 3933 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3934 "revokeRuntimePermission"); 3935 3936 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3937 true /* requireFullPermission */, true /* checkShell */, 3938 "revokeRuntimePermission"); 3939 3940 final int appId; 3941 3942 synchronized (mPackages) { 3943 final PackageParser.Package pkg = mPackages.get(packageName); 3944 if (pkg == null) { 3945 throw new IllegalArgumentException("Unknown package: " + packageName); 3946 } 3947 3948 final BasePermission bp = mSettings.mPermissions.get(name); 3949 if (bp == null) { 3950 throw new IllegalArgumentException("Unknown permission: " + name); 3951 } 3952 3953 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3954 3955 // If a permission review is required for legacy apps we represent 3956 // their permissions as always granted runtime ones since we need 3957 // to keep the review required permission flag per user while an 3958 // install permission's state is shared across all users. 3959 if (Build.PERMISSIONS_REVIEW_REQUIRED 3960 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3961 && bp.isRuntime()) { 3962 return; 3963 } 3964 3965 SettingBase sb = (SettingBase) pkg.mExtras; 3966 if (sb == null) { 3967 throw new IllegalArgumentException("Unknown package: " + packageName); 3968 } 3969 3970 final PermissionsState permissionsState = sb.getPermissionsState(); 3971 3972 final int flags = permissionsState.getPermissionFlags(name, userId); 3973 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3974 throw new SecurityException("Cannot revoke system fixed permission " 3975 + name + " for package " + packageName); 3976 } 3977 3978 if (bp.isDevelopment()) { 3979 // Development permissions must be handled specially, since they are not 3980 // normal runtime permissions. For now they apply to all users. 3981 if (permissionsState.revokeInstallPermission(bp) != 3982 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3983 scheduleWriteSettingsLocked(); 3984 } 3985 return; 3986 } 3987 3988 if (permissionsState.revokeRuntimePermission(bp, userId) == 3989 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3990 return; 3991 } 3992 3993 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3994 3995 // Critical, after this call app should never have the permission. 3996 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3997 3998 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3999 } 4000 4001 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4002 } 4003 4004 @Override 4005 public void resetRuntimePermissions() { 4006 mContext.enforceCallingOrSelfPermission( 4007 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4008 "revokeRuntimePermission"); 4009 4010 int callingUid = Binder.getCallingUid(); 4011 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4012 mContext.enforceCallingOrSelfPermission( 4013 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4014 "resetRuntimePermissions"); 4015 } 4016 4017 synchronized (mPackages) { 4018 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4019 for (int userId : UserManagerService.getInstance().getUserIds()) { 4020 final int packageCount = mPackages.size(); 4021 for (int i = 0; i < packageCount; i++) { 4022 PackageParser.Package pkg = mPackages.valueAt(i); 4023 if (!(pkg.mExtras instanceof PackageSetting)) { 4024 continue; 4025 } 4026 PackageSetting ps = (PackageSetting) pkg.mExtras; 4027 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4028 } 4029 } 4030 } 4031 } 4032 4033 @Override 4034 public int getPermissionFlags(String name, String packageName, int userId) { 4035 if (!sUserManager.exists(userId)) { 4036 return 0; 4037 } 4038 4039 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4040 4041 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4042 true /* requireFullPermission */, false /* checkShell */, 4043 "getPermissionFlags"); 4044 4045 synchronized (mPackages) { 4046 final PackageParser.Package pkg = mPackages.get(packageName); 4047 if (pkg == null) { 4048 throw new IllegalArgumentException("Unknown package: " + packageName); 4049 } 4050 4051 final BasePermission bp = mSettings.mPermissions.get(name); 4052 if (bp == null) { 4053 throw new IllegalArgumentException("Unknown permission: " + name); 4054 } 4055 4056 SettingBase sb = (SettingBase) pkg.mExtras; 4057 if (sb == null) { 4058 throw new IllegalArgumentException("Unknown package: " + packageName); 4059 } 4060 4061 PermissionsState permissionsState = sb.getPermissionsState(); 4062 return permissionsState.getPermissionFlags(name, userId); 4063 } 4064 } 4065 4066 @Override 4067 public void updatePermissionFlags(String name, String packageName, int flagMask, 4068 int flagValues, int userId) { 4069 if (!sUserManager.exists(userId)) { 4070 return; 4071 } 4072 4073 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4074 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 true /* requireFullPermission */, true /* checkShell */, 4077 "updatePermissionFlags"); 4078 4079 // Only the system can change these flags and nothing else. 4080 if (getCallingUid() != Process.SYSTEM_UID) { 4081 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4082 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4083 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4084 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4085 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4086 } 4087 4088 synchronized (mPackages) { 4089 final PackageParser.Package pkg = mPackages.get(packageName); 4090 if (pkg == null) { 4091 throw new IllegalArgumentException("Unknown package: " + packageName); 4092 } 4093 4094 final BasePermission bp = mSettings.mPermissions.get(name); 4095 if (bp == null) { 4096 throw new IllegalArgumentException("Unknown permission: " + name); 4097 } 4098 4099 SettingBase sb = (SettingBase) pkg.mExtras; 4100 if (sb == null) { 4101 throw new IllegalArgumentException("Unknown package: " + packageName); 4102 } 4103 4104 PermissionsState permissionsState = sb.getPermissionsState(); 4105 4106 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4107 4108 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4109 // Install and runtime permissions are stored in different places, 4110 // so figure out what permission changed and persist the change. 4111 if (permissionsState.getInstallPermissionState(name) != null) { 4112 scheduleWriteSettingsLocked(); 4113 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4114 || hadState) { 4115 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4116 } 4117 } 4118 } 4119 } 4120 4121 /** 4122 * Update the permission flags for all packages and runtime permissions of a user in order 4123 * to allow device or profile owner to remove POLICY_FIXED. 4124 */ 4125 @Override 4126 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4127 if (!sUserManager.exists(userId)) { 4128 return; 4129 } 4130 4131 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4132 4133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4134 true /* requireFullPermission */, true /* checkShell */, 4135 "updatePermissionFlagsForAllApps"); 4136 4137 // Only the system can change system fixed flags. 4138 if (getCallingUid() != Process.SYSTEM_UID) { 4139 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4140 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4141 } 4142 4143 synchronized (mPackages) { 4144 boolean changed = false; 4145 final int packageCount = mPackages.size(); 4146 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4147 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4148 SettingBase sb = (SettingBase) pkg.mExtras; 4149 if (sb == null) { 4150 continue; 4151 } 4152 PermissionsState permissionsState = sb.getPermissionsState(); 4153 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4154 userId, flagMask, flagValues); 4155 } 4156 if (changed) { 4157 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4158 } 4159 } 4160 } 4161 4162 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4163 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4164 != PackageManager.PERMISSION_GRANTED 4165 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4166 != PackageManager.PERMISSION_GRANTED) { 4167 throw new SecurityException(message + " requires " 4168 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4169 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4170 } 4171 } 4172 4173 @Override 4174 public boolean shouldShowRequestPermissionRationale(String permissionName, 4175 String packageName, int userId) { 4176 if (UserHandle.getCallingUserId() != userId) { 4177 mContext.enforceCallingPermission( 4178 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4179 "canShowRequestPermissionRationale for user " + userId); 4180 } 4181 4182 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4183 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4184 return false; 4185 } 4186 4187 if (checkPermission(permissionName, packageName, userId) 4188 == PackageManager.PERMISSION_GRANTED) { 4189 return false; 4190 } 4191 4192 final int flags; 4193 4194 final long identity = Binder.clearCallingIdentity(); 4195 try { 4196 flags = getPermissionFlags(permissionName, 4197 packageName, userId); 4198 } finally { 4199 Binder.restoreCallingIdentity(identity); 4200 } 4201 4202 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4203 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4204 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4205 4206 if ((flags & fixedFlags) != 0) { 4207 return false; 4208 } 4209 4210 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4211 } 4212 4213 @Override 4214 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4215 mContext.enforceCallingOrSelfPermission( 4216 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4217 "addOnPermissionsChangeListener"); 4218 4219 synchronized (mPackages) { 4220 mOnPermissionChangeListeners.addListenerLocked(listener); 4221 } 4222 } 4223 4224 @Override 4225 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4226 synchronized (mPackages) { 4227 mOnPermissionChangeListeners.removeListenerLocked(listener); 4228 } 4229 } 4230 4231 @Override 4232 public boolean isProtectedBroadcast(String actionName) { 4233 synchronized (mPackages) { 4234 if (mProtectedBroadcasts.contains(actionName)) { 4235 return true; 4236 } else if (actionName != null) { 4237 // TODO: remove these terrible hacks 4238 if (actionName.startsWith("android.net.netmon.lingerExpired") 4239 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4240 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4241 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4242 return true; 4243 } 4244 } 4245 } 4246 return false; 4247 } 4248 4249 @Override 4250 public int checkSignatures(String pkg1, String pkg2) { 4251 synchronized (mPackages) { 4252 final PackageParser.Package p1 = mPackages.get(pkg1); 4253 final PackageParser.Package p2 = mPackages.get(pkg2); 4254 if (p1 == null || p1.mExtras == null 4255 || p2 == null || p2.mExtras == null) { 4256 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4257 } 4258 return compareSignatures(p1.mSignatures, p2.mSignatures); 4259 } 4260 } 4261 4262 @Override 4263 public int checkUidSignatures(int uid1, int uid2) { 4264 // Map to base uids. 4265 uid1 = UserHandle.getAppId(uid1); 4266 uid2 = UserHandle.getAppId(uid2); 4267 // reader 4268 synchronized (mPackages) { 4269 Signature[] s1; 4270 Signature[] s2; 4271 Object obj = mSettings.getUserIdLPr(uid1); 4272 if (obj != null) { 4273 if (obj instanceof SharedUserSetting) { 4274 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4275 } else if (obj instanceof PackageSetting) { 4276 s1 = ((PackageSetting)obj).signatures.mSignatures; 4277 } else { 4278 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4279 } 4280 } else { 4281 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4282 } 4283 obj = mSettings.getUserIdLPr(uid2); 4284 if (obj != null) { 4285 if (obj instanceof SharedUserSetting) { 4286 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4287 } else if (obj instanceof PackageSetting) { 4288 s2 = ((PackageSetting)obj).signatures.mSignatures; 4289 } else { 4290 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4291 } 4292 } else { 4293 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4294 } 4295 return compareSignatures(s1, s2); 4296 } 4297 } 4298 4299 private void killUid(int appId, int userId, String reason) { 4300 final long identity = Binder.clearCallingIdentity(); 4301 try { 4302 IActivityManager am = ActivityManagerNative.getDefault(); 4303 if (am != null) { 4304 try { 4305 am.killUid(appId, userId, reason); 4306 } catch (RemoteException e) { 4307 /* ignore - same process */ 4308 } 4309 } 4310 } finally { 4311 Binder.restoreCallingIdentity(identity); 4312 } 4313 } 4314 4315 /** 4316 * Compares two sets of signatures. Returns: 4317 * <br /> 4318 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4319 * <br /> 4320 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4321 * <br /> 4322 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4323 * <br /> 4324 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4325 * <br /> 4326 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4327 */ 4328 static int compareSignatures(Signature[] s1, Signature[] s2) { 4329 if (s1 == null) { 4330 return s2 == null 4331 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4332 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4333 } 4334 4335 if (s2 == null) { 4336 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4337 } 4338 4339 if (s1.length != s2.length) { 4340 return PackageManager.SIGNATURE_NO_MATCH; 4341 } 4342 4343 // Since both signature sets are of size 1, we can compare without HashSets. 4344 if (s1.length == 1) { 4345 return s1[0].equals(s2[0]) ? 4346 PackageManager.SIGNATURE_MATCH : 4347 PackageManager.SIGNATURE_NO_MATCH; 4348 } 4349 4350 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4351 for (Signature sig : s1) { 4352 set1.add(sig); 4353 } 4354 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4355 for (Signature sig : s2) { 4356 set2.add(sig); 4357 } 4358 // Make sure s2 contains all signatures in s1. 4359 if (set1.equals(set2)) { 4360 return PackageManager.SIGNATURE_MATCH; 4361 } 4362 return PackageManager.SIGNATURE_NO_MATCH; 4363 } 4364 4365 /** 4366 * If the database version for this type of package (internal storage or 4367 * external storage) is less than the version where package signatures 4368 * were updated, return true. 4369 */ 4370 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4371 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4372 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4373 } 4374 4375 /** 4376 * Used for backward compatibility to make sure any packages with 4377 * certificate chains get upgraded to the new style. {@code existingSigs} 4378 * will be in the old format (since they were stored on disk from before the 4379 * system upgrade) and {@code scannedSigs} will be in the newer format. 4380 */ 4381 private int compareSignaturesCompat(PackageSignatures existingSigs, 4382 PackageParser.Package scannedPkg) { 4383 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4384 return PackageManager.SIGNATURE_NO_MATCH; 4385 } 4386 4387 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4388 for (Signature sig : existingSigs.mSignatures) { 4389 existingSet.add(sig); 4390 } 4391 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4392 for (Signature sig : scannedPkg.mSignatures) { 4393 try { 4394 Signature[] chainSignatures = sig.getChainSignatures(); 4395 for (Signature chainSig : chainSignatures) { 4396 scannedCompatSet.add(chainSig); 4397 } 4398 } catch (CertificateEncodingException e) { 4399 scannedCompatSet.add(sig); 4400 } 4401 } 4402 /* 4403 * Make sure the expanded scanned set contains all signatures in the 4404 * existing one. 4405 */ 4406 if (scannedCompatSet.equals(existingSet)) { 4407 // Migrate the old signatures to the new scheme. 4408 existingSigs.assignSignatures(scannedPkg.mSignatures); 4409 // The new KeySets will be re-added later in the scanning process. 4410 synchronized (mPackages) { 4411 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4412 } 4413 return PackageManager.SIGNATURE_MATCH; 4414 } 4415 return PackageManager.SIGNATURE_NO_MATCH; 4416 } 4417 4418 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4419 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4420 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4421 } 4422 4423 private int compareSignaturesRecover(PackageSignatures existingSigs, 4424 PackageParser.Package scannedPkg) { 4425 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4426 return PackageManager.SIGNATURE_NO_MATCH; 4427 } 4428 4429 String msg = null; 4430 try { 4431 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4432 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4433 + scannedPkg.packageName); 4434 return PackageManager.SIGNATURE_MATCH; 4435 } 4436 } catch (CertificateException e) { 4437 msg = e.getMessage(); 4438 } 4439 4440 logCriticalInfo(Log.INFO, 4441 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4442 return PackageManager.SIGNATURE_NO_MATCH; 4443 } 4444 4445 @Override 4446 public List<String> getAllPackages() { 4447 synchronized (mPackages) { 4448 return new ArrayList<String>(mPackages.keySet()); 4449 } 4450 } 4451 4452 @Override 4453 public String[] getPackagesForUid(int uid) { 4454 uid = UserHandle.getAppId(uid); 4455 // reader 4456 synchronized (mPackages) { 4457 Object obj = mSettings.getUserIdLPr(uid); 4458 if (obj instanceof SharedUserSetting) { 4459 final SharedUserSetting sus = (SharedUserSetting) obj; 4460 final int N = sus.packages.size(); 4461 final String[] res = new String[N]; 4462 final Iterator<PackageSetting> it = sus.packages.iterator(); 4463 int i = 0; 4464 while (it.hasNext()) { 4465 res[i++] = it.next().name; 4466 } 4467 return res; 4468 } else if (obj instanceof PackageSetting) { 4469 final PackageSetting ps = (PackageSetting) obj; 4470 return new String[] { ps.name }; 4471 } 4472 } 4473 return null; 4474 } 4475 4476 @Override 4477 public String getNameForUid(int uid) { 4478 // reader 4479 synchronized (mPackages) { 4480 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4481 if (obj instanceof SharedUserSetting) { 4482 final SharedUserSetting sus = (SharedUserSetting) obj; 4483 return sus.name + ":" + sus.userId; 4484 } else if (obj instanceof PackageSetting) { 4485 final PackageSetting ps = (PackageSetting) obj; 4486 return ps.name; 4487 } 4488 } 4489 return null; 4490 } 4491 4492 @Override 4493 public int getUidForSharedUser(String sharedUserName) { 4494 if(sharedUserName == null) { 4495 return -1; 4496 } 4497 // reader 4498 synchronized (mPackages) { 4499 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4500 if (suid == null) { 4501 return -1; 4502 } 4503 return suid.userId; 4504 } 4505 } 4506 4507 @Override 4508 public int getFlagsForUid(int uid) { 4509 synchronized (mPackages) { 4510 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4511 if (obj instanceof SharedUserSetting) { 4512 final SharedUserSetting sus = (SharedUserSetting) obj; 4513 return sus.pkgFlags; 4514 } else if (obj instanceof PackageSetting) { 4515 final PackageSetting ps = (PackageSetting) obj; 4516 return ps.pkgFlags; 4517 } 4518 } 4519 return 0; 4520 } 4521 4522 @Override 4523 public int getPrivateFlagsForUid(int uid) { 4524 synchronized (mPackages) { 4525 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4526 if (obj instanceof SharedUserSetting) { 4527 final SharedUserSetting sus = (SharedUserSetting) obj; 4528 return sus.pkgPrivateFlags; 4529 } else if (obj instanceof PackageSetting) { 4530 final PackageSetting ps = (PackageSetting) obj; 4531 return ps.pkgPrivateFlags; 4532 } 4533 } 4534 return 0; 4535 } 4536 4537 @Override 4538 public boolean isUidPrivileged(int uid) { 4539 uid = UserHandle.getAppId(uid); 4540 // reader 4541 synchronized (mPackages) { 4542 Object obj = mSettings.getUserIdLPr(uid); 4543 if (obj instanceof SharedUserSetting) { 4544 final SharedUserSetting sus = (SharedUserSetting) obj; 4545 final Iterator<PackageSetting> it = sus.packages.iterator(); 4546 while (it.hasNext()) { 4547 if (it.next().isPrivileged()) { 4548 return true; 4549 } 4550 } 4551 } else if (obj instanceof PackageSetting) { 4552 final PackageSetting ps = (PackageSetting) obj; 4553 return ps.isPrivileged(); 4554 } 4555 } 4556 return false; 4557 } 4558 4559 @Override 4560 public String[] getAppOpPermissionPackages(String permissionName) { 4561 synchronized (mPackages) { 4562 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4563 if (pkgs == null) { 4564 return null; 4565 } 4566 return pkgs.toArray(new String[pkgs.size()]); 4567 } 4568 } 4569 4570 @Override 4571 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4572 int flags, int userId) { 4573 if (!sUserManager.exists(userId)) return null; 4574 flags = updateFlagsForResolve(flags, userId, intent); 4575 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4576 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4577 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4578 userId); 4579 final ResolveInfo bestChoice = 4580 chooseBestActivity(intent, resolvedType, flags, query, userId); 4581 4582 if (isEphemeralAllowed(intent, query, userId)) { 4583 final EphemeralResolveInfo ai = 4584 getEphemeralResolveInfo(intent, resolvedType, userId); 4585 if (ai != null) { 4586 if (DEBUG_EPHEMERAL) { 4587 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4588 } 4589 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4590 bestChoice.ephemeralResolveInfo = ai; 4591 } 4592 } 4593 return bestChoice; 4594 } 4595 4596 @Override 4597 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4598 IntentFilter filter, int match, ComponentName activity) { 4599 final int userId = UserHandle.getCallingUserId(); 4600 if (DEBUG_PREFERRED) { 4601 Log.v(TAG, "setLastChosenActivity intent=" + intent 4602 + " resolvedType=" + resolvedType 4603 + " flags=" + flags 4604 + " filter=" + filter 4605 + " match=" + match 4606 + " activity=" + activity); 4607 filter.dump(new PrintStreamPrinter(System.out), " "); 4608 } 4609 intent.setComponent(null); 4610 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4611 userId); 4612 // Find any earlier preferred or last chosen entries and nuke them 4613 findPreferredActivity(intent, resolvedType, 4614 flags, query, 0, false, true, false, userId); 4615 // Add the new activity as the last chosen for this filter 4616 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4617 "Setting last chosen"); 4618 } 4619 4620 @Override 4621 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4622 final int userId = UserHandle.getCallingUserId(); 4623 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4624 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4625 userId); 4626 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4627 false, false, false, userId); 4628 } 4629 4630 4631 private boolean isEphemeralAllowed( 4632 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4633 // Short circuit and return early if possible. 4634 if (DISABLE_EPHEMERAL_APPS) { 4635 return false; 4636 } 4637 final int callingUser = UserHandle.getCallingUserId(); 4638 if (callingUser != UserHandle.USER_SYSTEM) { 4639 return false; 4640 } 4641 if (mEphemeralResolverConnection == null) { 4642 return false; 4643 } 4644 if (intent.getComponent() != null) { 4645 return false; 4646 } 4647 if (intent.getPackage() != null) { 4648 return false; 4649 } 4650 final boolean isWebUri = hasWebURI(intent); 4651 if (!isWebUri) { 4652 return false; 4653 } 4654 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4655 synchronized (mPackages) { 4656 final int count = resolvedActivites.size(); 4657 for (int n = 0; n < count; n++) { 4658 ResolveInfo info = resolvedActivites.get(n); 4659 String packageName = info.activityInfo.packageName; 4660 PackageSetting ps = mSettings.mPackages.get(packageName); 4661 if (ps != null) { 4662 // Try to get the status from User settings first 4663 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4664 int status = (int) (packedStatus >> 32); 4665 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4666 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4667 if (DEBUG_EPHEMERAL) { 4668 Slog.v(TAG, "DENY ephemeral apps;" 4669 + " pkg: " + packageName + ", status: " + status); 4670 } 4671 return false; 4672 } 4673 } 4674 } 4675 } 4676 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4677 return true; 4678 } 4679 4680 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4681 int userId) { 4682 MessageDigest digest = null; 4683 try { 4684 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4685 } catch (NoSuchAlgorithmException e) { 4686 // If we can't create a digest, ignore ephemeral apps. 4687 return null; 4688 } 4689 4690 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4691 final byte[] digestBytes = digest.digest(hostBytes); 4692 int shaPrefix = 4693 digestBytes[0] << 24 4694 | digestBytes[1] << 16 4695 | digestBytes[2] << 8 4696 | digestBytes[3] << 0; 4697 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4698 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4699 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4700 // No hash prefix match; there are no ephemeral apps for this domain. 4701 return null; 4702 } 4703 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4704 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4705 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4706 continue; 4707 } 4708 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4709 // No filters; this should never happen. 4710 if (filters.isEmpty()) { 4711 continue; 4712 } 4713 // We have a domain match; resolve the filters to see if anything matches. 4714 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4715 for (int j = filters.size() - 1; j >= 0; --j) { 4716 final EphemeralResolveIntentInfo intentInfo = 4717 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4718 ephemeralResolver.addFilter(intentInfo); 4719 } 4720 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4721 intent, resolvedType, false /*defaultOnly*/, userId); 4722 if (!matchedResolveInfoList.isEmpty()) { 4723 return matchedResolveInfoList.get(0); 4724 } 4725 } 4726 // Hash or filter mis-match; no ephemeral apps for this domain. 4727 return null; 4728 } 4729 4730 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4731 int flags, List<ResolveInfo> query, int userId) { 4732 if (query != null) { 4733 final int N = query.size(); 4734 if (N == 1) { 4735 return query.get(0); 4736 } else if (N > 1) { 4737 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4738 // If there is more than one activity with the same priority, 4739 // then let the user decide between them. 4740 ResolveInfo r0 = query.get(0); 4741 ResolveInfo r1 = query.get(1); 4742 if (DEBUG_INTENT_MATCHING || debug) { 4743 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4744 + r1.activityInfo.name + "=" + r1.priority); 4745 } 4746 // If the first activity has a higher priority, or a different 4747 // default, then it is always desirable to pick it. 4748 if (r0.priority != r1.priority 4749 || r0.preferredOrder != r1.preferredOrder 4750 || r0.isDefault != r1.isDefault) { 4751 return query.get(0); 4752 } 4753 // If we have saved a preference for a preferred activity for 4754 // this Intent, use that. 4755 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4756 flags, query, r0.priority, true, false, debug, userId); 4757 if (ri != null) { 4758 return ri; 4759 } 4760 ri = new ResolveInfo(mResolveInfo); 4761 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4762 ri.activityInfo.applicationInfo = new ApplicationInfo( 4763 ri.activityInfo.applicationInfo); 4764 if (userId != 0) { 4765 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4766 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4767 } 4768 // Make sure that the resolver is displayable in car mode 4769 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4770 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4771 return ri; 4772 } 4773 } 4774 return null; 4775 } 4776 4777 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4778 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4779 final int N = query.size(); 4780 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4781 .get(userId); 4782 // Get the list of persistent preferred activities that handle the intent 4783 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4784 List<PersistentPreferredActivity> pprefs = ppir != null 4785 ? ppir.queryIntent(intent, resolvedType, 4786 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4787 : null; 4788 if (pprefs != null && pprefs.size() > 0) { 4789 final int M = pprefs.size(); 4790 for (int i=0; i<M; i++) { 4791 final PersistentPreferredActivity ppa = pprefs.get(i); 4792 if (DEBUG_PREFERRED || debug) { 4793 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4794 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4795 + "\n component=" + ppa.mComponent); 4796 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4797 } 4798 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4799 flags | MATCH_DISABLED_COMPONENTS, userId); 4800 if (DEBUG_PREFERRED || debug) { 4801 Slog.v(TAG, "Found persistent preferred activity:"); 4802 if (ai != null) { 4803 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4804 } else { 4805 Slog.v(TAG, " null"); 4806 } 4807 } 4808 if (ai == null) { 4809 // This previously registered persistent preferred activity 4810 // component is no longer known. Ignore it and do NOT remove it. 4811 continue; 4812 } 4813 for (int j=0; j<N; j++) { 4814 final ResolveInfo ri = query.get(j); 4815 if (!ri.activityInfo.applicationInfo.packageName 4816 .equals(ai.applicationInfo.packageName)) { 4817 continue; 4818 } 4819 if (!ri.activityInfo.name.equals(ai.name)) { 4820 continue; 4821 } 4822 // Found a persistent preference that can handle the intent. 4823 if (DEBUG_PREFERRED || debug) { 4824 Slog.v(TAG, "Returning persistent preferred activity: " + 4825 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4826 } 4827 return ri; 4828 } 4829 } 4830 } 4831 return null; 4832 } 4833 4834 // TODO: handle preferred activities missing while user has amnesia 4835 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4836 List<ResolveInfo> query, int priority, boolean always, 4837 boolean removeMatches, boolean debug, int userId) { 4838 if (!sUserManager.exists(userId)) return null; 4839 flags = updateFlagsForResolve(flags, userId, intent); 4840 // writer 4841 synchronized (mPackages) { 4842 if (intent.getSelector() != null) { 4843 intent = intent.getSelector(); 4844 } 4845 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4846 4847 // Try to find a matching persistent preferred activity. 4848 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4849 debug, userId); 4850 4851 // If a persistent preferred activity matched, use it. 4852 if (pri != null) { 4853 return pri; 4854 } 4855 4856 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4857 // Get the list of preferred activities that handle the intent 4858 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4859 List<PreferredActivity> prefs = pir != null 4860 ? pir.queryIntent(intent, resolvedType, 4861 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4862 : null; 4863 if (prefs != null && prefs.size() > 0) { 4864 boolean changed = false; 4865 try { 4866 // First figure out how good the original match set is. 4867 // We will only allow preferred activities that came 4868 // from the same match quality. 4869 int match = 0; 4870 4871 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4872 4873 final int N = query.size(); 4874 for (int j=0; j<N; j++) { 4875 final ResolveInfo ri = query.get(j); 4876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4877 + ": 0x" + Integer.toHexString(match)); 4878 if (ri.match > match) { 4879 match = ri.match; 4880 } 4881 } 4882 4883 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4884 + Integer.toHexString(match)); 4885 4886 match &= IntentFilter.MATCH_CATEGORY_MASK; 4887 final int M = prefs.size(); 4888 for (int i=0; i<M; i++) { 4889 final PreferredActivity pa = prefs.get(i); 4890 if (DEBUG_PREFERRED || debug) { 4891 Slog.v(TAG, "Checking PreferredActivity ds=" 4892 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4893 + "\n component=" + pa.mPref.mComponent); 4894 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4895 } 4896 if (pa.mPref.mMatch != match) { 4897 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4898 + Integer.toHexString(pa.mPref.mMatch)); 4899 continue; 4900 } 4901 // If it's not an "always" type preferred activity and that's what we're 4902 // looking for, skip it. 4903 if (always && !pa.mPref.mAlways) { 4904 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4905 continue; 4906 } 4907 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4908 flags | MATCH_DISABLED_COMPONENTS, userId); 4909 if (DEBUG_PREFERRED || debug) { 4910 Slog.v(TAG, "Found preferred activity:"); 4911 if (ai != null) { 4912 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4913 } else { 4914 Slog.v(TAG, " null"); 4915 } 4916 } 4917 if (ai == null) { 4918 // This previously registered preferred activity 4919 // component is no longer known. Most likely an update 4920 // to the app was installed and in the new version this 4921 // component no longer exists. Clean it up by removing 4922 // it from the preferred activities list, and skip it. 4923 Slog.w(TAG, "Removing dangling preferred activity: " 4924 + pa.mPref.mComponent); 4925 pir.removeFilter(pa); 4926 changed = true; 4927 continue; 4928 } 4929 for (int j=0; j<N; j++) { 4930 final ResolveInfo ri = query.get(j); 4931 if (!ri.activityInfo.applicationInfo.packageName 4932 .equals(ai.applicationInfo.packageName)) { 4933 continue; 4934 } 4935 if (!ri.activityInfo.name.equals(ai.name)) { 4936 continue; 4937 } 4938 4939 if (removeMatches) { 4940 pir.removeFilter(pa); 4941 changed = true; 4942 if (DEBUG_PREFERRED) { 4943 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4944 } 4945 break; 4946 } 4947 4948 // Okay we found a previously set preferred or last chosen app. 4949 // If the result set is different from when this 4950 // was created, we need to clear it and re-ask the 4951 // user their preference, if we're looking for an "always" type entry. 4952 if (always && !pa.mPref.sameSet(query)) { 4953 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4954 + intent + " type " + resolvedType); 4955 if (DEBUG_PREFERRED) { 4956 Slog.v(TAG, "Removing preferred activity since set changed " 4957 + pa.mPref.mComponent); 4958 } 4959 pir.removeFilter(pa); 4960 // Re-add the filter as a "last chosen" entry (!always) 4961 PreferredActivity lastChosen = new PreferredActivity( 4962 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4963 pir.addFilter(lastChosen); 4964 changed = true; 4965 return null; 4966 } 4967 4968 // Yay! Either the set matched or we're looking for the last chosen 4969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4970 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4971 return ri; 4972 } 4973 } 4974 } finally { 4975 if (changed) { 4976 if (DEBUG_PREFERRED) { 4977 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4978 } 4979 scheduleWritePackageRestrictionsLocked(userId); 4980 } 4981 } 4982 } 4983 } 4984 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4985 return null; 4986 } 4987 4988 /* 4989 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4990 */ 4991 @Override 4992 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4993 int targetUserId) { 4994 mContext.enforceCallingOrSelfPermission( 4995 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4996 List<CrossProfileIntentFilter> matches = 4997 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4998 if (matches != null) { 4999 int size = matches.size(); 5000 for (int i = 0; i < size; i++) { 5001 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5002 } 5003 } 5004 if (hasWebURI(intent)) { 5005 // cross-profile app linking works only towards the parent. 5006 final UserInfo parent = getProfileParent(sourceUserId); 5007 synchronized(mPackages) { 5008 int flags = updateFlagsForResolve(0, parent.id, intent); 5009 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5010 intent, resolvedType, flags, sourceUserId, parent.id); 5011 return xpDomainInfo != null; 5012 } 5013 } 5014 return false; 5015 } 5016 5017 private UserInfo getProfileParent(int userId) { 5018 final long identity = Binder.clearCallingIdentity(); 5019 try { 5020 return sUserManager.getProfileParent(userId); 5021 } finally { 5022 Binder.restoreCallingIdentity(identity); 5023 } 5024 } 5025 5026 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5027 String resolvedType, int userId) { 5028 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5029 if (resolver != null) { 5030 return resolver.queryIntent(intent, resolvedType, false, userId); 5031 } 5032 return null; 5033 } 5034 5035 @Override 5036 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5037 String resolvedType, int flags, int userId) { 5038 return new ParceledListSlice<>( 5039 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5040 } 5041 5042 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5043 String resolvedType, int flags, int userId) { 5044 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5045 flags = updateFlagsForResolve(flags, userId, intent); 5046 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5047 false /* requireFullPermission */, false /* checkShell */, 5048 "query intent activities"); 5049 ComponentName comp = intent.getComponent(); 5050 if (comp == null) { 5051 if (intent.getSelector() != null) { 5052 intent = intent.getSelector(); 5053 comp = intent.getComponent(); 5054 } 5055 } 5056 5057 if (comp != null) { 5058 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5059 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5060 if (ai != null) { 5061 final ResolveInfo ri = new ResolveInfo(); 5062 ri.activityInfo = ai; 5063 list.add(ri); 5064 } 5065 return list; 5066 } 5067 5068 // reader 5069 synchronized (mPackages) { 5070 final String pkgName = intent.getPackage(); 5071 if (pkgName == null) { 5072 List<CrossProfileIntentFilter> matchingFilters = 5073 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5074 // Check for results that need to skip the current profile. 5075 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5076 resolvedType, flags, userId); 5077 if (xpResolveInfo != null) { 5078 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5079 result.add(xpResolveInfo); 5080 return filterIfNotSystemUser(result, userId); 5081 } 5082 5083 // Check for results in the current profile. 5084 List<ResolveInfo> result = mActivities.queryIntent( 5085 intent, resolvedType, flags, userId); 5086 result = filterIfNotSystemUser(result, userId); 5087 5088 // Check for cross profile results. 5089 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5090 xpResolveInfo = queryCrossProfileIntents( 5091 matchingFilters, intent, resolvedType, flags, userId, 5092 hasNonNegativePriorityResult); 5093 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5094 boolean isVisibleToUser = filterIfNotSystemUser( 5095 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5096 if (isVisibleToUser) { 5097 result.add(xpResolveInfo); 5098 Collections.sort(result, mResolvePrioritySorter); 5099 } 5100 } 5101 if (hasWebURI(intent)) { 5102 CrossProfileDomainInfo xpDomainInfo = null; 5103 final UserInfo parent = getProfileParent(userId); 5104 if (parent != null) { 5105 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5106 flags, userId, parent.id); 5107 } 5108 if (xpDomainInfo != null) { 5109 if (xpResolveInfo != null) { 5110 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5111 // in the result. 5112 result.remove(xpResolveInfo); 5113 } 5114 if (result.size() == 0) { 5115 result.add(xpDomainInfo.resolveInfo); 5116 return result; 5117 } 5118 } else if (result.size() <= 1) { 5119 return result; 5120 } 5121 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5122 xpDomainInfo, userId); 5123 Collections.sort(result, mResolvePrioritySorter); 5124 } 5125 return result; 5126 } 5127 final PackageParser.Package pkg = mPackages.get(pkgName); 5128 if (pkg != null) { 5129 return filterIfNotSystemUser( 5130 mActivities.queryIntentForPackage( 5131 intent, resolvedType, flags, pkg.activities, userId), 5132 userId); 5133 } 5134 return new ArrayList<ResolveInfo>(); 5135 } 5136 } 5137 5138 private static class CrossProfileDomainInfo { 5139 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5140 ResolveInfo resolveInfo; 5141 /* Best domain verification status of the activities found in the other profile */ 5142 int bestDomainVerificationStatus; 5143 } 5144 5145 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5146 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5147 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5148 sourceUserId)) { 5149 return null; 5150 } 5151 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5152 resolvedType, flags, parentUserId); 5153 5154 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5155 return null; 5156 } 5157 CrossProfileDomainInfo result = null; 5158 int size = resultTargetUser.size(); 5159 for (int i = 0; i < size; i++) { 5160 ResolveInfo riTargetUser = resultTargetUser.get(i); 5161 // Intent filter verification is only for filters that specify a host. So don't return 5162 // those that handle all web uris. 5163 if (riTargetUser.handleAllWebDataURI) { 5164 continue; 5165 } 5166 String packageName = riTargetUser.activityInfo.packageName; 5167 PackageSetting ps = mSettings.mPackages.get(packageName); 5168 if (ps == null) { 5169 continue; 5170 } 5171 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5172 int status = (int)(verificationState >> 32); 5173 if (result == null) { 5174 result = new CrossProfileDomainInfo(); 5175 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5176 sourceUserId, parentUserId); 5177 result.bestDomainVerificationStatus = status; 5178 } else { 5179 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5180 result.bestDomainVerificationStatus); 5181 } 5182 } 5183 // Don't consider matches with status NEVER across profiles. 5184 if (result != null && result.bestDomainVerificationStatus 5185 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5186 return null; 5187 } 5188 return result; 5189 } 5190 5191 /** 5192 * Verification statuses are ordered from the worse to the best, except for 5193 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5194 */ 5195 private int bestDomainVerificationStatus(int status1, int status2) { 5196 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5197 return status2; 5198 } 5199 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5200 return status1; 5201 } 5202 return (int) MathUtils.max(status1, status2); 5203 } 5204 5205 private boolean isUserEnabled(int userId) { 5206 long callingId = Binder.clearCallingIdentity(); 5207 try { 5208 UserInfo userInfo = sUserManager.getUserInfo(userId); 5209 return userInfo != null && userInfo.isEnabled(); 5210 } finally { 5211 Binder.restoreCallingIdentity(callingId); 5212 } 5213 } 5214 5215 /** 5216 * Filter out activities with systemUserOnly flag set, when current user is not System. 5217 * 5218 * @return filtered list 5219 */ 5220 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5221 if (userId == UserHandle.USER_SYSTEM) { 5222 return resolveInfos; 5223 } 5224 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5225 ResolveInfo info = resolveInfos.get(i); 5226 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5227 resolveInfos.remove(i); 5228 } 5229 } 5230 return resolveInfos; 5231 } 5232 5233 /** 5234 * @param resolveInfos list of resolve infos in descending priority order 5235 * @return if the list contains a resolve info with non-negative priority 5236 */ 5237 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5238 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5239 } 5240 5241 private static boolean hasWebURI(Intent intent) { 5242 if (intent.getData() == null) { 5243 return false; 5244 } 5245 final String scheme = intent.getScheme(); 5246 if (TextUtils.isEmpty(scheme)) { 5247 return false; 5248 } 5249 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5250 } 5251 5252 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5253 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5254 int userId) { 5255 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5256 5257 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5258 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5259 candidates.size()); 5260 } 5261 5262 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5263 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5264 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5265 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5266 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5267 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5268 5269 synchronized (mPackages) { 5270 final int count = candidates.size(); 5271 // First, try to use linked apps. Partition the candidates into four lists: 5272 // one for the final results, one for the "do not use ever", one for "undefined status" 5273 // and finally one for "browser app type". 5274 for (int n=0; n<count; n++) { 5275 ResolveInfo info = candidates.get(n); 5276 String packageName = info.activityInfo.packageName; 5277 PackageSetting ps = mSettings.mPackages.get(packageName); 5278 if (ps != null) { 5279 // Add to the special match all list (Browser use case) 5280 if (info.handleAllWebDataURI) { 5281 matchAllList.add(info); 5282 continue; 5283 } 5284 // Try to get the status from User settings first 5285 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5286 int status = (int)(packedStatus >> 32); 5287 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5288 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5289 if (DEBUG_DOMAIN_VERIFICATION) { 5290 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5291 + " : linkgen=" + linkGeneration); 5292 } 5293 // Use link-enabled generation as preferredOrder, i.e. 5294 // prefer newly-enabled over earlier-enabled. 5295 info.preferredOrder = linkGeneration; 5296 alwaysList.add(info); 5297 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5298 if (DEBUG_DOMAIN_VERIFICATION) { 5299 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5300 } 5301 neverList.add(info); 5302 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5303 if (DEBUG_DOMAIN_VERIFICATION) { 5304 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5305 } 5306 alwaysAskList.add(info); 5307 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5308 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5309 if (DEBUG_DOMAIN_VERIFICATION) { 5310 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5311 } 5312 undefinedList.add(info); 5313 } 5314 } 5315 } 5316 5317 // We'll want to include browser possibilities in a few cases 5318 boolean includeBrowser = false; 5319 5320 // First try to add the "always" resolution(s) for the current user, if any 5321 if (alwaysList.size() > 0) { 5322 result.addAll(alwaysList); 5323 } else { 5324 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5325 result.addAll(undefinedList); 5326 // Maybe add one for the other profile. 5327 if (xpDomainInfo != null && ( 5328 xpDomainInfo.bestDomainVerificationStatus 5329 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5330 result.add(xpDomainInfo.resolveInfo); 5331 } 5332 includeBrowser = true; 5333 } 5334 5335 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5336 // If there were 'always' entries their preferred order has been set, so we also 5337 // back that off to make the alternatives equivalent 5338 if (alwaysAskList.size() > 0) { 5339 for (ResolveInfo i : result) { 5340 i.preferredOrder = 0; 5341 } 5342 result.addAll(alwaysAskList); 5343 includeBrowser = true; 5344 } 5345 5346 if (includeBrowser) { 5347 // Also add browsers (all of them or only the default one) 5348 if (DEBUG_DOMAIN_VERIFICATION) { 5349 Slog.v(TAG, " ...including browsers in candidate set"); 5350 } 5351 if ((matchFlags & MATCH_ALL) != 0) { 5352 result.addAll(matchAllList); 5353 } else { 5354 // Browser/generic handling case. If there's a default browser, go straight 5355 // to that (but only if there is no other higher-priority match). 5356 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5357 int maxMatchPrio = 0; 5358 ResolveInfo defaultBrowserMatch = null; 5359 final int numCandidates = matchAllList.size(); 5360 for (int n = 0; n < numCandidates; n++) { 5361 ResolveInfo info = matchAllList.get(n); 5362 // track the highest overall match priority... 5363 if (info.priority > maxMatchPrio) { 5364 maxMatchPrio = info.priority; 5365 } 5366 // ...and the highest-priority default browser match 5367 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5368 if (defaultBrowserMatch == null 5369 || (defaultBrowserMatch.priority < info.priority)) { 5370 if (debug) { 5371 Slog.v(TAG, "Considering default browser match " + info); 5372 } 5373 defaultBrowserMatch = info; 5374 } 5375 } 5376 } 5377 if (defaultBrowserMatch != null 5378 && defaultBrowserMatch.priority >= maxMatchPrio 5379 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5380 { 5381 if (debug) { 5382 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5383 } 5384 result.add(defaultBrowserMatch); 5385 } else { 5386 result.addAll(matchAllList); 5387 } 5388 } 5389 5390 // If there is nothing selected, add all candidates and remove the ones that the user 5391 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5392 if (result.size() == 0) { 5393 result.addAll(candidates); 5394 result.removeAll(neverList); 5395 } 5396 } 5397 } 5398 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5399 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5400 result.size()); 5401 for (ResolveInfo info : result) { 5402 Slog.v(TAG, " + " + info.activityInfo); 5403 } 5404 } 5405 return result; 5406 } 5407 5408 // Returns a packed value as a long: 5409 // 5410 // high 'int'-sized word: link status: undefined/ask/never/always. 5411 // low 'int'-sized word: relative priority among 'always' results. 5412 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5413 long result = ps.getDomainVerificationStatusForUser(userId); 5414 // if none available, get the master status 5415 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5416 if (ps.getIntentFilterVerificationInfo() != null) { 5417 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5418 } 5419 } 5420 return result; 5421 } 5422 5423 private ResolveInfo querySkipCurrentProfileIntents( 5424 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5425 int flags, int sourceUserId) { 5426 if (matchingFilters != null) { 5427 int size = matchingFilters.size(); 5428 for (int i = 0; i < size; i ++) { 5429 CrossProfileIntentFilter filter = matchingFilters.get(i); 5430 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5431 // Checking if there are activities in the target user that can handle the 5432 // intent. 5433 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5434 resolvedType, flags, sourceUserId); 5435 if (resolveInfo != null) { 5436 return resolveInfo; 5437 } 5438 } 5439 } 5440 } 5441 return null; 5442 } 5443 5444 // Return matching ResolveInfo in target user if any. 5445 private ResolveInfo queryCrossProfileIntents( 5446 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5447 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5448 if (matchingFilters != null) { 5449 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5450 // match the same intent. For performance reasons, it is better not to 5451 // run queryIntent twice for the same userId 5452 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5453 int size = matchingFilters.size(); 5454 for (int i = 0; i < size; i++) { 5455 CrossProfileIntentFilter filter = matchingFilters.get(i); 5456 int targetUserId = filter.getTargetUserId(); 5457 boolean skipCurrentProfile = 5458 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5459 boolean skipCurrentProfileIfNoMatchFound = 5460 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5461 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5462 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5463 // Checking if there are activities in the target user that can handle the 5464 // intent. 5465 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5466 resolvedType, flags, sourceUserId); 5467 if (resolveInfo != null) return resolveInfo; 5468 alreadyTriedUserIds.put(targetUserId, true); 5469 } 5470 } 5471 } 5472 return null; 5473 } 5474 5475 /** 5476 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5477 * will forward the intent to the filter's target user. 5478 * Otherwise, returns null. 5479 */ 5480 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5481 String resolvedType, int flags, int sourceUserId) { 5482 int targetUserId = filter.getTargetUserId(); 5483 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5484 resolvedType, flags, targetUserId); 5485 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5486 // If all the matches in the target profile are suspended, return null. 5487 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5488 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5489 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5490 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5491 targetUserId); 5492 } 5493 } 5494 } 5495 return null; 5496 } 5497 5498 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5499 int sourceUserId, int targetUserId) { 5500 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5501 long ident = Binder.clearCallingIdentity(); 5502 boolean targetIsProfile; 5503 try { 5504 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5505 } finally { 5506 Binder.restoreCallingIdentity(ident); 5507 } 5508 String className; 5509 if (targetIsProfile) { 5510 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5511 } else { 5512 className = FORWARD_INTENT_TO_PARENT; 5513 } 5514 ComponentName forwardingActivityComponentName = new ComponentName( 5515 mAndroidApplication.packageName, className); 5516 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5517 sourceUserId); 5518 if (!targetIsProfile) { 5519 forwardingActivityInfo.showUserIcon = targetUserId; 5520 forwardingResolveInfo.noResourceId = true; 5521 } 5522 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5523 forwardingResolveInfo.priority = 0; 5524 forwardingResolveInfo.preferredOrder = 0; 5525 forwardingResolveInfo.match = 0; 5526 forwardingResolveInfo.isDefault = true; 5527 forwardingResolveInfo.filter = filter; 5528 forwardingResolveInfo.targetUserId = targetUserId; 5529 return forwardingResolveInfo; 5530 } 5531 5532 @Override 5533 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5534 Intent[] specifics, String[] specificTypes, Intent intent, 5535 String resolvedType, int flags, int userId) { 5536 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5537 specificTypes, intent, resolvedType, flags, userId)); 5538 } 5539 5540 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5541 Intent[] specifics, String[] specificTypes, Intent intent, 5542 String resolvedType, int flags, int userId) { 5543 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5544 flags = updateFlagsForResolve(flags, userId, intent); 5545 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5546 false /* requireFullPermission */, false /* checkShell */, 5547 "query intent activity options"); 5548 final String resultsAction = intent.getAction(); 5549 5550 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5551 | PackageManager.GET_RESOLVED_FILTER, userId); 5552 5553 if (DEBUG_INTENT_MATCHING) { 5554 Log.v(TAG, "Query " + intent + ": " + results); 5555 } 5556 5557 int specificsPos = 0; 5558 int N; 5559 5560 // todo: note that the algorithm used here is O(N^2). This 5561 // isn't a problem in our current environment, but if we start running 5562 // into situations where we have more than 5 or 10 matches then this 5563 // should probably be changed to something smarter... 5564 5565 // First we go through and resolve each of the specific items 5566 // that were supplied, taking care of removing any corresponding 5567 // duplicate items in the generic resolve list. 5568 if (specifics != null) { 5569 for (int i=0; i<specifics.length; i++) { 5570 final Intent sintent = specifics[i]; 5571 if (sintent == null) { 5572 continue; 5573 } 5574 5575 if (DEBUG_INTENT_MATCHING) { 5576 Log.v(TAG, "Specific #" + i + ": " + sintent); 5577 } 5578 5579 String action = sintent.getAction(); 5580 if (resultsAction != null && resultsAction.equals(action)) { 5581 // If this action was explicitly requested, then don't 5582 // remove things that have it. 5583 action = null; 5584 } 5585 5586 ResolveInfo ri = null; 5587 ActivityInfo ai = null; 5588 5589 ComponentName comp = sintent.getComponent(); 5590 if (comp == null) { 5591 ri = resolveIntent( 5592 sintent, 5593 specificTypes != null ? specificTypes[i] : null, 5594 flags, userId); 5595 if (ri == null) { 5596 continue; 5597 } 5598 if (ri == mResolveInfo) { 5599 // ACK! Must do something better with this. 5600 } 5601 ai = ri.activityInfo; 5602 comp = new ComponentName(ai.applicationInfo.packageName, 5603 ai.name); 5604 } else { 5605 ai = getActivityInfo(comp, flags, userId); 5606 if (ai == null) { 5607 continue; 5608 } 5609 } 5610 5611 // Look for any generic query activities that are duplicates 5612 // of this specific one, and remove them from the results. 5613 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5614 N = results.size(); 5615 int j; 5616 for (j=specificsPos; j<N; j++) { 5617 ResolveInfo sri = results.get(j); 5618 if ((sri.activityInfo.name.equals(comp.getClassName()) 5619 && sri.activityInfo.applicationInfo.packageName.equals( 5620 comp.getPackageName())) 5621 || (action != null && sri.filter.matchAction(action))) { 5622 results.remove(j); 5623 if (DEBUG_INTENT_MATCHING) Log.v( 5624 TAG, "Removing duplicate item from " + j 5625 + " due to specific " + specificsPos); 5626 if (ri == null) { 5627 ri = sri; 5628 } 5629 j--; 5630 N--; 5631 } 5632 } 5633 5634 // Add this specific item to its proper place. 5635 if (ri == null) { 5636 ri = new ResolveInfo(); 5637 ri.activityInfo = ai; 5638 } 5639 results.add(specificsPos, ri); 5640 ri.specificIndex = i; 5641 specificsPos++; 5642 } 5643 } 5644 5645 // Now we go through the remaining generic results and remove any 5646 // duplicate actions that are found here. 5647 N = results.size(); 5648 for (int i=specificsPos; i<N-1; i++) { 5649 final ResolveInfo rii = results.get(i); 5650 if (rii.filter == null) { 5651 continue; 5652 } 5653 5654 // Iterate over all of the actions of this result's intent 5655 // filter... typically this should be just one. 5656 final Iterator<String> it = rii.filter.actionsIterator(); 5657 if (it == null) { 5658 continue; 5659 } 5660 while (it.hasNext()) { 5661 final String action = it.next(); 5662 if (resultsAction != null && resultsAction.equals(action)) { 5663 // If this action was explicitly requested, then don't 5664 // remove things that have it. 5665 continue; 5666 } 5667 for (int j=i+1; j<N; j++) { 5668 final ResolveInfo rij = results.get(j); 5669 if (rij.filter != null && rij.filter.hasAction(action)) { 5670 results.remove(j); 5671 if (DEBUG_INTENT_MATCHING) Log.v( 5672 TAG, "Removing duplicate item from " + j 5673 + " due to action " + action + " at " + i); 5674 j--; 5675 N--; 5676 } 5677 } 5678 } 5679 5680 // If the caller didn't request filter information, drop it now 5681 // so we don't have to marshall/unmarshall it. 5682 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5683 rii.filter = null; 5684 } 5685 } 5686 5687 // Filter out the caller activity if so requested. 5688 if (caller != null) { 5689 N = results.size(); 5690 for (int i=0; i<N; i++) { 5691 ActivityInfo ainfo = results.get(i).activityInfo; 5692 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5693 && caller.getClassName().equals(ainfo.name)) { 5694 results.remove(i); 5695 break; 5696 } 5697 } 5698 } 5699 5700 // If the caller didn't request filter information, 5701 // drop them now so we don't have to 5702 // marshall/unmarshall it. 5703 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5704 N = results.size(); 5705 for (int i=0; i<N; i++) { 5706 results.get(i).filter = null; 5707 } 5708 } 5709 5710 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5711 return results; 5712 } 5713 5714 @Override 5715 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5716 String resolvedType, int flags, int userId) { 5717 return new ParceledListSlice<>( 5718 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5719 } 5720 5721 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5722 String resolvedType, int flags, int userId) { 5723 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5724 flags = updateFlagsForResolve(flags, userId, intent); 5725 ComponentName comp = intent.getComponent(); 5726 if (comp == null) { 5727 if (intent.getSelector() != null) { 5728 intent = intent.getSelector(); 5729 comp = intent.getComponent(); 5730 } 5731 } 5732 if (comp != null) { 5733 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5734 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5735 if (ai != null) { 5736 ResolveInfo ri = new ResolveInfo(); 5737 ri.activityInfo = ai; 5738 list.add(ri); 5739 } 5740 return list; 5741 } 5742 5743 // reader 5744 synchronized (mPackages) { 5745 String pkgName = intent.getPackage(); 5746 if (pkgName == null) { 5747 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5748 } 5749 final PackageParser.Package pkg = mPackages.get(pkgName); 5750 if (pkg != null) { 5751 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5752 userId); 5753 } 5754 return Collections.emptyList(); 5755 } 5756 } 5757 5758 @Override 5759 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5760 if (!sUserManager.exists(userId)) return null; 5761 flags = updateFlagsForResolve(flags, userId, intent); 5762 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5763 if (query != null) { 5764 if (query.size() >= 1) { 5765 // If there is more than one service with the same priority, 5766 // just arbitrarily pick the first one. 5767 return query.get(0); 5768 } 5769 } 5770 return null; 5771 } 5772 5773 @Override 5774 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5775 String resolvedType, int flags, int userId) { 5776 return new ParceledListSlice<>( 5777 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5778 } 5779 5780 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5781 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 ServiceInfo si = getServiceInfo(comp, flags, userId); 5794 if (si != null) { 5795 final ResolveInfo ri = new ResolveInfo(); 5796 ri.serviceInfo = si; 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 mServices.queryIntent(intent, resolvedType, flags, userId); 5807 } 5808 final PackageParser.Package pkg = mPackages.get(pkgName); 5809 if (pkg != null) { 5810 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5811 userId); 5812 } 5813 return Collections.emptyList(); 5814 } 5815 } 5816 5817 @Override 5818 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5819 String resolvedType, int flags, int userId) { 5820 return new ParceledListSlice<>( 5821 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5822 } 5823 5824 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5825 Intent intent, String resolvedType, int flags, int userId) { 5826 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5827 flags = updateFlagsForResolve(flags, userId, intent); 5828 ComponentName comp = intent.getComponent(); 5829 if (comp == null) { 5830 if (intent.getSelector() != null) { 5831 intent = intent.getSelector(); 5832 comp = intent.getComponent(); 5833 } 5834 } 5835 if (comp != null) { 5836 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5837 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5838 if (pi != null) { 5839 final ResolveInfo ri = new ResolveInfo(); 5840 ri.providerInfo = pi; 5841 list.add(ri); 5842 } 5843 return list; 5844 } 5845 5846 // reader 5847 synchronized (mPackages) { 5848 String pkgName = intent.getPackage(); 5849 if (pkgName == null) { 5850 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5851 } 5852 final PackageParser.Package pkg = mPackages.get(pkgName); 5853 if (pkg != null) { 5854 return mProviders.queryIntentForPackage( 5855 intent, resolvedType, flags, pkg.providers, userId); 5856 } 5857 return Collections.emptyList(); 5858 } 5859 } 5860 5861 @Override 5862 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5863 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5864 flags = updateFlagsForPackage(flags, userId, null); 5865 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5866 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5867 true /* requireFullPermission */, false /* checkShell */, 5868 "get installed packages"); 5869 5870 // writer 5871 synchronized (mPackages) { 5872 ArrayList<PackageInfo> list; 5873 if (listUninstalled) { 5874 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5875 for (PackageSetting ps : mSettings.mPackages.values()) { 5876 PackageInfo pi; 5877 if (ps.pkg != null) { 5878 pi = generatePackageInfo(ps.pkg, flags, userId); 5879 } else { 5880 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5881 } 5882 if (pi != null) { 5883 list.add(pi); 5884 } 5885 } 5886 } else { 5887 list = new ArrayList<PackageInfo>(mPackages.size()); 5888 for (PackageParser.Package p : mPackages.values()) { 5889 PackageInfo pi = generatePackageInfo(p, flags, userId); 5890 if (pi != null) { 5891 list.add(pi); 5892 } 5893 } 5894 } 5895 5896 return new ParceledListSlice<PackageInfo>(list); 5897 } 5898 } 5899 5900 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5901 String[] permissions, boolean[] tmp, int flags, int userId) { 5902 int numMatch = 0; 5903 final PermissionsState permissionsState = ps.getPermissionsState(); 5904 for (int i=0; i<permissions.length; i++) { 5905 final String permission = permissions[i]; 5906 if (permissionsState.hasPermission(permission, userId)) { 5907 tmp[i] = true; 5908 numMatch++; 5909 } else { 5910 tmp[i] = false; 5911 } 5912 } 5913 if (numMatch == 0) { 5914 return; 5915 } 5916 PackageInfo pi; 5917 if (ps.pkg != null) { 5918 pi = generatePackageInfo(ps.pkg, flags, userId); 5919 } else { 5920 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5921 } 5922 // The above might return null in cases of uninstalled apps or install-state 5923 // skew across users/profiles. 5924 if (pi != null) { 5925 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5926 if (numMatch == permissions.length) { 5927 pi.requestedPermissions = permissions; 5928 } else { 5929 pi.requestedPermissions = new String[numMatch]; 5930 numMatch = 0; 5931 for (int i=0; i<permissions.length; i++) { 5932 if (tmp[i]) { 5933 pi.requestedPermissions[numMatch] = permissions[i]; 5934 numMatch++; 5935 } 5936 } 5937 } 5938 } 5939 list.add(pi); 5940 } 5941 } 5942 5943 @Override 5944 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5945 String[] permissions, int flags, int userId) { 5946 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5947 flags = updateFlagsForPackage(flags, userId, permissions); 5948 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5949 5950 // writer 5951 synchronized (mPackages) { 5952 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5953 boolean[] tmpBools = new boolean[permissions.length]; 5954 if (listUninstalled) { 5955 for (PackageSetting ps : mSettings.mPackages.values()) { 5956 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5957 } 5958 } else { 5959 for (PackageParser.Package pkg : mPackages.values()) { 5960 PackageSetting ps = (PackageSetting)pkg.mExtras; 5961 if (ps != null) { 5962 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5963 userId); 5964 } 5965 } 5966 } 5967 5968 return new ParceledListSlice<PackageInfo>(list); 5969 } 5970 } 5971 5972 @Override 5973 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5974 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5975 flags = updateFlagsForApplication(flags, userId, null); 5976 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5977 5978 // writer 5979 synchronized (mPackages) { 5980 ArrayList<ApplicationInfo> list; 5981 if (listUninstalled) { 5982 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5983 for (PackageSetting ps : mSettings.mPackages.values()) { 5984 ApplicationInfo ai; 5985 if (ps.pkg != null) { 5986 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5987 ps.readUserState(userId), userId); 5988 } else { 5989 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5990 } 5991 if (ai != null) { 5992 list.add(ai); 5993 } 5994 } 5995 } else { 5996 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5997 for (PackageParser.Package p : mPackages.values()) { 5998 if (p.mExtras != null) { 5999 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6000 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6001 if (ai != null) { 6002 list.add(ai); 6003 } 6004 } 6005 } 6006 } 6007 6008 return new ParceledListSlice<ApplicationInfo>(list); 6009 } 6010 } 6011 6012 @Override 6013 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6014 if (DISABLE_EPHEMERAL_APPS) { 6015 return null; 6016 } 6017 6018 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6019 "getEphemeralApplications"); 6020 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6021 true /* requireFullPermission */, false /* checkShell */, 6022 "getEphemeralApplications"); 6023 synchronized (mPackages) { 6024 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6025 .getEphemeralApplicationsLPw(userId); 6026 if (ephemeralApps != null) { 6027 return new ParceledListSlice<>(ephemeralApps); 6028 } 6029 } 6030 return null; 6031 } 6032 6033 @Override 6034 public boolean isEphemeralApplication(String packageName, int userId) { 6035 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6036 true /* requireFullPermission */, false /* checkShell */, 6037 "isEphemeral"); 6038 if (DISABLE_EPHEMERAL_APPS) { 6039 return false; 6040 } 6041 6042 if (!isCallerSameApp(packageName)) { 6043 return false; 6044 } 6045 synchronized (mPackages) { 6046 PackageParser.Package pkg = mPackages.get(packageName); 6047 if (pkg != null) { 6048 return pkg.applicationInfo.isEphemeralApp(); 6049 } 6050 } 6051 return false; 6052 } 6053 6054 @Override 6055 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6056 if (DISABLE_EPHEMERAL_APPS) { 6057 return null; 6058 } 6059 6060 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6061 true /* requireFullPermission */, false /* checkShell */, 6062 "getCookie"); 6063 if (!isCallerSameApp(packageName)) { 6064 return null; 6065 } 6066 synchronized (mPackages) { 6067 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6068 packageName, userId); 6069 } 6070 } 6071 6072 @Override 6073 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6074 if (DISABLE_EPHEMERAL_APPS) { 6075 return true; 6076 } 6077 6078 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6079 true /* requireFullPermission */, true /* checkShell */, 6080 "setCookie"); 6081 if (!isCallerSameApp(packageName)) { 6082 return false; 6083 } 6084 synchronized (mPackages) { 6085 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6086 packageName, cookie, userId); 6087 } 6088 } 6089 6090 @Override 6091 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6092 if (DISABLE_EPHEMERAL_APPS) { 6093 return null; 6094 } 6095 6096 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6097 "getEphemeralApplicationIcon"); 6098 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6099 true /* requireFullPermission */, false /* checkShell */, 6100 "getEphemeralApplicationIcon"); 6101 synchronized (mPackages) { 6102 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6103 packageName, userId); 6104 } 6105 } 6106 6107 private boolean isCallerSameApp(String packageName) { 6108 PackageParser.Package pkg = mPackages.get(packageName); 6109 return pkg != null 6110 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6111 } 6112 6113 @Override 6114 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6115 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6116 } 6117 6118 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6119 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6120 6121 // reader 6122 synchronized (mPackages) { 6123 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6124 final int userId = UserHandle.getCallingUserId(); 6125 while (i.hasNext()) { 6126 final PackageParser.Package p = i.next(); 6127 if (p.applicationInfo == null) continue; 6128 6129 final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0) 6130 && !p.applicationInfo.isEncryptionAware(); 6131 final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0) 6132 && p.applicationInfo.isEncryptionAware(); 6133 6134 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6135 && (!mSafeMode || isSystemApp(p)) 6136 && (matchesUnaware || matchesAware)) { 6137 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6138 if (ps != null) { 6139 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6140 ps.readUserState(userId), userId); 6141 if (ai != null) { 6142 finalList.add(ai); 6143 } 6144 } 6145 } 6146 } 6147 } 6148 6149 return finalList; 6150 } 6151 6152 @Override 6153 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6154 if (!sUserManager.exists(userId)) return null; 6155 flags = updateFlagsForComponent(flags, userId, name); 6156 // reader 6157 synchronized (mPackages) { 6158 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6159 PackageSetting ps = provider != null 6160 ? mSettings.mPackages.get(provider.owner.packageName) 6161 : null; 6162 return ps != null 6163 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6164 ? PackageParser.generateProviderInfo(provider, flags, 6165 ps.readUserState(userId), userId) 6166 : null; 6167 } 6168 } 6169 6170 /** 6171 * @deprecated 6172 */ 6173 @Deprecated 6174 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6175 // reader 6176 synchronized (mPackages) { 6177 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6178 .entrySet().iterator(); 6179 final int userId = UserHandle.getCallingUserId(); 6180 while (i.hasNext()) { 6181 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6182 PackageParser.Provider p = entry.getValue(); 6183 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6184 6185 if (ps != null && p.syncable 6186 && (!mSafeMode || (p.info.applicationInfo.flags 6187 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6188 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6189 ps.readUserState(userId), userId); 6190 if (info != null) { 6191 outNames.add(entry.getKey()); 6192 outInfo.add(info); 6193 } 6194 } 6195 } 6196 } 6197 } 6198 6199 @Override 6200 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6201 int uid, int flags) { 6202 final int userId = processName != null ? UserHandle.getUserId(uid) 6203 : UserHandle.getCallingUserId(); 6204 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6205 flags = updateFlagsForComponent(flags, userId, processName); 6206 6207 ArrayList<ProviderInfo> finalList = null; 6208 // reader 6209 synchronized (mPackages) { 6210 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6211 while (i.hasNext()) { 6212 final PackageParser.Provider p = i.next(); 6213 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6214 if (ps != null && p.info.authority != null 6215 && (processName == null 6216 || (p.info.processName.equals(processName) 6217 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6218 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6219 if (finalList == null) { 6220 finalList = new ArrayList<ProviderInfo>(3); 6221 } 6222 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6223 ps.readUserState(userId), userId); 6224 if (info != null) { 6225 finalList.add(info); 6226 } 6227 } 6228 } 6229 } 6230 6231 if (finalList != null) { 6232 Collections.sort(finalList, mProviderInitOrderSorter); 6233 return new ParceledListSlice<ProviderInfo>(finalList); 6234 } 6235 6236 return ParceledListSlice.emptyList(); 6237 } 6238 6239 @Override 6240 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6241 // reader 6242 synchronized (mPackages) { 6243 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6244 return PackageParser.generateInstrumentationInfo(i, flags); 6245 } 6246 } 6247 6248 @Override 6249 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6250 String targetPackage, int flags) { 6251 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6252 } 6253 6254 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6255 int flags) { 6256 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6257 6258 // reader 6259 synchronized (mPackages) { 6260 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6261 while (i.hasNext()) { 6262 final PackageParser.Instrumentation p = i.next(); 6263 if (targetPackage == null 6264 || targetPackage.equals(p.info.targetPackage)) { 6265 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6266 flags); 6267 if (ii != null) { 6268 finalList.add(ii); 6269 } 6270 } 6271 } 6272 } 6273 6274 return finalList; 6275 } 6276 6277 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6278 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6279 if (overlays == null) { 6280 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6281 return; 6282 } 6283 for (PackageParser.Package opkg : overlays.values()) { 6284 // Not much to do if idmap fails: we already logged the error 6285 // and we certainly don't want to abort installation of pkg simply 6286 // because an overlay didn't fit properly. For these reasons, 6287 // ignore the return value of createIdmapForPackagePairLI. 6288 createIdmapForPackagePairLI(pkg, opkg); 6289 } 6290 } 6291 6292 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6293 PackageParser.Package opkg) { 6294 if (!opkg.mTrustedOverlay) { 6295 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6296 opkg.baseCodePath + ": overlay not trusted"); 6297 return false; 6298 } 6299 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6300 if (overlaySet == null) { 6301 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6302 opkg.baseCodePath + " but target package has no known overlays"); 6303 return false; 6304 } 6305 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6306 // TODO: generate idmap for split APKs 6307 try { 6308 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6309 } catch (InstallerException e) { 6310 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6311 + opkg.baseCodePath); 6312 return false; 6313 } 6314 PackageParser.Package[] overlayArray = 6315 overlaySet.values().toArray(new PackageParser.Package[0]); 6316 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6317 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6318 return p1.mOverlayPriority - p2.mOverlayPriority; 6319 } 6320 }; 6321 Arrays.sort(overlayArray, cmp); 6322 6323 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6324 int i = 0; 6325 for (PackageParser.Package p : overlayArray) { 6326 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6327 } 6328 return true; 6329 } 6330 6331 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6333 try { 6334 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6335 } finally { 6336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6337 } 6338 } 6339 6340 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6341 final File[] files = dir.listFiles(); 6342 if (ArrayUtils.isEmpty(files)) { 6343 Log.d(TAG, "No files in app dir " + dir); 6344 return; 6345 } 6346 6347 if (DEBUG_PACKAGE_SCANNING) { 6348 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6349 + " flags=0x" + Integer.toHexString(parseFlags)); 6350 } 6351 6352 for (File file : files) { 6353 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6354 && !PackageInstallerService.isStageName(file.getName()); 6355 if (!isPackage) { 6356 // Ignore entries which are not packages 6357 continue; 6358 } 6359 try { 6360 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6361 scanFlags, currentTime, null); 6362 } catch (PackageManagerException e) { 6363 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6364 6365 // Delete invalid userdata apps 6366 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6367 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6368 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6369 removeCodePathLI(file); 6370 } 6371 } 6372 } 6373 } 6374 6375 private static File getSettingsProblemFile() { 6376 File dataDir = Environment.getDataDirectory(); 6377 File systemDir = new File(dataDir, "system"); 6378 File fname = new File(systemDir, "uiderrors.txt"); 6379 return fname; 6380 } 6381 6382 static void reportSettingsProblem(int priority, String msg) { 6383 logCriticalInfo(priority, msg); 6384 } 6385 6386 static void logCriticalInfo(int priority, String msg) { 6387 Slog.println(priority, TAG, msg); 6388 EventLogTags.writePmCriticalInfo(msg); 6389 try { 6390 File fname = getSettingsProblemFile(); 6391 FileOutputStream out = new FileOutputStream(fname, true); 6392 PrintWriter pw = new FastPrintWriter(out); 6393 SimpleDateFormat formatter = new SimpleDateFormat(); 6394 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6395 pw.println(dateString + ": " + msg); 6396 pw.close(); 6397 FileUtils.setPermissions( 6398 fname.toString(), 6399 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6400 -1, -1); 6401 } catch (java.io.IOException e) { 6402 } 6403 } 6404 6405 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6406 int parseFlags) throws PackageManagerException { 6407 if (ps != null 6408 && ps.codePath.equals(srcFile) 6409 && ps.timeStamp == srcFile.lastModified() 6410 && !isCompatSignatureUpdateNeeded(pkg) 6411 && !isRecoverSignatureUpdateNeeded(pkg)) { 6412 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6413 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6414 ArraySet<PublicKey> signingKs; 6415 synchronized (mPackages) { 6416 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6417 } 6418 if (ps.signatures.mSignatures != null 6419 && ps.signatures.mSignatures.length != 0 6420 && signingKs != null) { 6421 // Optimization: reuse the existing cached certificates 6422 // if the package appears to be unchanged. 6423 pkg.mSignatures = ps.signatures.mSignatures; 6424 pkg.mSigningKeys = signingKs; 6425 return; 6426 } 6427 6428 Slog.w(TAG, "PackageSetting for " + ps.name 6429 + " is missing signatures. Collecting certs again to recover them."); 6430 } else { 6431 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6432 } 6433 6434 try { 6435 PackageParser.collectCertificates(pkg, parseFlags); 6436 } catch (PackageParserException e) { 6437 throw PackageManagerException.from(e); 6438 } 6439 } 6440 6441 /** 6442 * Traces a package scan. 6443 * @see #scanPackageLI(File, int, int, long, UserHandle) 6444 */ 6445 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6446 long currentTime, UserHandle user) throws PackageManagerException { 6447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6448 try { 6449 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6450 } finally { 6451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6452 } 6453 } 6454 6455 /** 6456 * Scans a package and returns the newly parsed package. 6457 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6458 */ 6459 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6460 long currentTime, UserHandle user) throws PackageManagerException { 6461 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6462 parseFlags |= mDefParseFlags; 6463 PackageParser pp = new PackageParser(); 6464 pp.setSeparateProcesses(mSeparateProcesses); 6465 pp.setOnlyCoreApps(mOnlyCore); 6466 pp.setDisplayMetrics(mMetrics); 6467 6468 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6469 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6470 } 6471 6472 final PackageParser.Package pkg; 6473 try { 6474 pkg = pp.parsePackage(scanFile, parseFlags); 6475 } catch (PackageParserException e) { 6476 throw PackageManagerException.from(e); 6477 } 6478 6479 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6480 } 6481 6482 /** 6483 * Scans a package and returns the newly parsed package. 6484 * @throws PackageManagerException on a parse error. 6485 */ 6486 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6487 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6488 throws PackageManagerException { 6489 // If the package has children and this is the first dive in the function 6490 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6491 // packages (parent and children) would be successfully scanned before the 6492 // actual scan since scanning mutates internal state and we want to atomically 6493 // install the package and its children. 6494 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6495 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6496 scanFlags |= SCAN_CHECK_ONLY; 6497 } 6498 } else { 6499 scanFlags &= ~SCAN_CHECK_ONLY; 6500 } 6501 6502 // Scan the parent 6503 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6504 scanFlags, currentTime, user); 6505 6506 // Scan the children 6507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6508 for (int i = 0; i < childCount; i++) { 6509 PackageParser.Package childPackage = pkg.childPackages.get(i); 6510 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6511 currentTime, user); 6512 } 6513 6514 6515 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6516 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6517 } 6518 6519 return scannedPkg; 6520 } 6521 6522 /** 6523 * Scans a package and returns the newly parsed package. 6524 * @throws PackageManagerException on a parse error. 6525 */ 6526 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6527 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6528 throws PackageManagerException { 6529 PackageSetting ps = null; 6530 PackageSetting updatedPkg; 6531 // reader 6532 synchronized (mPackages) { 6533 // Look to see if we already know about this package. 6534 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6535 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6536 // This package has been renamed to its original name. Let's 6537 // use that. 6538 ps = mSettings.peekPackageLPr(oldName); 6539 } 6540 // If there was no original package, see one for the real package name. 6541 if (ps == null) { 6542 ps = mSettings.peekPackageLPr(pkg.packageName); 6543 } 6544 // Check to see if this package could be hiding/updating a system 6545 // package. Must look for it either under the original or real 6546 // package name depending on our state. 6547 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6548 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6549 6550 // If this is a package we don't know about on the system partition, we 6551 // may need to remove disabled child packages on the system partition 6552 // or may need to not add child packages if the parent apk is updated 6553 // on the data partition and no longer defines this child package. 6554 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6555 // If this is a parent package for an updated system app and this system 6556 // app got an OTA update which no longer defines some of the child packages 6557 // we have to prune them from the disabled system packages. 6558 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6559 if (disabledPs != null) { 6560 final int scannedChildCount = (pkg.childPackages != null) 6561 ? pkg.childPackages.size() : 0; 6562 final int disabledChildCount = disabledPs.childPackageNames != null 6563 ? disabledPs.childPackageNames.size() : 0; 6564 for (int i = 0; i < disabledChildCount; i++) { 6565 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6566 boolean disabledPackageAvailable = false; 6567 for (int j = 0; j < scannedChildCount; j++) { 6568 PackageParser.Package childPkg = pkg.childPackages.get(j); 6569 if (childPkg.packageName.equals(disabledChildPackageName)) { 6570 disabledPackageAvailable = true; 6571 break; 6572 } 6573 } 6574 if (!disabledPackageAvailable) { 6575 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6576 } 6577 } 6578 } 6579 } 6580 } 6581 6582 boolean updatedPkgBetter = false; 6583 // First check if this is a system package that may involve an update 6584 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6585 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6586 // it needs to drop FLAG_PRIVILEGED. 6587 if (locationIsPrivileged(scanFile)) { 6588 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6589 } else { 6590 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6591 } 6592 6593 if (ps != null && !ps.codePath.equals(scanFile)) { 6594 // The path has changed from what was last scanned... check the 6595 // version of the new path against what we have stored to determine 6596 // what to do. 6597 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6598 if (pkg.mVersionCode <= ps.versionCode) { 6599 // The system package has been updated and the code path does not match 6600 // Ignore entry. Skip it. 6601 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6602 + " ignored: updated version " + ps.versionCode 6603 + " better than this " + pkg.mVersionCode); 6604 if (!updatedPkg.codePath.equals(scanFile)) { 6605 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6606 + ps.name + " changing from " + updatedPkg.codePathString 6607 + " to " + scanFile); 6608 updatedPkg.codePath = scanFile; 6609 updatedPkg.codePathString = scanFile.toString(); 6610 updatedPkg.resourcePath = scanFile; 6611 updatedPkg.resourcePathString = scanFile.toString(); 6612 } 6613 updatedPkg.pkg = pkg; 6614 updatedPkg.versionCode = pkg.mVersionCode; 6615 6616 // Update the disabled system child packages to point to the package too. 6617 final int childCount = updatedPkg.childPackageNames != null 6618 ? updatedPkg.childPackageNames.size() : 0; 6619 for (int i = 0; i < childCount; i++) { 6620 String childPackageName = updatedPkg.childPackageNames.get(i); 6621 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6622 childPackageName); 6623 if (updatedChildPkg != null) { 6624 updatedChildPkg.pkg = pkg; 6625 updatedChildPkg.versionCode = pkg.mVersionCode; 6626 } 6627 } 6628 6629 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6630 + scanFile + " ignored: updated version " + ps.versionCode 6631 + " better than this " + pkg.mVersionCode); 6632 } else { 6633 // The current app on the system partition is better than 6634 // what we have updated to on the data partition; switch 6635 // back to the system partition version. 6636 // At this point, its safely assumed that package installation for 6637 // apps in system partition will go through. If not there won't be a working 6638 // version of the app 6639 // writer 6640 synchronized (mPackages) { 6641 // Just remove the loaded entries from package lists. 6642 mPackages.remove(ps.name); 6643 } 6644 6645 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6646 + " reverting from " + ps.codePathString 6647 + ": new version " + pkg.mVersionCode 6648 + " better than installed " + ps.versionCode); 6649 6650 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6651 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6652 synchronized (mInstallLock) { 6653 args.cleanUpResourcesLI(); 6654 } 6655 synchronized (mPackages) { 6656 mSettings.enableSystemPackageLPw(ps.name); 6657 } 6658 updatedPkgBetter = true; 6659 } 6660 } 6661 } 6662 6663 if (updatedPkg != null) { 6664 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6665 // initially 6666 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6667 6668 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6669 // flag set initially 6670 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6671 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6672 } 6673 } 6674 6675 // Verify certificates against what was last scanned 6676 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6677 6678 /* 6679 * A new system app appeared, but we already had a non-system one of the 6680 * same name installed earlier. 6681 */ 6682 boolean shouldHideSystemApp = false; 6683 if (updatedPkg == null && ps != null 6684 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6685 /* 6686 * Check to make sure the signatures match first. If they don't, 6687 * wipe the installed application and its data. 6688 */ 6689 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6690 != PackageManager.SIGNATURE_MATCH) { 6691 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6692 + " signatures don't match existing userdata copy; removing"); 6693 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6694 ps = null; 6695 } else { 6696 /* 6697 * If the newly-added system app is an older version than the 6698 * already installed version, hide it. It will be scanned later 6699 * and re-added like an update. 6700 */ 6701 if (pkg.mVersionCode <= ps.versionCode) { 6702 shouldHideSystemApp = true; 6703 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6704 + " but new version " + pkg.mVersionCode + " better than installed " 6705 + ps.versionCode + "; hiding system"); 6706 } else { 6707 /* 6708 * The newly found system app is a newer version that the 6709 * one previously installed. Simply remove the 6710 * already-installed application and replace it with our own 6711 * while keeping the application data. 6712 */ 6713 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6714 + " reverting from " + ps.codePathString + ": new version " 6715 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6716 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6717 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6718 synchronized (mInstallLock) { 6719 args.cleanUpResourcesLI(); 6720 } 6721 } 6722 } 6723 } 6724 6725 // The apk is forward locked (not public) if its code and resources 6726 // are kept in different files. (except for app in either system or 6727 // vendor path). 6728 // TODO grab this value from PackageSettings 6729 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6730 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6731 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6732 } 6733 } 6734 6735 // TODO: extend to support forward-locked splits 6736 String resourcePath = null; 6737 String baseResourcePath = null; 6738 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6739 if (ps != null && ps.resourcePathString != null) { 6740 resourcePath = ps.resourcePathString; 6741 baseResourcePath = ps.resourcePathString; 6742 } else { 6743 // Should not happen at all. Just log an error. 6744 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6745 } 6746 } else { 6747 resourcePath = pkg.codePath; 6748 baseResourcePath = pkg.baseCodePath; 6749 } 6750 6751 // Set application objects path explicitly. 6752 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6753 pkg.setApplicationInfoCodePath(pkg.codePath); 6754 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6755 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6756 pkg.setApplicationInfoResourcePath(resourcePath); 6757 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6758 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6759 6760 // Note that we invoke the following method only if we are about to unpack an application 6761 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6762 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6763 6764 /* 6765 * If the system app should be overridden by a previously installed 6766 * data, hide the system app now and let the /data/app scan pick it up 6767 * again. 6768 */ 6769 if (shouldHideSystemApp) { 6770 synchronized (mPackages) { 6771 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6772 } 6773 } 6774 6775 return scannedPkg; 6776 } 6777 6778 private static String fixProcessName(String defProcessName, 6779 String processName, int uid) { 6780 if (processName == null) { 6781 return defProcessName; 6782 } 6783 return processName; 6784 } 6785 6786 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6787 throws PackageManagerException { 6788 if (pkgSetting.signatures.mSignatures != null) { 6789 // Already existing package. Make sure signatures match 6790 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6791 == PackageManager.SIGNATURE_MATCH; 6792 if (!match) { 6793 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6794 == PackageManager.SIGNATURE_MATCH; 6795 } 6796 if (!match) { 6797 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6798 == PackageManager.SIGNATURE_MATCH; 6799 } 6800 if (!match) { 6801 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6802 + pkg.packageName + " signatures do not match the " 6803 + "previously installed version; ignoring!"); 6804 } 6805 } 6806 6807 // Check for shared user signatures 6808 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6809 // Already existing package. Make sure signatures match 6810 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6811 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6812 if (!match) { 6813 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6814 == PackageManager.SIGNATURE_MATCH; 6815 } 6816 if (!match) { 6817 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6818 == PackageManager.SIGNATURE_MATCH; 6819 } 6820 if (!match) { 6821 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6822 "Package " + pkg.packageName 6823 + " has no signatures that match those in shared user " 6824 + pkgSetting.sharedUser.name + "; ignoring!"); 6825 } 6826 } 6827 } 6828 6829 /** 6830 * Enforces that only the system UID or root's UID can call a method exposed 6831 * via Binder. 6832 * 6833 * @param message used as message if SecurityException is thrown 6834 * @throws SecurityException if the caller is not system or root 6835 */ 6836 private static final void enforceSystemOrRoot(String message) { 6837 final int uid = Binder.getCallingUid(); 6838 if (uid != Process.SYSTEM_UID && uid != 0) { 6839 throw new SecurityException(message); 6840 } 6841 } 6842 6843 @Override 6844 public void performFstrimIfNeeded() { 6845 enforceSystemOrRoot("Only the system can request fstrim"); 6846 6847 // Before everything else, see whether we need to fstrim. 6848 try { 6849 IMountService ms = PackageHelper.getMountService(); 6850 if (ms != null) { 6851 final boolean isUpgrade = isUpgrade(); 6852 boolean doTrim = isUpgrade; 6853 if (doTrim) { 6854 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6855 } else { 6856 final long interval = android.provider.Settings.Global.getLong( 6857 mContext.getContentResolver(), 6858 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6859 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6860 if (interval > 0) { 6861 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6862 if (timeSinceLast > interval) { 6863 doTrim = true; 6864 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6865 + "; running immediately"); 6866 } 6867 } 6868 } 6869 if (doTrim) { 6870 if (!isFirstBoot()) { 6871 try { 6872 ActivityManagerNative.getDefault().showBootMessage( 6873 mContext.getResources().getString( 6874 R.string.android_upgrading_fstrim), true); 6875 } catch (RemoteException e) { 6876 } 6877 } 6878 ms.runMaintenance(); 6879 } 6880 } else { 6881 Slog.e(TAG, "Mount service unavailable!"); 6882 } 6883 } catch (RemoteException e) { 6884 // Can't happen; MountService is local 6885 } 6886 } 6887 6888 @Override 6889 public void extractPackagesIfNeeded() { 6890 enforceSystemOrRoot("Only the system can request package extraction"); 6891 6892 // Extract pacakges only if profile-guided compilation is enabled because 6893 // otherwise BackgroundDexOptService will not dexopt them later. 6894 if (!isUpgrade()) { 6895 return; 6896 } 6897 6898 List<PackageParser.Package> pkgs; 6899 synchronized (mPackages) { 6900 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6901 } 6902 6903 int curr = 0; 6904 int total = pkgs.size(); 6905 for (PackageParser.Package pkg : pkgs) { 6906 curr++; 6907 6908 if (DEBUG_DEXOPT) { 6909 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6910 } 6911 6912 if (!isFirstBoot()) { 6913 try { 6914 ActivityManagerNative.getDefault().showBootMessage( 6915 mContext.getResources().getString(R.string.android_upgrading_apk, 6916 curr, total), true); 6917 } catch (RemoteException e) { 6918 } 6919 } 6920 6921 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6922 performDexOpt(pkg.packageName, null /* instructionSet */, 6923 false /* useProfiles */, true /* extractOnly */, false /* force */); 6924 } 6925 } 6926 } 6927 6928 @Override 6929 public void notifyPackageUse(String packageName) { 6930 synchronized (mPackages) { 6931 PackageParser.Package p = mPackages.get(packageName); 6932 if (p == null) { 6933 return; 6934 } 6935 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6936 } 6937 } 6938 6939 // TODO: this is not used nor needed. Delete it. 6940 @Override 6941 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6942 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6943 false /* extractOnly */, false /* force */); 6944 } 6945 6946 @Override 6947 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6948 boolean extractOnly, boolean force) { 6949 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6950 } 6951 6952 private boolean performDexOptTraced(String packageName, String instructionSet, 6953 boolean useProfiles, boolean extractOnly, boolean force) { 6954 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6955 try { 6956 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6957 force); 6958 } finally { 6959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6960 } 6961 } 6962 6963 private boolean performDexOptInternal(String packageName, String instructionSet, 6964 boolean useProfiles, boolean extractOnly, boolean force) { 6965 PackageParser.Package p; 6966 final String targetInstructionSet; 6967 synchronized (mPackages) { 6968 p = mPackages.get(packageName); 6969 if (p == null) { 6970 return false; 6971 } 6972 mPackageUsage.write(false); 6973 6974 targetInstructionSet = instructionSet != null ? instructionSet : 6975 getPrimaryInstructionSet(p.applicationInfo); 6976 } 6977 long callingId = Binder.clearCallingIdentity(); 6978 try { 6979 synchronized (mInstallLock) { 6980 final String[] instructionSets = new String[] { targetInstructionSet }; 6981 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6982 useProfiles, extractOnly, force); 6983 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6984 } 6985 } finally { 6986 Binder.restoreCallingIdentity(callingId); 6987 } 6988 } 6989 6990 public ArraySet<String> getOptimizablePackages() { 6991 ArraySet<String> pkgs = new ArraySet<String>(); 6992 synchronized (mPackages) { 6993 for (PackageParser.Package p : mPackages.values()) { 6994 if (PackageDexOptimizer.canOptimizePackage(p)) { 6995 pkgs.add(p.packageName); 6996 } 6997 } 6998 } 6999 return pkgs; 7000 } 7001 7002 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7003 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 7004 // Select the dex optimizer based on the force parameter. 7005 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7006 // allocate an object here. 7007 PackageDexOptimizer pdo = force 7008 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7009 : mPackageDexOptimizer; 7010 7011 // Optimize all dependencies first. Note: we ignore the return value and march on 7012 // on errors. 7013 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7014 if (!deps.isEmpty()) { 7015 for (PackageParser.Package depPackage : deps) { 7016 // TODO: Analyze and investigate if we (should) profile libraries. 7017 // Currently this will do a full compilation of the library. 7018 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 7019 false /* extractOnly */); 7020 } 7021 } 7022 7023 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 7024 } 7025 7026 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7027 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7028 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7029 Set<String> collectedNames = new HashSet<>(); 7030 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7031 7032 retValue.remove(p); 7033 7034 return retValue; 7035 } else { 7036 return Collections.emptyList(); 7037 } 7038 } 7039 7040 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7041 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7042 if (!collectedNames.contains(p.packageName)) { 7043 collectedNames.add(p.packageName); 7044 collected.add(p); 7045 7046 if (p.usesLibraries != null) { 7047 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7048 } 7049 if (p.usesOptionalLibraries != null) { 7050 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7051 collectedNames); 7052 } 7053 } 7054 } 7055 7056 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7057 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7058 for (String libName : libs) { 7059 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7060 if (libPkg != null) { 7061 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7062 } 7063 } 7064 } 7065 7066 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7067 synchronized (mPackages) { 7068 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7069 if (lib != null && lib.apk != null) { 7070 return mPackages.get(lib.apk); 7071 } 7072 } 7073 return null; 7074 } 7075 7076 public void shutdown() { 7077 mPackageUsage.write(true); 7078 } 7079 7080 @Override 7081 public void forceDexOpt(String packageName) { 7082 enforceSystemOrRoot("forceDexOpt"); 7083 7084 PackageParser.Package pkg; 7085 synchronized (mPackages) { 7086 pkg = mPackages.get(packageName); 7087 if (pkg == null) { 7088 throw new IllegalArgumentException("Unknown package: " + packageName); 7089 } 7090 } 7091 7092 synchronized (mInstallLock) { 7093 final String[] instructionSets = new String[] { 7094 getPrimaryInstructionSet(pkg.applicationInfo) }; 7095 7096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7097 7098 // Whoever is calling forceDexOpt wants a fully compiled package. 7099 // Don't use profiles since that may cause compilation to be skipped. 7100 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7101 false /* useProfiles */, false /* extractOnly */, true /* force */); 7102 7103 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7104 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7105 throw new IllegalStateException("Failed to dexopt: " + res); 7106 } 7107 } 7108 } 7109 7110 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7111 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7112 Slog.w(TAG, "Unable to update from " + oldPkg.name 7113 + " to " + newPkg.packageName 7114 + ": old package not in system partition"); 7115 return false; 7116 } else if (mPackages.get(oldPkg.name) != null) { 7117 Slog.w(TAG, "Unable to update from " + oldPkg.name 7118 + " to " + newPkg.packageName 7119 + ": old package still exists"); 7120 return false; 7121 } 7122 return true; 7123 } 7124 7125 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7126 // TODO: triage flags as part of 26466827 7127 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7128 7129 boolean res = true; 7130 final int[] users = sUserManager.getUserIds(); 7131 for (int user : users) { 7132 try { 7133 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7134 } catch (InstallerException e) { 7135 Slog.w(TAG, "Failed to delete data directory", e); 7136 res = false; 7137 } 7138 } 7139 return res; 7140 } 7141 7142 void removeCodePathLI(File codePath) { 7143 if (codePath.isDirectory()) { 7144 try { 7145 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7146 } catch (InstallerException e) { 7147 Slog.w(TAG, "Failed to remove code path", e); 7148 } 7149 } else { 7150 codePath.delete(); 7151 } 7152 } 7153 7154 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7155 try { 7156 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7157 } catch (InstallerException e) { 7158 Slog.w(TAG, "Failed to destroy app data", e); 7159 } 7160 } 7161 7162 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7163 int appId, String seinfo) { 7164 try { 7165 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7166 } catch (InstallerException e) { 7167 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7168 } 7169 } 7170 7171 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7172 final PackageParser.Package pkg; 7173 synchronized (mPackages) { 7174 pkg = mPackages.get(packageName); 7175 } 7176 if (pkg == null) { 7177 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7178 return; 7179 } 7180 deleteCodeCacheDirsLI(pkg); 7181 } 7182 7183 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7184 // TODO: triage flags as part of 26466827 7185 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7186 7187 int[] users = sUserManager.getUserIds(); 7188 int res = 0; 7189 for (int user : users) { 7190 // Remove the parent code cache 7191 try { 7192 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7193 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7194 } catch (InstallerException e) { 7195 Slog.w(TAG, "Failed to delete code cache directory", e); 7196 } 7197 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7198 for (int i = 0; i < childCount; i++) { 7199 PackageParser.Package childPkg = pkg.childPackages.get(i); 7200 // Remove the child code cache 7201 try { 7202 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7203 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7204 } catch (InstallerException e) { 7205 Slog.w(TAG, "Failed to delete code cache directory", e); 7206 } 7207 } 7208 } 7209 } 7210 7211 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7212 long lastUpdateTime) { 7213 // Set parent install/update time 7214 PackageSetting ps = (PackageSetting) pkg.mExtras; 7215 if (ps != null) { 7216 ps.firstInstallTime = firstInstallTime; 7217 ps.lastUpdateTime = lastUpdateTime; 7218 } 7219 // Set children install/update time 7220 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7221 for (int i = 0; i < childCount; i++) { 7222 PackageParser.Package childPkg = pkg.childPackages.get(i); 7223 ps = (PackageSetting) childPkg.mExtras; 7224 if (ps != null) { 7225 ps.firstInstallTime = firstInstallTime; 7226 ps.lastUpdateTime = lastUpdateTime; 7227 } 7228 } 7229 } 7230 7231 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7232 PackageParser.Package changingLib) { 7233 if (file.path != null) { 7234 usesLibraryFiles.add(file.path); 7235 return; 7236 } 7237 PackageParser.Package p = mPackages.get(file.apk); 7238 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7239 // If we are doing this while in the middle of updating a library apk, 7240 // then we need to make sure to use that new apk for determining the 7241 // dependencies here. (We haven't yet finished committing the new apk 7242 // to the package manager state.) 7243 if (p == null || p.packageName.equals(changingLib.packageName)) { 7244 p = changingLib; 7245 } 7246 } 7247 if (p != null) { 7248 usesLibraryFiles.addAll(p.getAllCodePaths()); 7249 } 7250 } 7251 7252 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7253 PackageParser.Package changingLib) throws PackageManagerException { 7254 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7255 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7256 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7257 for (int i=0; i<N; i++) { 7258 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7259 if (file == null) { 7260 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7261 "Package " + pkg.packageName + " requires unavailable shared library " 7262 + pkg.usesLibraries.get(i) + "; failing!"); 7263 } 7264 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7265 } 7266 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7267 for (int i=0; i<N; i++) { 7268 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7269 if (file == null) { 7270 Slog.w(TAG, "Package " + pkg.packageName 7271 + " desires unavailable shared library " 7272 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7273 } else { 7274 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7275 } 7276 } 7277 N = usesLibraryFiles.size(); 7278 if (N > 0) { 7279 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7280 } else { 7281 pkg.usesLibraryFiles = null; 7282 } 7283 } 7284 } 7285 7286 private static boolean hasString(List<String> list, List<String> which) { 7287 if (list == null) { 7288 return false; 7289 } 7290 for (int i=list.size()-1; i>=0; i--) { 7291 for (int j=which.size()-1; j>=0; j--) { 7292 if (which.get(j).equals(list.get(i))) { 7293 return true; 7294 } 7295 } 7296 } 7297 return false; 7298 } 7299 7300 private void updateAllSharedLibrariesLPw() { 7301 for (PackageParser.Package pkg : mPackages.values()) { 7302 try { 7303 updateSharedLibrariesLPw(pkg, null); 7304 } catch (PackageManagerException e) { 7305 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7306 } 7307 } 7308 } 7309 7310 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7311 PackageParser.Package changingPkg) { 7312 ArrayList<PackageParser.Package> res = null; 7313 for (PackageParser.Package pkg : mPackages.values()) { 7314 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7315 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7316 if (res == null) { 7317 res = new ArrayList<PackageParser.Package>(); 7318 } 7319 res.add(pkg); 7320 try { 7321 updateSharedLibrariesLPw(pkg, changingPkg); 7322 } catch (PackageManagerException e) { 7323 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7324 } 7325 } 7326 } 7327 return res; 7328 } 7329 7330 /** 7331 * Derive the value of the {@code cpuAbiOverride} based on the provided 7332 * value and an optional stored value from the package settings. 7333 */ 7334 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7335 String cpuAbiOverride = null; 7336 7337 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7338 cpuAbiOverride = null; 7339 } else if (abiOverride != null) { 7340 cpuAbiOverride = abiOverride; 7341 } else if (settings != null) { 7342 cpuAbiOverride = settings.cpuAbiOverrideString; 7343 } 7344 7345 return cpuAbiOverride; 7346 } 7347 7348 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7349 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7351 // If the package has children and this is the first dive in the function 7352 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7353 // whether all packages (parent and children) would be successfully scanned 7354 // before the actual scan since scanning mutates internal state and we want 7355 // to atomically install the package and its children. 7356 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7357 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7358 scanFlags |= SCAN_CHECK_ONLY; 7359 } 7360 } else { 7361 scanFlags &= ~SCAN_CHECK_ONLY; 7362 } 7363 7364 final PackageParser.Package scannedPkg; 7365 try { 7366 // Scan the parent 7367 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7368 // Scan the children 7369 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7370 for (int i = 0; i < childCount; i++) { 7371 PackageParser.Package childPkg = pkg.childPackages.get(i); 7372 scanPackageLI(childPkg, parseFlags, 7373 scanFlags, currentTime, user); 7374 } 7375 } finally { 7376 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7377 } 7378 7379 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7380 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7381 } 7382 7383 return scannedPkg; 7384 } 7385 7386 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7387 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7388 boolean success = false; 7389 try { 7390 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7391 currentTime, user); 7392 success = true; 7393 return res; 7394 } finally { 7395 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7396 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7397 } 7398 } 7399 } 7400 7401 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7402 int scanFlags, long currentTime, UserHandle user) 7403 throws PackageManagerException { 7404 final File scanFile = new File(pkg.codePath); 7405 if (pkg.applicationInfo.getCodePath() == null || 7406 pkg.applicationInfo.getResourcePath() == null) { 7407 // Bail out. The resource and code paths haven't been set. 7408 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7409 "Code and resource paths haven't been set correctly"); 7410 } 7411 7412 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7413 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7414 } else { 7415 // Only allow system apps to be flagged as core apps. 7416 pkg.coreApp = false; 7417 } 7418 7419 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7420 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7421 } 7422 7423 if (mCustomResolverComponentName != null && 7424 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7425 setUpCustomResolverActivity(pkg); 7426 } 7427 7428 if (pkg.packageName.equals("android")) { 7429 synchronized (mPackages) { 7430 if (mAndroidApplication != null) { 7431 Slog.w(TAG, "*************************************************"); 7432 Slog.w(TAG, "Core android package being redefined. Skipping."); 7433 Slog.w(TAG, " file=" + scanFile); 7434 Slog.w(TAG, "*************************************************"); 7435 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7436 "Core android package being redefined. Skipping."); 7437 } 7438 7439 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7440 // Set up information for our fall-back user intent resolution activity. 7441 mPlatformPackage = pkg; 7442 pkg.mVersionCode = mSdkVersion; 7443 mAndroidApplication = pkg.applicationInfo; 7444 7445 if (!mResolverReplaced) { 7446 mResolveActivity.applicationInfo = mAndroidApplication; 7447 mResolveActivity.name = ResolverActivity.class.getName(); 7448 mResolveActivity.packageName = mAndroidApplication.packageName; 7449 mResolveActivity.processName = "system:ui"; 7450 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7451 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7452 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7453 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7454 mResolveActivity.exported = true; 7455 mResolveActivity.enabled = true; 7456 mResolveInfo.activityInfo = mResolveActivity; 7457 mResolveInfo.priority = 0; 7458 mResolveInfo.preferredOrder = 0; 7459 mResolveInfo.match = 0; 7460 mResolveComponentName = new ComponentName( 7461 mAndroidApplication.packageName, mResolveActivity.name); 7462 } 7463 } 7464 } 7465 } 7466 7467 if (DEBUG_PACKAGE_SCANNING) { 7468 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7469 Log.d(TAG, "Scanning package " + pkg.packageName); 7470 } 7471 7472 synchronized (mPackages) { 7473 if (mPackages.containsKey(pkg.packageName) 7474 || mSharedLibraries.containsKey(pkg.packageName)) { 7475 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7476 "Application package " + pkg.packageName 7477 + " already installed. Skipping duplicate."); 7478 } 7479 7480 // If we're only installing presumed-existing packages, require that the 7481 // scanned APK is both already known and at the path previously established 7482 // for it. Previously unknown packages we pick up normally, but if we have an 7483 // a priori expectation about this package's install presence, enforce it. 7484 // With a singular exception for new system packages. When an OTA contains 7485 // a new system package, we allow the codepath to change from a system location 7486 // to the user-installed location. If we don't allow this change, any newer, 7487 // user-installed version of the application will be ignored. 7488 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7489 if (mExpectingBetter.containsKey(pkg.packageName)) { 7490 logCriticalInfo(Log.WARN, 7491 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7492 } else { 7493 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7494 if (known != null) { 7495 if (DEBUG_PACKAGE_SCANNING) { 7496 Log.d(TAG, "Examining " + pkg.codePath 7497 + " and requiring known paths " + known.codePathString 7498 + " & " + known.resourcePathString); 7499 } 7500 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7501 || !pkg.applicationInfo.getResourcePath().equals( 7502 known.resourcePathString)) { 7503 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7504 "Application package " + pkg.packageName 7505 + " found at " + pkg.applicationInfo.getCodePath() 7506 + " but expected at " + known.codePathString 7507 + "; ignoring."); 7508 } 7509 } 7510 } 7511 } 7512 } 7513 7514 // Initialize package source and resource directories 7515 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7516 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7517 7518 SharedUserSetting suid = null; 7519 PackageSetting pkgSetting = null; 7520 7521 if (!isSystemApp(pkg)) { 7522 // Only system apps can use these features. 7523 pkg.mOriginalPackages = null; 7524 pkg.mRealPackage = null; 7525 pkg.mAdoptPermissions = null; 7526 } 7527 7528 // Getting the package setting may have a side-effect, so if we 7529 // are only checking if scan would succeed, stash a copy of the 7530 // old setting to restore at the end. 7531 PackageSetting nonMutatedPs = null; 7532 7533 // writer 7534 synchronized (mPackages) { 7535 if (pkg.mSharedUserId != null) { 7536 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7537 if (suid == null) { 7538 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7539 "Creating application package " + pkg.packageName 7540 + " for shared user failed"); 7541 } 7542 if (DEBUG_PACKAGE_SCANNING) { 7543 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7544 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7545 + "): packages=" + suid.packages); 7546 } 7547 } 7548 7549 // Check if we are renaming from an original package name. 7550 PackageSetting origPackage = null; 7551 String realName = null; 7552 if (pkg.mOriginalPackages != null) { 7553 // This package may need to be renamed to a previously 7554 // installed name. Let's check on that... 7555 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7556 if (pkg.mOriginalPackages.contains(renamed)) { 7557 // This package had originally been installed as the 7558 // original name, and we have already taken care of 7559 // transitioning to the new one. Just update the new 7560 // one to continue using the old name. 7561 realName = pkg.mRealPackage; 7562 if (!pkg.packageName.equals(renamed)) { 7563 // Callers into this function may have already taken 7564 // care of renaming the package; only do it here if 7565 // it is not already done. 7566 pkg.setPackageName(renamed); 7567 } 7568 7569 } else { 7570 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7571 if ((origPackage = mSettings.peekPackageLPr( 7572 pkg.mOriginalPackages.get(i))) != null) { 7573 // We do have the package already installed under its 7574 // original name... should we use it? 7575 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7576 // New package is not compatible with original. 7577 origPackage = null; 7578 continue; 7579 } else if (origPackage.sharedUser != null) { 7580 // Make sure uid is compatible between packages. 7581 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7582 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7583 + " to " + pkg.packageName + ": old uid " 7584 + origPackage.sharedUser.name 7585 + " differs from " + pkg.mSharedUserId); 7586 origPackage = null; 7587 continue; 7588 } 7589 } else { 7590 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7591 + pkg.packageName + " to old name " + origPackage.name); 7592 } 7593 break; 7594 } 7595 } 7596 } 7597 } 7598 7599 if (mTransferedPackages.contains(pkg.packageName)) { 7600 Slog.w(TAG, "Package " + pkg.packageName 7601 + " was transferred to another, but its .apk remains"); 7602 } 7603 7604 // See comments in nonMutatedPs declaration 7605 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7606 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7607 if (foundPs != null) { 7608 nonMutatedPs = new PackageSetting(foundPs); 7609 } 7610 } 7611 7612 // Just create the setting, don't add it yet. For already existing packages 7613 // the PkgSetting exists already and doesn't have to be created. 7614 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7615 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7616 pkg.applicationInfo.primaryCpuAbi, 7617 pkg.applicationInfo.secondaryCpuAbi, 7618 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7619 user, false); 7620 if (pkgSetting == null) { 7621 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7622 "Creating application package " + pkg.packageName + " failed"); 7623 } 7624 7625 if (pkgSetting.origPackage != null) { 7626 // If we are first transitioning from an original package, 7627 // fix up the new package's name now. We need to do this after 7628 // looking up the package under its new name, so getPackageLP 7629 // can take care of fiddling things correctly. 7630 pkg.setPackageName(origPackage.name); 7631 7632 // File a report about this. 7633 String msg = "New package " + pkgSetting.realName 7634 + " renamed to replace old package " + pkgSetting.name; 7635 reportSettingsProblem(Log.WARN, msg); 7636 7637 // Make a note of it. 7638 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7639 mTransferedPackages.add(origPackage.name); 7640 } 7641 7642 // No longer need to retain this. 7643 pkgSetting.origPackage = null; 7644 } 7645 7646 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7647 // Make a note of it. 7648 mTransferedPackages.add(pkg.packageName); 7649 } 7650 7651 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7652 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7653 } 7654 7655 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7656 // Check all shared libraries and map to their actual file path. 7657 // We only do this here for apps not on a system dir, because those 7658 // are the only ones that can fail an install due to this. We 7659 // will take care of the system apps by updating all of their 7660 // library paths after the scan is done. 7661 updateSharedLibrariesLPw(pkg, null); 7662 } 7663 7664 if (mFoundPolicyFile) { 7665 SELinuxMMAC.assignSeinfoValue(pkg); 7666 } 7667 7668 pkg.applicationInfo.uid = pkgSetting.appId; 7669 pkg.mExtras = pkgSetting; 7670 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7671 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7672 // We just determined the app is signed correctly, so bring 7673 // over the latest parsed certs. 7674 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7675 } else { 7676 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7677 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7678 "Package " + pkg.packageName + " upgrade keys do not match the " 7679 + "previously installed version"); 7680 } else { 7681 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7682 String msg = "System package " + pkg.packageName 7683 + " signature changed; retaining data."; 7684 reportSettingsProblem(Log.WARN, msg); 7685 } 7686 } 7687 } else { 7688 try { 7689 verifySignaturesLP(pkgSetting, pkg); 7690 // We just determined the app is signed correctly, so bring 7691 // over the latest parsed certs. 7692 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7693 } catch (PackageManagerException e) { 7694 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7695 throw e; 7696 } 7697 // The signature has changed, but this package is in the system 7698 // image... let's recover! 7699 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7700 // However... if this package is part of a shared user, but it 7701 // doesn't match the signature of the shared user, let's fail. 7702 // What this means is that you can't change the signatures 7703 // associated with an overall shared user, which doesn't seem all 7704 // that unreasonable. 7705 if (pkgSetting.sharedUser != null) { 7706 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7707 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7708 throw new PackageManagerException( 7709 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7710 "Signature mismatch for shared user: " 7711 + pkgSetting.sharedUser); 7712 } 7713 } 7714 // File a report about this. 7715 String msg = "System package " + pkg.packageName 7716 + " signature changed; retaining data."; 7717 reportSettingsProblem(Log.WARN, msg); 7718 } 7719 } 7720 // Verify that this new package doesn't have any content providers 7721 // that conflict with existing packages. Only do this if the 7722 // package isn't already installed, since we don't want to break 7723 // things that are installed. 7724 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7725 final int N = pkg.providers.size(); 7726 int i; 7727 for (i=0; i<N; i++) { 7728 PackageParser.Provider p = pkg.providers.get(i); 7729 if (p.info.authority != null) { 7730 String names[] = p.info.authority.split(";"); 7731 for (int j = 0; j < names.length; j++) { 7732 if (mProvidersByAuthority.containsKey(names[j])) { 7733 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7734 final String otherPackageName = 7735 ((other != null && other.getComponentName() != null) ? 7736 other.getComponentName().getPackageName() : "?"); 7737 throw new PackageManagerException( 7738 INSTALL_FAILED_CONFLICTING_PROVIDER, 7739 "Can't install because provider name " + names[j] 7740 + " (in package " + pkg.applicationInfo.packageName 7741 + ") is already used by " + otherPackageName); 7742 } 7743 } 7744 } 7745 } 7746 } 7747 7748 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7749 // This package wants to adopt ownership of permissions from 7750 // another package. 7751 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7752 final String origName = pkg.mAdoptPermissions.get(i); 7753 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7754 if (orig != null) { 7755 if (verifyPackageUpdateLPr(orig, pkg)) { 7756 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7757 + pkg.packageName); 7758 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7759 } 7760 } 7761 } 7762 } 7763 } 7764 7765 final String pkgName = pkg.packageName; 7766 7767 final long scanFileTime = scanFile.lastModified(); 7768 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7769 pkg.applicationInfo.processName = fixProcessName( 7770 pkg.applicationInfo.packageName, 7771 pkg.applicationInfo.processName, 7772 pkg.applicationInfo.uid); 7773 7774 if (pkg != mPlatformPackage) { 7775 // Get all of our default paths setup 7776 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7777 } 7778 7779 final String path = scanFile.getPath(); 7780 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7781 7782 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7783 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7784 7785 // Some system apps still use directory structure for native libraries 7786 // in which case we might end up not detecting abi solely based on apk 7787 // structure. Try to detect abi based on directory structure. 7788 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7789 pkg.applicationInfo.primaryCpuAbi == null) { 7790 setBundledAppAbisAndRoots(pkg, pkgSetting); 7791 setNativeLibraryPaths(pkg); 7792 } 7793 7794 } else { 7795 if ((scanFlags & SCAN_MOVE) != 0) { 7796 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7797 // but we already have this packages package info in the PackageSetting. We just 7798 // use that and derive the native library path based on the new codepath. 7799 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7800 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7801 } 7802 7803 // Set native library paths again. For moves, the path will be updated based on the 7804 // ABIs we've determined above. For non-moves, the path will be updated based on the 7805 // ABIs we determined during compilation, but the path will depend on the final 7806 // package path (after the rename away from the stage path). 7807 setNativeLibraryPaths(pkg); 7808 } 7809 7810 // This is a special case for the "system" package, where the ABI is 7811 // dictated by the zygote configuration (and init.rc). We should keep track 7812 // of this ABI so that we can deal with "normal" applications that run under 7813 // the same UID correctly. 7814 if (mPlatformPackage == pkg) { 7815 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7816 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7817 } 7818 7819 // If there's a mismatch between the abi-override in the package setting 7820 // and the abiOverride specified for the install. Warn about this because we 7821 // would've already compiled the app without taking the package setting into 7822 // account. 7823 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7824 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7825 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7826 " for package " + pkg.packageName); 7827 } 7828 } 7829 7830 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7831 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7832 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7833 7834 // Copy the derived override back to the parsed package, so that we can 7835 // update the package settings accordingly. 7836 pkg.cpuAbiOverride = cpuAbiOverride; 7837 7838 if (DEBUG_ABI_SELECTION) { 7839 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7840 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7841 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7842 } 7843 7844 // Push the derived path down into PackageSettings so we know what to 7845 // clean up at uninstall time. 7846 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7847 7848 if (DEBUG_ABI_SELECTION) { 7849 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7850 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7851 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7852 } 7853 7854 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7855 // We don't do this here during boot because we can do it all 7856 // at once after scanning all existing packages. 7857 // 7858 // We also do this *before* we perform dexopt on this package, so that 7859 // we can avoid redundant dexopts, and also to make sure we've got the 7860 // code and package path correct. 7861 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7862 pkg, true /* boot complete */); 7863 } 7864 7865 if (mFactoryTest && pkg.requestedPermissions.contains( 7866 android.Manifest.permission.FACTORY_TEST)) { 7867 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7868 } 7869 7870 ArrayList<PackageParser.Package> clientLibPkgs = null; 7871 7872 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7873 if (nonMutatedPs != null) { 7874 synchronized (mPackages) { 7875 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7876 } 7877 } 7878 return pkg; 7879 } 7880 7881 // Only privileged apps and updated privileged apps can add child packages. 7882 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7883 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7884 throw new PackageManagerException("Only privileged apps and updated " 7885 + "privileged apps can add child packages. Ignoring package " 7886 + pkg.packageName); 7887 } 7888 final int childCount = pkg.childPackages.size(); 7889 for (int i = 0; i < childCount; i++) { 7890 PackageParser.Package childPkg = pkg.childPackages.get(i); 7891 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7892 childPkg.packageName)) { 7893 throw new PackageManagerException("Cannot override a child package of " 7894 + "another disabled system app. Ignoring package " + pkg.packageName); 7895 } 7896 } 7897 } 7898 7899 // writer 7900 synchronized (mPackages) { 7901 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7902 // Only system apps can add new shared libraries. 7903 if (pkg.libraryNames != null) { 7904 for (int i=0; i<pkg.libraryNames.size(); i++) { 7905 String name = pkg.libraryNames.get(i); 7906 boolean allowed = false; 7907 if (pkg.isUpdatedSystemApp()) { 7908 // New library entries can only be added through the 7909 // system image. This is important to get rid of a lot 7910 // of nasty edge cases: for example if we allowed a non- 7911 // system update of the app to add a library, then uninstalling 7912 // the update would make the library go away, and assumptions 7913 // we made such as through app install filtering would now 7914 // have allowed apps on the device which aren't compatible 7915 // with it. Better to just have the restriction here, be 7916 // conservative, and create many fewer cases that can negatively 7917 // impact the user experience. 7918 final PackageSetting sysPs = mSettings 7919 .getDisabledSystemPkgLPr(pkg.packageName); 7920 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7921 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7922 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7923 allowed = true; 7924 break; 7925 } 7926 } 7927 } 7928 } else { 7929 allowed = true; 7930 } 7931 if (allowed) { 7932 if (!mSharedLibraries.containsKey(name)) { 7933 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7934 } else if (!name.equals(pkg.packageName)) { 7935 Slog.w(TAG, "Package " + pkg.packageName + " library " 7936 + name + " already exists; skipping"); 7937 } 7938 } else { 7939 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7940 + name + " that is not declared on system image; skipping"); 7941 } 7942 } 7943 if ((scanFlags & SCAN_BOOTING) == 0) { 7944 // If we are not booting, we need to update any applications 7945 // that are clients of our shared library. If we are booting, 7946 // this will all be done once the scan is complete. 7947 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7948 } 7949 } 7950 } 7951 } 7952 7953 // Request the ActivityManager to kill the process(only for existing packages) 7954 // so that we do not end up in a confused state while the user is still using the older 7955 // version of the application while the new one gets installed. 7956 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 7957 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 7958 if (killApp) { 7959 if (isReplacing) { 7960 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7961 7962 killApplication(pkg.applicationInfo.packageName, 7963 pkg.applicationInfo.uid, "replace pkg"); 7964 7965 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7966 } 7967 } 7968 7969 // Also need to kill any apps that are dependent on the library. 7970 if (clientLibPkgs != null) { 7971 for (int i=0; i<clientLibPkgs.size(); i++) { 7972 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7973 killApplication(clientPkg.applicationInfo.packageName, 7974 clientPkg.applicationInfo.uid, "update lib"); 7975 } 7976 } 7977 7978 // Make sure we're not adding any bogus keyset info 7979 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7980 ksms.assertScannedPackageValid(pkg); 7981 7982 // writer 7983 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7984 7985 boolean createIdmapFailed = false; 7986 synchronized (mPackages) { 7987 // We don't expect installation to fail beyond this point 7988 7989 // Add the new setting to mSettings 7990 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7991 // Add the new setting to mPackages 7992 mPackages.put(pkg.applicationInfo.packageName, pkg); 7993 // Make sure we don't accidentally delete its data. 7994 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7995 while (iter.hasNext()) { 7996 PackageCleanItem item = iter.next(); 7997 if (pkgName.equals(item.packageName)) { 7998 iter.remove(); 7999 } 8000 } 8001 8002 // Take care of first install / last update times. 8003 if (currentTime != 0) { 8004 if (pkgSetting.firstInstallTime == 0) { 8005 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8006 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8007 pkgSetting.lastUpdateTime = currentTime; 8008 } 8009 } else if (pkgSetting.firstInstallTime == 0) { 8010 // We need *something*. Take time time stamp of the file. 8011 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8012 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8013 if (scanFileTime != pkgSetting.timeStamp) { 8014 // A package on the system image has changed; consider this 8015 // to be an update. 8016 pkgSetting.lastUpdateTime = scanFileTime; 8017 } 8018 } 8019 8020 // Add the package's KeySets to the global KeySetManagerService 8021 ksms.addScannedPackageLPw(pkg); 8022 8023 int N = pkg.providers.size(); 8024 StringBuilder r = null; 8025 int i; 8026 for (i=0; i<N; i++) { 8027 PackageParser.Provider p = pkg.providers.get(i); 8028 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8029 p.info.processName, pkg.applicationInfo.uid); 8030 mProviders.addProvider(p); 8031 p.syncable = p.info.isSyncable; 8032 if (p.info.authority != null) { 8033 String names[] = p.info.authority.split(";"); 8034 p.info.authority = null; 8035 for (int j = 0; j < names.length; j++) { 8036 if (j == 1 && p.syncable) { 8037 // We only want the first authority for a provider to possibly be 8038 // syncable, so if we already added this provider using a different 8039 // authority clear the syncable flag. We copy the provider before 8040 // changing it because the mProviders object contains a reference 8041 // to a provider that we don't want to change. 8042 // Only do this for the second authority since the resulting provider 8043 // object can be the same for all future authorities for this provider. 8044 p = new PackageParser.Provider(p); 8045 p.syncable = false; 8046 } 8047 if (!mProvidersByAuthority.containsKey(names[j])) { 8048 mProvidersByAuthority.put(names[j], p); 8049 if (p.info.authority == null) { 8050 p.info.authority = names[j]; 8051 } else { 8052 p.info.authority = p.info.authority + ";" + names[j]; 8053 } 8054 if (DEBUG_PACKAGE_SCANNING) { 8055 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8056 Log.d(TAG, "Registered content provider: " + names[j] 8057 + ", className = " + p.info.name + ", isSyncable = " 8058 + p.info.isSyncable); 8059 } 8060 } else { 8061 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8062 Slog.w(TAG, "Skipping provider name " + names[j] + 8063 " (in package " + pkg.applicationInfo.packageName + 8064 "): name already used by " 8065 + ((other != null && other.getComponentName() != null) 8066 ? other.getComponentName().getPackageName() : "?")); 8067 } 8068 } 8069 } 8070 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8071 if (r == null) { 8072 r = new StringBuilder(256); 8073 } else { 8074 r.append(' '); 8075 } 8076 r.append(p.info.name); 8077 } 8078 } 8079 if (r != null) { 8080 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8081 } 8082 8083 N = pkg.services.size(); 8084 r = null; 8085 for (i=0; i<N; i++) { 8086 PackageParser.Service s = pkg.services.get(i); 8087 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8088 s.info.processName, pkg.applicationInfo.uid); 8089 mServices.addService(s); 8090 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8091 if (r == null) { 8092 r = new StringBuilder(256); 8093 } else { 8094 r.append(' '); 8095 } 8096 r.append(s.info.name); 8097 } 8098 } 8099 if (r != null) { 8100 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8101 } 8102 8103 N = pkg.receivers.size(); 8104 r = null; 8105 for (i=0; i<N; i++) { 8106 PackageParser.Activity a = pkg.receivers.get(i); 8107 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8108 a.info.processName, pkg.applicationInfo.uid); 8109 mReceivers.addActivity(a, "receiver"); 8110 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8111 if (r == null) { 8112 r = new StringBuilder(256); 8113 } else { 8114 r.append(' '); 8115 } 8116 r.append(a.info.name); 8117 } 8118 } 8119 if (r != null) { 8120 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8121 } 8122 8123 N = pkg.activities.size(); 8124 r = null; 8125 for (i=0; i<N; i++) { 8126 PackageParser.Activity a = pkg.activities.get(i); 8127 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8128 a.info.processName, pkg.applicationInfo.uid); 8129 mActivities.addActivity(a, "activity"); 8130 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8131 if (r == null) { 8132 r = new StringBuilder(256); 8133 } else { 8134 r.append(' '); 8135 } 8136 r.append(a.info.name); 8137 } 8138 } 8139 if (r != null) { 8140 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8141 } 8142 8143 N = pkg.permissionGroups.size(); 8144 r = null; 8145 for (i=0; i<N; i++) { 8146 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8147 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8148 if (cur == null) { 8149 mPermissionGroups.put(pg.info.name, pg); 8150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8151 if (r == null) { 8152 r = new StringBuilder(256); 8153 } else { 8154 r.append(' '); 8155 } 8156 r.append(pg.info.name); 8157 } 8158 } else { 8159 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8160 + pg.info.packageName + " ignored: original from " 8161 + cur.info.packageName); 8162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8163 if (r == null) { 8164 r = new StringBuilder(256); 8165 } else { 8166 r.append(' '); 8167 } 8168 r.append("DUP:"); 8169 r.append(pg.info.name); 8170 } 8171 } 8172 } 8173 if (r != null) { 8174 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8175 } 8176 8177 N = pkg.permissions.size(); 8178 r = null; 8179 for (i=0; i<N; i++) { 8180 PackageParser.Permission p = pkg.permissions.get(i); 8181 8182 // Assume by default that we did not install this permission into the system. 8183 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8184 8185 // Now that permission groups have a special meaning, we ignore permission 8186 // groups for legacy apps to prevent unexpected behavior. In particular, 8187 // permissions for one app being granted to someone just becase they happen 8188 // to be in a group defined by another app (before this had no implications). 8189 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8190 p.group = mPermissionGroups.get(p.info.group); 8191 // Warn for a permission in an unknown group. 8192 if (p.info.group != null && p.group == null) { 8193 Slog.w(TAG, "Permission " + p.info.name + " from package " 8194 + p.info.packageName + " in an unknown group " + p.info.group); 8195 } 8196 } 8197 8198 ArrayMap<String, BasePermission> permissionMap = 8199 p.tree ? mSettings.mPermissionTrees 8200 : mSettings.mPermissions; 8201 BasePermission bp = permissionMap.get(p.info.name); 8202 8203 // Allow system apps to redefine non-system permissions 8204 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8205 final boolean currentOwnerIsSystem = (bp.perm != null 8206 && isSystemApp(bp.perm.owner)); 8207 if (isSystemApp(p.owner)) { 8208 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8209 // It's a built-in permission and no owner, take ownership now 8210 bp.packageSetting = pkgSetting; 8211 bp.perm = p; 8212 bp.uid = pkg.applicationInfo.uid; 8213 bp.sourcePackage = p.info.packageName; 8214 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8215 } else if (!currentOwnerIsSystem) { 8216 String msg = "New decl " + p.owner + " of permission " 8217 + p.info.name + " is system; overriding " + bp.sourcePackage; 8218 reportSettingsProblem(Log.WARN, msg); 8219 bp = null; 8220 } 8221 } 8222 } 8223 8224 if (bp == null) { 8225 bp = new BasePermission(p.info.name, p.info.packageName, 8226 BasePermission.TYPE_NORMAL); 8227 permissionMap.put(p.info.name, bp); 8228 } 8229 8230 if (bp.perm == null) { 8231 if (bp.sourcePackage == null 8232 || bp.sourcePackage.equals(p.info.packageName)) { 8233 BasePermission tree = findPermissionTreeLP(p.info.name); 8234 if (tree == null 8235 || tree.sourcePackage.equals(p.info.packageName)) { 8236 bp.packageSetting = pkgSetting; 8237 bp.perm = p; 8238 bp.uid = pkg.applicationInfo.uid; 8239 bp.sourcePackage = p.info.packageName; 8240 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8241 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8242 if (r == null) { 8243 r = new StringBuilder(256); 8244 } else { 8245 r.append(' '); 8246 } 8247 r.append(p.info.name); 8248 } 8249 } else { 8250 Slog.w(TAG, "Permission " + p.info.name + " from package " 8251 + p.info.packageName + " ignored: base tree " 8252 + tree.name + " is from package " 8253 + tree.sourcePackage); 8254 } 8255 } else { 8256 Slog.w(TAG, "Permission " + p.info.name + " from package " 8257 + p.info.packageName + " ignored: original from " 8258 + bp.sourcePackage); 8259 } 8260 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8261 if (r == null) { 8262 r = new StringBuilder(256); 8263 } else { 8264 r.append(' '); 8265 } 8266 r.append("DUP:"); 8267 r.append(p.info.name); 8268 } 8269 if (bp.perm == p) { 8270 bp.protectionLevel = p.info.protectionLevel; 8271 } 8272 } 8273 8274 if (r != null) { 8275 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8276 } 8277 8278 N = pkg.instrumentation.size(); 8279 r = null; 8280 for (i=0; i<N; i++) { 8281 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8282 a.info.packageName = pkg.applicationInfo.packageName; 8283 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8284 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8285 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8286 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8287 a.info.dataDir = pkg.applicationInfo.dataDir; 8288 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8289 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8290 8291 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8292 // need other information about the application, like the ABI and what not ? 8293 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8294 mInstrumentation.put(a.getComponentName(), a); 8295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8296 if (r == null) { 8297 r = new StringBuilder(256); 8298 } else { 8299 r.append(' '); 8300 } 8301 r.append(a.info.name); 8302 } 8303 } 8304 if (r != null) { 8305 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8306 } 8307 8308 if (pkg.protectedBroadcasts != null) { 8309 N = pkg.protectedBroadcasts.size(); 8310 for (i=0; i<N; i++) { 8311 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8312 } 8313 } 8314 8315 pkgSetting.setTimeStamp(scanFileTime); 8316 8317 // Create idmap files for pairs of (packages, overlay packages). 8318 // Note: "android", ie framework-res.apk, is handled by native layers. 8319 if (pkg.mOverlayTarget != null) { 8320 // This is an overlay package. 8321 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8322 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8323 mOverlays.put(pkg.mOverlayTarget, 8324 new ArrayMap<String, PackageParser.Package>()); 8325 } 8326 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8327 map.put(pkg.packageName, pkg); 8328 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8329 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8330 createIdmapFailed = true; 8331 } 8332 } 8333 } else if (mOverlays.containsKey(pkg.packageName) && 8334 !pkg.packageName.equals("android")) { 8335 // This is a regular package, with one or more known overlay packages. 8336 createIdmapsForPackageLI(pkg); 8337 } 8338 } 8339 8340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8341 8342 if (createIdmapFailed) { 8343 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8344 "scanPackageLI failed to createIdmap"); 8345 } 8346 return pkg; 8347 } 8348 8349 /** 8350 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8351 * is derived purely on the basis of the contents of {@code scanFile} and 8352 * {@code cpuAbiOverride}. 8353 * 8354 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8355 */ 8356 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8357 String cpuAbiOverride, boolean extractLibs) 8358 throws PackageManagerException { 8359 // TODO: We can probably be smarter about this stuff. For installed apps, 8360 // we can calculate this information at install time once and for all. For 8361 // system apps, we can probably assume that this information doesn't change 8362 // after the first boot scan. As things stand, we do lots of unnecessary work. 8363 8364 // Give ourselves some initial paths; we'll come back for another 8365 // pass once we've determined ABI below. 8366 setNativeLibraryPaths(pkg); 8367 8368 // We would never need to extract libs for forward-locked and external packages, 8369 // since the container service will do it for us. We shouldn't attempt to 8370 // extract libs from system app when it was not updated. 8371 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8372 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8373 extractLibs = false; 8374 } 8375 8376 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8377 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8378 8379 NativeLibraryHelper.Handle handle = null; 8380 try { 8381 handle = NativeLibraryHelper.Handle.create(pkg); 8382 // TODO(multiArch): This can be null for apps that didn't go through the 8383 // usual installation process. We can calculate it again, like we 8384 // do during install time. 8385 // 8386 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8387 // unnecessary. 8388 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8389 8390 // Null out the abis so that they can be recalculated. 8391 pkg.applicationInfo.primaryCpuAbi = null; 8392 pkg.applicationInfo.secondaryCpuAbi = null; 8393 if (isMultiArch(pkg.applicationInfo)) { 8394 // Warn if we've set an abiOverride for multi-lib packages.. 8395 // By definition, we need to copy both 32 and 64 bit libraries for 8396 // such packages. 8397 if (pkg.cpuAbiOverride != null 8398 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8399 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8400 } 8401 8402 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8403 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8404 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8405 if (extractLibs) { 8406 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8407 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8408 useIsaSpecificSubdirs); 8409 } else { 8410 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8411 } 8412 } 8413 8414 maybeThrowExceptionForMultiArchCopy( 8415 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8416 8417 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8418 if (extractLibs) { 8419 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8420 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8421 useIsaSpecificSubdirs); 8422 } else { 8423 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8424 } 8425 } 8426 8427 maybeThrowExceptionForMultiArchCopy( 8428 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8429 8430 if (abi64 >= 0) { 8431 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8432 } 8433 8434 if (abi32 >= 0) { 8435 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8436 if (abi64 >= 0) { 8437 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8438 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8439 pkg.applicationInfo.primaryCpuAbi = abi; 8440 } else { 8441 pkg.applicationInfo.secondaryCpuAbi = abi; 8442 } 8443 } else { 8444 pkg.applicationInfo.primaryCpuAbi = abi; 8445 } 8446 } 8447 8448 } else { 8449 String[] abiList = (cpuAbiOverride != null) ? 8450 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8451 8452 // Enable gross and lame hacks for apps that are built with old 8453 // SDK tools. We must scan their APKs for renderscript bitcode and 8454 // not launch them if it's present. Don't bother checking on devices 8455 // that don't have 64 bit support. 8456 boolean needsRenderScriptOverride = false; 8457 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8458 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8459 abiList = Build.SUPPORTED_32_BIT_ABIS; 8460 needsRenderScriptOverride = true; 8461 } 8462 8463 final int copyRet; 8464 if (extractLibs) { 8465 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8466 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8467 } else { 8468 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8469 } 8470 8471 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8472 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8473 "Error unpackaging native libs for app, errorCode=" + copyRet); 8474 } 8475 8476 if (copyRet >= 0) { 8477 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8478 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8479 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8480 } else if (needsRenderScriptOverride) { 8481 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8482 } 8483 } 8484 } catch (IOException ioe) { 8485 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8486 } finally { 8487 IoUtils.closeQuietly(handle); 8488 } 8489 8490 // Now that we've calculated the ABIs and determined if it's an internal app, 8491 // we will go ahead and populate the nativeLibraryPath. 8492 setNativeLibraryPaths(pkg); 8493 } 8494 8495 /** 8496 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8497 * i.e, so that all packages can be run inside a single process if required. 8498 * 8499 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8500 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8501 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8502 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8503 * updating a package that belongs to a shared user. 8504 * 8505 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8506 * adds unnecessary complexity. 8507 */ 8508 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8509 PackageParser.Package scannedPackage, boolean bootComplete) { 8510 String requiredInstructionSet = null; 8511 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8512 requiredInstructionSet = VMRuntime.getInstructionSet( 8513 scannedPackage.applicationInfo.primaryCpuAbi); 8514 } 8515 8516 PackageSetting requirer = null; 8517 for (PackageSetting ps : packagesForUser) { 8518 // If packagesForUser contains scannedPackage, we skip it. This will happen 8519 // when scannedPackage is an update of an existing package. Without this check, 8520 // we will never be able to change the ABI of any package belonging to a shared 8521 // user, even if it's compatible with other packages. 8522 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8523 if (ps.primaryCpuAbiString == null) { 8524 continue; 8525 } 8526 8527 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8528 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8529 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8530 // this but there's not much we can do. 8531 String errorMessage = "Instruction set mismatch, " 8532 + ((requirer == null) ? "[caller]" : requirer) 8533 + " requires " + requiredInstructionSet + " whereas " + ps 8534 + " requires " + instructionSet; 8535 Slog.w(TAG, errorMessage); 8536 } 8537 8538 if (requiredInstructionSet == null) { 8539 requiredInstructionSet = instructionSet; 8540 requirer = ps; 8541 } 8542 } 8543 } 8544 8545 if (requiredInstructionSet != null) { 8546 String adjustedAbi; 8547 if (requirer != null) { 8548 // requirer != null implies that either scannedPackage was null or that scannedPackage 8549 // did not require an ABI, in which case we have to adjust scannedPackage to match 8550 // the ABI of the set (which is the same as requirer's ABI) 8551 adjustedAbi = requirer.primaryCpuAbiString; 8552 if (scannedPackage != null) { 8553 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8554 } 8555 } else { 8556 // requirer == null implies that we're updating all ABIs in the set to 8557 // match scannedPackage. 8558 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8559 } 8560 8561 for (PackageSetting ps : packagesForUser) { 8562 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8563 if (ps.primaryCpuAbiString != null) { 8564 continue; 8565 } 8566 8567 ps.primaryCpuAbiString = adjustedAbi; 8568 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8569 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8570 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8571 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8572 + " (requirer=" 8573 + (requirer == null ? "null" : requirer.pkg.packageName) 8574 + ", scannedPackage=" 8575 + (scannedPackage != null ? scannedPackage.packageName : "null") 8576 + ")"); 8577 try { 8578 mInstaller.rmdex(ps.codePathString, 8579 getDexCodeInstructionSet(getPreferredInstructionSet())); 8580 } catch (InstallerException ignored) { 8581 } 8582 } 8583 } 8584 } 8585 } 8586 } 8587 8588 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8589 synchronized (mPackages) { 8590 mResolverReplaced = true; 8591 // Set up information for custom user intent resolution activity. 8592 mResolveActivity.applicationInfo = pkg.applicationInfo; 8593 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8594 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8595 mResolveActivity.processName = pkg.applicationInfo.packageName; 8596 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8597 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8598 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8599 mResolveActivity.theme = 0; 8600 mResolveActivity.exported = true; 8601 mResolveActivity.enabled = true; 8602 mResolveInfo.activityInfo = mResolveActivity; 8603 mResolveInfo.priority = 0; 8604 mResolveInfo.preferredOrder = 0; 8605 mResolveInfo.match = 0; 8606 mResolveComponentName = mCustomResolverComponentName; 8607 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8608 mResolveComponentName); 8609 } 8610 } 8611 8612 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8613 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8614 8615 // Set up information for ephemeral installer activity 8616 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8617 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8618 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8619 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8620 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8621 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8622 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8623 mEphemeralInstallerActivity.theme = 0; 8624 mEphemeralInstallerActivity.exported = true; 8625 mEphemeralInstallerActivity.enabled = true; 8626 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8627 mEphemeralInstallerInfo.priority = 0; 8628 mEphemeralInstallerInfo.preferredOrder = 0; 8629 mEphemeralInstallerInfo.match = 0; 8630 8631 if (DEBUG_EPHEMERAL) { 8632 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8633 } 8634 } 8635 8636 private static String calculateBundledApkRoot(final String codePathString) { 8637 final File codePath = new File(codePathString); 8638 final File codeRoot; 8639 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8640 codeRoot = Environment.getRootDirectory(); 8641 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8642 codeRoot = Environment.getOemDirectory(); 8643 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8644 codeRoot = Environment.getVendorDirectory(); 8645 } else { 8646 // Unrecognized code path; take its top real segment as the apk root: 8647 // e.g. /something/app/blah.apk => /something 8648 try { 8649 File f = codePath.getCanonicalFile(); 8650 File parent = f.getParentFile(); // non-null because codePath is a file 8651 File tmp; 8652 while ((tmp = parent.getParentFile()) != null) { 8653 f = parent; 8654 parent = tmp; 8655 } 8656 codeRoot = f; 8657 Slog.w(TAG, "Unrecognized code path " 8658 + codePath + " - using " + codeRoot); 8659 } catch (IOException e) { 8660 // Can't canonicalize the code path -- shenanigans? 8661 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8662 return Environment.getRootDirectory().getPath(); 8663 } 8664 } 8665 return codeRoot.getPath(); 8666 } 8667 8668 /** 8669 * Derive and set the location of native libraries for the given package, 8670 * which varies depending on where and how the package was installed. 8671 */ 8672 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8673 final ApplicationInfo info = pkg.applicationInfo; 8674 final String codePath = pkg.codePath; 8675 final File codeFile = new File(codePath); 8676 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8677 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8678 8679 info.nativeLibraryRootDir = null; 8680 info.nativeLibraryRootRequiresIsa = false; 8681 info.nativeLibraryDir = null; 8682 info.secondaryNativeLibraryDir = null; 8683 8684 if (isApkFile(codeFile)) { 8685 // Monolithic install 8686 if (bundledApp) { 8687 // If "/system/lib64/apkname" exists, assume that is the per-package 8688 // native library directory to use; otherwise use "/system/lib/apkname". 8689 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8690 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8691 getPrimaryInstructionSet(info)); 8692 8693 // This is a bundled system app so choose the path based on the ABI. 8694 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8695 // is just the default path. 8696 final String apkName = deriveCodePathName(codePath); 8697 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8698 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8699 apkName).getAbsolutePath(); 8700 8701 if (info.secondaryCpuAbi != null) { 8702 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8703 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8704 secondaryLibDir, apkName).getAbsolutePath(); 8705 } 8706 } else if (asecApp) { 8707 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8708 .getAbsolutePath(); 8709 } else { 8710 final String apkName = deriveCodePathName(codePath); 8711 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8712 .getAbsolutePath(); 8713 } 8714 8715 info.nativeLibraryRootRequiresIsa = false; 8716 info.nativeLibraryDir = info.nativeLibraryRootDir; 8717 } else { 8718 // Cluster install 8719 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8720 info.nativeLibraryRootRequiresIsa = true; 8721 8722 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8723 getPrimaryInstructionSet(info)).getAbsolutePath(); 8724 8725 if (info.secondaryCpuAbi != null) { 8726 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8727 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8728 } 8729 } 8730 } 8731 8732 /** 8733 * Calculate the abis and roots for a bundled app. These can uniquely 8734 * be determined from the contents of the system partition, i.e whether 8735 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8736 * of this information, and instead assume that the system was built 8737 * sensibly. 8738 */ 8739 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8740 PackageSetting pkgSetting) { 8741 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8742 8743 // If "/system/lib64/apkname" exists, assume that is the per-package 8744 // native library directory to use; otherwise use "/system/lib/apkname". 8745 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8746 setBundledAppAbi(pkg, apkRoot, apkName); 8747 // pkgSetting might be null during rescan following uninstall of updates 8748 // to a bundled app, so accommodate that possibility. The settings in 8749 // that case will be established later from the parsed package. 8750 // 8751 // If the settings aren't null, sync them up with what we've just derived. 8752 // note that apkRoot isn't stored in the package settings. 8753 if (pkgSetting != null) { 8754 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8755 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8756 } 8757 } 8758 8759 /** 8760 * Deduces the ABI of a bundled app and sets the relevant fields on the 8761 * parsed pkg object. 8762 * 8763 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8764 * under which system libraries are installed. 8765 * @param apkName the name of the installed package. 8766 */ 8767 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8768 final File codeFile = new File(pkg.codePath); 8769 8770 final boolean has64BitLibs; 8771 final boolean has32BitLibs; 8772 if (isApkFile(codeFile)) { 8773 // Monolithic install 8774 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8775 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8776 } else { 8777 // Cluster install 8778 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8779 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8780 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8781 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8782 has64BitLibs = (new File(rootDir, isa)).exists(); 8783 } else { 8784 has64BitLibs = false; 8785 } 8786 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8787 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8788 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8789 has32BitLibs = (new File(rootDir, isa)).exists(); 8790 } else { 8791 has32BitLibs = false; 8792 } 8793 } 8794 8795 if (has64BitLibs && !has32BitLibs) { 8796 // The package has 64 bit libs, but not 32 bit libs. Its primary 8797 // ABI should be 64 bit. We can safely assume here that the bundled 8798 // native libraries correspond to the most preferred ABI in the list. 8799 8800 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8801 pkg.applicationInfo.secondaryCpuAbi = null; 8802 } else if (has32BitLibs && !has64BitLibs) { 8803 // The package has 32 bit libs but not 64 bit libs. Its primary 8804 // ABI should be 32 bit. 8805 8806 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8807 pkg.applicationInfo.secondaryCpuAbi = null; 8808 } else if (has32BitLibs && has64BitLibs) { 8809 // The application has both 64 and 32 bit bundled libraries. We check 8810 // here that the app declares multiArch support, and warn if it doesn't. 8811 // 8812 // We will be lenient here and record both ABIs. The primary will be the 8813 // ABI that's higher on the list, i.e, a device that's configured to prefer 8814 // 64 bit apps will see a 64 bit primary ABI, 8815 8816 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8817 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8818 } 8819 8820 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8822 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8823 } else { 8824 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8825 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8826 } 8827 } else { 8828 pkg.applicationInfo.primaryCpuAbi = null; 8829 pkg.applicationInfo.secondaryCpuAbi = null; 8830 } 8831 } 8832 8833 private void killPackage(PackageParser.Package pkg, String reason) { 8834 // Kill the parent package 8835 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8836 // Kill the child packages 8837 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8838 for (int i = 0; i < childCount; i++) { 8839 PackageParser.Package childPkg = pkg.childPackages.get(i); 8840 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8841 } 8842 } 8843 8844 private void killApplication(String pkgName, int appId, String reason) { 8845 // Request the ActivityManager to kill the process(only for existing packages) 8846 // so that we do not end up in a confused state while the user is still using the older 8847 // version of the application while the new one gets installed. 8848 IActivityManager am = ActivityManagerNative.getDefault(); 8849 if (am != null) { 8850 try { 8851 am.killApplicationWithAppId(pkgName, appId, reason); 8852 } catch (RemoteException e) { 8853 } 8854 } 8855 } 8856 8857 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8858 // Remove the parent package setting 8859 PackageSetting ps = (PackageSetting) pkg.mExtras; 8860 if (ps != null) { 8861 removePackageLI(ps, chatty); 8862 } 8863 // Remove the child package setting 8864 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8865 for (int i = 0; i < childCount; i++) { 8866 PackageParser.Package childPkg = pkg.childPackages.get(i); 8867 ps = (PackageSetting) childPkg.mExtras; 8868 if (ps != null) { 8869 removePackageLI(ps, chatty); 8870 } 8871 } 8872 } 8873 8874 void removePackageLI(PackageSetting ps, boolean chatty) { 8875 if (DEBUG_INSTALL) { 8876 if (chatty) 8877 Log.d(TAG, "Removing package " + ps.name); 8878 } 8879 8880 // writer 8881 synchronized (mPackages) { 8882 mPackages.remove(ps.name); 8883 final PackageParser.Package pkg = ps.pkg; 8884 if (pkg != null) { 8885 cleanPackageDataStructuresLILPw(pkg, chatty); 8886 } 8887 } 8888 } 8889 8890 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8891 if (DEBUG_INSTALL) { 8892 if (chatty) 8893 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8894 } 8895 8896 // writer 8897 synchronized (mPackages) { 8898 // Remove the parent package 8899 mPackages.remove(pkg.applicationInfo.packageName); 8900 cleanPackageDataStructuresLILPw(pkg, chatty); 8901 8902 // Remove the child packages 8903 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8904 for (int i = 0; i < childCount; i++) { 8905 PackageParser.Package childPkg = pkg.childPackages.get(i); 8906 mPackages.remove(childPkg.applicationInfo.packageName); 8907 cleanPackageDataStructuresLILPw(childPkg, chatty); 8908 } 8909 } 8910 } 8911 8912 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8913 int N = pkg.providers.size(); 8914 StringBuilder r = null; 8915 int i; 8916 for (i=0; i<N; i++) { 8917 PackageParser.Provider p = pkg.providers.get(i); 8918 mProviders.removeProvider(p); 8919 if (p.info.authority == null) { 8920 8921 /* There was another ContentProvider with this authority when 8922 * this app was installed so this authority is null, 8923 * Ignore it as we don't have to unregister the provider. 8924 */ 8925 continue; 8926 } 8927 String names[] = p.info.authority.split(";"); 8928 for (int j = 0; j < names.length; j++) { 8929 if (mProvidersByAuthority.get(names[j]) == p) { 8930 mProvidersByAuthority.remove(names[j]); 8931 if (DEBUG_REMOVE) { 8932 if (chatty) 8933 Log.d(TAG, "Unregistered content provider: " + names[j] 8934 + ", className = " + p.info.name + ", isSyncable = " 8935 + p.info.isSyncable); 8936 } 8937 } 8938 } 8939 if (DEBUG_REMOVE && chatty) { 8940 if (r == null) { 8941 r = new StringBuilder(256); 8942 } else { 8943 r.append(' '); 8944 } 8945 r.append(p.info.name); 8946 } 8947 } 8948 if (r != null) { 8949 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8950 } 8951 8952 N = pkg.services.size(); 8953 r = null; 8954 for (i=0; i<N; i++) { 8955 PackageParser.Service s = pkg.services.get(i); 8956 mServices.removeService(s); 8957 if (chatty) { 8958 if (r == null) { 8959 r = new StringBuilder(256); 8960 } else { 8961 r.append(' '); 8962 } 8963 r.append(s.info.name); 8964 } 8965 } 8966 if (r != null) { 8967 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8968 } 8969 8970 N = pkg.receivers.size(); 8971 r = null; 8972 for (i=0; i<N; i++) { 8973 PackageParser.Activity a = pkg.receivers.get(i); 8974 mReceivers.removeActivity(a, "receiver"); 8975 if (DEBUG_REMOVE && chatty) { 8976 if (r == null) { 8977 r = new StringBuilder(256); 8978 } else { 8979 r.append(' '); 8980 } 8981 r.append(a.info.name); 8982 } 8983 } 8984 if (r != null) { 8985 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8986 } 8987 8988 N = pkg.activities.size(); 8989 r = null; 8990 for (i=0; i<N; i++) { 8991 PackageParser.Activity a = pkg.activities.get(i); 8992 mActivities.removeActivity(a, "activity"); 8993 if (DEBUG_REMOVE && chatty) { 8994 if (r == null) { 8995 r = new StringBuilder(256); 8996 } else { 8997 r.append(' '); 8998 } 8999 r.append(a.info.name); 9000 } 9001 } 9002 if (r != null) { 9003 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9004 } 9005 9006 N = pkg.permissions.size(); 9007 r = null; 9008 for (i=0; i<N; i++) { 9009 PackageParser.Permission p = pkg.permissions.get(i); 9010 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9011 if (bp == null) { 9012 bp = mSettings.mPermissionTrees.get(p.info.name); 9013 } 9014 if (bp != null && bp.perm == p) { 9015 bp.perm = null; 9016 if (DEBUG_REMOVE && chatty) { 9017 if (r == null) { 9018 r = new StringBuilder(256); 9019 } else { 9020 r.append(' '); 9021 } 9022 r.append(p.info.name); 9023 } 9024 } 9025 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9026 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9027 if (appOpPkgs != null) { 9028 appOpPkgs.remove(pkg.packageName); 9029 } 9030 } 9031 } 9032 if (r != null) { 9033 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9034 } 9035 9036 N = pkg.requestedPermissions.size(); 9037 r = null; 9038 for (i=0; i<N; i++) { 9039 String perm = pkg.requestedPermissions.get(i); 9040 BasePermission bp = mSettings.mPermissions.get(perm); 9041 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9042 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9043 if (appOpPkgs != null) { 9044 appOpPkgs.remove(pkg.packageName); 9045 if (appOpPkgs.isEmpty()) { 9046 mAppOpPermissionPackages.remove(perm); 9047 } 9048 } 9049 } 9050 } 9051 if (r != null) { 9052 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9053 } 9054 9055 N = pkg.instrumentation.size(); 9056 r = null; 9057 for (i=0; i<N; i++) { 9058 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9059 mInstrumentation.remove(a.getComponentName()); 9060 if (DEBUG_REMOVE && chatty) { 9061 if (r == null) { 9062 r = new StringBuilder(256); 9063 } else { 9064 r.append(' '); 9065 } 9066 r.append(a.info.name); 9067 } 9068 } 9069 if (r != null) { 9070 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9071 } 9072 9073 r = null; 9074 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9075 // Only system apps can hold shared libraries. 9076 if (pkg.libraryNames != null) { 9077 for (i=0; i<pkg.libraryNames.size(); i++) { 9078 String name = pkg.libraryNames.get(i); 9079 SharedLibraryEntry cur = mSharedLibraries.get(name); 9080 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9081 mSharedLibraries.remove(name); 9082 if (DEBUG_REMOVE && chatty) { 9083 if (r == null) { 9084 r = new StringBuilder(256); 9085 } else { 9086 r.append(' '); 9087 } 9088 r.append(name); 9089 } 9090 } 9091 } 9092 } 9093 } 9094 if (r != null) { 9095 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9096 } 9097 } 9098 9099 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9100 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9101 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9102 return true; 9103 } 9104 } 9105 return false; 9106 } 9107 9108 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9109 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9110 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9111 9112 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9113 // Update the parent permissions 9114 updatePermissionsLPw(pkg.packageName, pkg, flags); 9115 // Update the child permissions 9116 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9117 for (int i = 0; i < childCount; i++) { 9118 PackageParser.Package childPkg = pkg.childPackages.get(i); 9119 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9120 } 9121 } 9122 9123 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9124 int flags) { 9125 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9126 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9127 } 9128 9129 private void updatePermissionsLPw(String changingPkg, 9130 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9131 // Make sure there are no dangling permission trees. 9132 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9133 while (it.hasNext()) { 9134 final BasePermission bp = it.next(); 9135 if (bp.packageSetting == null) { 9136 // We may not yet have parsed the package, so just see if 9137 // we still know about its settings. 9138 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9139 } 9140 if (bp.packageSetting == null) { 9141 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9142 + " from package " + bp.sourcePackage); 9143 it.remove(); 9144 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9145 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9146 Slog.i(TAG, "Removing old permission tree: " + bp.name 9147 + " from package " + bp.sourcePackage); 9148 flags |= UPDATE_PERMISSIONS_ALL; 9149 it.remove(); 9150 } 9151 } 9152 } 9153 9154 // Make sure all dynamic permissions have been assigned to a package, 9155 // and make sure there are no dangling permissions. 9156 it = mSettings.mPermissions.values().iterator(); 9157 while (it.hasNext()) { 9158 final BasePermission bp = it.next(); 9159 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9160 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9161 + bp.name + " pkg=" + bp.sourcePackage 9162 + " info=" + bp.pendingInfo); 9163 if (bp.packageSetting == null && bp.pendingInfo != null) { 9164 final BasePermission tree = findPermissionTreeLP(bp.name); 9165 if (tree != null && tree.perm != null) { 9166 bp.packageSetting = tree.packageSetting; 9167 bp.perm = new PackageParser.Permission(tree.perm.owner, 9168 new PermissionInfo(bp.pendingInfo)); 9169 bp.perm.info.packageName = tree.perm.info.packageName; 9170 bp.perm.info.name = bp.name; 9171 bp.uid = tree.uid; 9172 } 9173 } 9174 } 9175 if (bp.packageSetting == null) { 9176 // We may not yet have parsed the package, so just see if 9177 // we still know about its settings. 9178 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9179 } 9180 if (bp.packageSetting == null) { 9181 Slog.w(TAG, "Removing dangling permission: " + bp.name 9182 + " from package " + bp.sourcePackage); 9183 it.remove(); 9184 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9185 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9186 Slog.i(TAG, "Removing old permission: " + bp.name 9187 + " from package " + bp.sourcePackage); 9188 flags |= UPDATE_PERMISSIONS_ALL; 9189 it.remove(); 9190 } 9191 } 9192 } 9193 9194 // Now update the permissions for all packages, in particular 9195 // replace the granted permissions of the system packages. 9196 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9197 for (PackageParser.Package pkg : mPackages.values()) { 9198 if (pkg != pkgInfo) { 9199 // Only replace for packages on requested volume 9200 final String volumeUuid = getVolumeUuidForPackage(pkg); 9201 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9202 && Objects.equals(replaceVolumeUuid, volumeUuid); 9203 grantPermissionsLPw(pkg, replace, changingPkg); 9204 } 9205 } 9206 } 9207 9208 if (pkgInfo != null) { 9209 // Only replace for packages on requested volume 9210 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9211 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9212 && Objects.equals(replaceVolumeUuid, volumeUuid); 9213 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9214 } 9215 } 9216 9217 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9218 String packageOfInterest) { 9219 // IMPORTANT: There are two types of permissions: install and runtime. 9220 // Install time permissions are granted when the app is installed to 9221 // all device users and users added in the future. Runtime permissions 9222 // are granted at runtime explicitly to specific users. Normal and signature 9223 // protected permissions are install time permissions. Dangerous permissions 9224 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9225 // otherwise they are runtime permissions. This function does not manage 9226 // runtime permissions except for the case an app targeting Lollipop MR1 9227 // being upgraded to target a newer SDK, in which case dangerous permissions 9228 // are transformed from install time to runtime ones. 9229 9230 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9231 if (ps == null) { 9232 return; 9233 } 9234 9235 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9236 9237 PermissionsState permissionsState = ps.getPermissionsState(); 9238 PermissionsState origPermissions = permissionsState; 9239 9240 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9241 9242 boolean runtimePermissionsRevoked = false; 9243 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9244 9245 boolean changedInstallPermission = false; 9246 9247 if (replace) { 9248 ps.installPermissionsFixed = false; 9249 if (!ps.isSharedUser()) { 9250 origPermissions = new PermissionsState(permissionsState); 9251 permissionsState.reset(); 9252 } else { 9253 // We need to know only about runtime permission changes since the 9254 // calling code always writes the install permissions state but 9255 // the runtime ones are written only if changed. The only cases of 9256 // changed runtime permissions here are promotion of an install to 9257 // runtime and revocation of a runtime from a shared user. 9258 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9259 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9260 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9261 runtimePermissionsRevoked = true; 9262 } 9263 } 9264 } 9265 9266 permissionsState.setGlobalGids(mGlobalGids); 9267 9268 final int N = pkg.requestedPermissions.size(); 9269 for (int i=0; i<N; i++) { 9270 final String name = pkg.requestedPermissions.get(i); 9271 final BasePermission bp = mSettings.mPermissions.get(name); 9272 9273 if (DEBUG_INSTALL) { 9274 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9275 } 9276 9277 if (bp == null || bp.packageSetting == null) { 9278 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9279 Slog.w(TAG, "Unknown permission " + name 9280 + " in package " + pkg.packageName); 9281 } 9282 continue; 9283 } 9284 9285 final String perm = bp.name; 9286 boolean allowedSig = false; 9287 int grant = GRANT_DENIED; 9288 9289 // Keep track of app op permissions. 9290 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9291 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9292 if (pkgs == null) { 9293 pkgs = new ArraySet<>(); 9294 mAppOpPermissionPackages.put(bp.name, pkgs); 9295 } 9296 pkgs.add(pkg.packageName); 9297 } 9298 9299 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9300 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9301 >= Build.VERSION_CODES.M; 9302 switch (level) { 9303 case PermissionInfo.PROTECTION_NORMAL: { 9304 // For all apps normal permissions are install time ones. 9305 grant = GRANT_INSTALL; 9306 } break; 9307 9308 case PermissionInfo.PROTECTION_DANGEROUS: { 9309 // If a permission review is required for legacy apps we represent 9310 // their permissions as always granted runtime ones since we need 9311 // to keep the review required permission flag per user while an 9312 // install permission's state is shared across all users. 9313 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9314 // For legacy apps dangerous permissions are install time ones. 9315 grant = GRANT_INSTALL; 9316 } else if (origPermissions.hasInstallPermission(bp.name)) { 9317 // For legacy apps that became modern, install becomes runtime. 9318 grant = GRANT_UPGRADE; 9319 } else if (mPromoteSystemApps 9320 && isSystemApp(ps) 9321 && mExistingSystemPackages.contains(ps.name)) { 9322 // For legacy system apps, install becomes runtime. 9323 // We cannot check hasInstallPermission() for system apps since those 9324 // permissions were granted implicitly and not persisted pre-M. 9325 grant = GRANT_UPGRADE; 9326 } else { 9327 // For modern apps keep runtime permissions unchanged. 9328 grant = GRANT_RUNTIME; 9329 } 9330 } break; 9331 9332 case PermissionInfo.PROTECTION_SIGNATURE: { 9333 // For all apps signature permissions are install time ones. 9334 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9335 if (allowedSig) { 9336 grant = GRANT_INSTALL; 9337 } 9338 } break; 9339 } 9340 9341 if (DEBUG_INSTALL) { 9342 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9343 } 9344 9345 if (grant != GRANT_DENIED) { 9346 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9347 // If this is an existing, non-system package, then 9348 // we can't add any new permissions to it. 9349 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9350 // Except... if this is a permission that was added 9351 // to the platform (note: need to only do this when 9352 // updating the platform). 9353 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9354 grant = GRANT_DENIED; 9355 } 9356 } 9357 } 9358 9359 switch (grant) { 9360 case GRANT_INSTALL: { 9361 // Revoke this as runtime permission to handle the case of 9362 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9363 for (int userId : UserManagerService.getInstance().getUserIds()) { 9364 if (origPermissions.getRuntimePermissionState( 9365 bp.name, userId) != null) { 9366 // Revoke the runtime permission and clear the flags. 9367 origPermissions.revokeRuntimePermission(bp, userId); 9368 origPermissions.updatePermissionFlags(bp, userId, 9369 PackageManager.MASK_PERMISSION_FLAGS, 0); 9370 // If we revoked a permission permission, we have to write. 9371 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9372 changedRuntimePermissionUserIds, userId); 9373 } 9374 } 9375 // Grant an install permission. 9376 if (permissionsState.grantInstallPermission(bp) != 9377 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9378 changedInstallPermission = true; 9379 } 9380 } break; 9381 9382 case GRANT_RUNTIME: { 9383 // Grant previously granted runtime permissions. 9384 for (int userId : UserManagerService.getInstance().getUserIds()) { 9385 PermissionState permissionState = origPermissions 9386 .getRuntimePermissionState(bp.name, userId); 9387 int flags = permissionState != null 9388 ? permissionState.getFlags() : 0; 9389 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9390 if (permissionsState.grantRuntimePermission(bp, userId) == 9391 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9392 // If we cannot put the permission as it was, we have to write. 9393 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9394 changedRuntimePermissionUserIds, userId); 9395 } 9396 // If the app supports runtime permissions no need for a review. 9397 if (Build.PERMISSIONS_REVIEW_REQUIRED 9398 && appSupportsRuntimePermissions 9399 && (flags & PackageManager 9400 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9401 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9402 // Since we changed the flags, we have to write. 9403 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9404 changedRuntimePermissionUserIds, userId); 9405 } 9406 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9407 && !appSupportsRuntimePermissions) { 9408 // For legacy apps that need a permission review, every new 9409 // runtime permission is granted but it is pending a review. 9410 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9411 permissionsState.grantRuntimePermission(bp, userId); 9412 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9413 // We changed the permission and flags, hence have to write. 9414 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9415 changedRuntimePermissionUserIds, userId); 9416 } 9417 } 9418 // Propagate the permission flags. 9419 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9420 } 9421 } break; 9422 9423 case GRANT_UPGRADE: { 9424 // Grant runtime permissions for a previously held install permission. 9425 PermissionState permissionState = origPermissions 9426 .getInstallPermissionState(bp.name); 9427 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9428 9429 if (origPermissions.revokeInstallPermission(bp) 9430 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9431 // We will be transferring the permission flags, so clear them. 9432 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9433 PackageManager.MASK_PERMISSION_FLAGS, 0); 9434 changedInstallPermission = true; 9435 } 9436 9437 // If the permission is not to be promoted to runtime we ignore it and 9438 // also its other flags as they are not applicable to install permissions. 9439 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9440 for (int userId : currentUserIds) { 9441 if (permissionsState.grantRuntimePermission(bp, userId) != 9442 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9443 // Transfer the permission flags. 9444 permissionsState.updatePermissionFlags(bp, userId, 9445 flags, flags); 9446 // If we granted the permission, we have to write. 9447 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9448 changedRuntimePermissionUserIds, userId); 9449 } 9450 } 9451 } 9452 } break; 9453 9454 default: { 9455 if (packageOfInterest == null 9456 || packageOfInterest.equals(pkg.packageName)) { 9457 Slog.w(TAG, "Not granting permission " + perm 9458 + " to package " + pkg.packageName 9459 + " because it was previously installed without"); 9460 } 9461 } break; 9462 } 9463 } else { 9464 if (permissionsState.revokeInstallPermission(bp) != 9465 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9466 // Also drop the permission flags. 9467 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9468 PackageManager.MASK_PERMISSION_FLAGS, 0); 9469 changedInstallPermission = true; 9470 Slog.i(TAG, "Un-granting permission " + perm 9471 + " from package " + pkg.packageName 9472 + " (protectionLevel=" + bp.protectionLevel 9473 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9474 + ")"); 9475 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9476 // Don't print warning for app op permissions, since it is fine for them 9477 // not to be granted, there is a UI for the user to decide. 9478 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9479 Slog.w(TAG, "Not granting permission " + perm 9480 + " to package " + pkg.packageName 9481 + " (protectionLevel=" + bp.protectionLevel 9482 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9483 + ")"); 9484 } 9485 } 9486 } 9487 } 9488 9489 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9490 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9491 // This is the first that we have heard about this package, so the 9492 // permissions we have now selected are fixed until explicitly 9493 // changed. 9494 ps.installPermissionsFixed = true; 9495 } 9496 9497 // Persist the runtime permissions state for users with changes. If permissions 9498 // were revoked because no app in the shared user declares them we have to 9499 // write synchronously to avoid losing runtime permissions state. 9500 for (int userId : changedRuntimePermissionUserIds) { 9501 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9502 } 9503 9504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9505 } 9506 9507 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9508 boolean allowed = false; 9509 final int NP = PackageParser.NEW_PERMISSIONS.length; 9510 for (int ip=0; ip<NP; ip++) { 9511 final PackageParser.NewPermissionInfo npi 9512 = PackageParser.NEW_PERMISSIONS[ip]; 9513 if (npi.name.equals(perm) 9514 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9515 allowed = true; 9516 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9517 + pkg.packageName); 9518 break; 9519 } 9520 } 9521 return allowed; 9522 } 9523 9524 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9525 BasePermission bp, PermissionsState origPermissions) { 9526 boolean allowed; 9527 allowed = (compareSignatures( 9528 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9529 == PackageManager.SIGNATURE_MATCH) 9530 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9531 == PackageManager.SIGNATURE_MATCH); 9532 if (!allowed && (bp.protectionLevel 9533 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9534 if (isSystemApp(pkg)) { 9535 // For updated system applications, a system permission 9536 // is granted only if it had been defined by the original application. 9537 if (pkg.isUpdatedSystemApp()) { 9538 final PackageSetting sysPs = mSettings 9539 .getDisabledSystemPkgLPr(pkg.packageName); 9540 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9541 // If the original was granted this permission, we take 9542 // that grant decision as read and propagate it to the 9543 // update. 9544 if (sysPs.isPrivileged()) { 9545 allowed = true; 9546 } 9547 } else { 9548 // The system apk may have been updated with an older 9549 // version of the one on the data partition, but which 9550 // granted a new system permission that it didn't have 9551 // before. In this case we do want to allow the app to 9552 // now get the new permission if the ancestral apk is 9553 // privileged to get it. 9554 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9555 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9556 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9557 allowed = true; 9558 break; 9559 } 9560 } 9561 } 9562 // Also if a privileged parent package on the system image or any of 9563 // its children requested a privileged permission, the updated child 9564 // packages can also get the permission. 9565 if (pkg.parentPackage != null) { 9566 final PackageSetting disabledSysParentPs = mSettings 9567 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9568 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9569 && disabledSysParentPs.isPrivileged()) { 9570 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9571 allowed = true; 9572 } else if (disabledSysParentPs.pkg.childPackages != null) { 9573 final int count = disabledSysParentPs.pkg.childPackages.size(); 9574 for (int i = 0; i < count; i++) { 9575 PackageParser.Package disabledSysChildPkg = 9576 disabledSysParentPs.pkg.childPackages.get(i); 9577 if (isPackageRequestingPermission(disabledSysChildPkg, 9578 perm)) { 9579 allowed = true; 9580 break; 9581 } 9582 } 9583 } 9584 } 9585 } 9586 } 9587 } else { 9588 allowed = isPrivilegedApp(pkg); 9589 } 9590 } 9591 } 9592 if (!allowed) { 9593 if (!allowed && (bp.protectionLevel 9594 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9595 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9596 // If this was a previously normal/dangerous permission that got moved 9597 // to a system permission as part of the runtime permission redesign, then 9598 // we still want to blindly grant it to old apps. 9599 allowed = true; 9600 } 9601 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9602 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9603 // If this permission is to be granted to the system installer and 9604 // this app is an installer, then it gets the permission. 9605 allowed = true; 9606 } 9607 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9608 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9609 // If this permission is to be granted to the system verifier and 9610 // this app is a verifier, then it gets the permission. 9611 allowed = true; 9612 } 9613 if (!allowed && (bp.protectionLevel 9614 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9615 && isSystemApp(pkg)) { 9616 // Any pre-installed system app is allowed to get this permission. 9617 allowed = true; 9618 } 9619 if (!allowed && (bp.protectionLevel 9620 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9621 // For development permissions, a development permission 9622 // is granted only if it was already granted. 9623 allowed = origPermissions.hasInstallPermission(perm); 9624 } 9625 } 9626 return allowed; 9627 } 9628 9629 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9630 final int permCount = pkg.requestedPermissions.size(); 9631 for (int j = 0; j < permCount; j++) { 9632 String requestedPermission = pkg.requestedPermissions.get(j); 9633 if (permission.equals(requestedPermission)) { 9634 return true; 9635 } 9636 } 9637 return false; 9638 } 9639 9640 final class ActivityIntentResolver 9641 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9642 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9643 boolean defaultOnly, int userId) { 9644 if (!sUserManager.exists(userId)) return null; 9645 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9646 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9647 } 9648 9649 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9650 int userId) { 9651 if (!sUserManager.exists(userId)) return null; 9652 mFlags = flags; 9653 return super.queryIntent(intent, resolvedType, 9654 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9655 } 9656 9657 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9658 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9659 if (!sUserManager.exists(userId)) return null; 9660 if (packageActivities == null) { 9661 return null; 9662 } 9663 mFlags = flags; 9664 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9665 final int N = packageActivities.size(); 9666 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9667 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9668 9669 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9670 for (int i = 0; i < N; ++i) { 9671 intentFilters = packageActivities.get(i).intents; 9672 if (intentFilters != null && intentFilters.size() > 0) { 9673 PackageParser.ActivityIntentInfo[] array = 9674 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9675 intentFilters.toArray(array); 9676 listCut.add(array); 9677 } 9678 } 9679 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9680 } 9681 9682 public final void addActivity(PackageParser.Activity a, String type) { 9683 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9684 mActivities.put(a.getComponentName(), a); 9685 if (DEBUG_SHOW_INFO) 9686 Log.v( 9687 TAG, " " + type + " " + 9688 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9689 if (DEBUG_SHOW_INFO) 9690 Log.v(TAG, " Class=" + a.info.name); 9691 final int NI = a.intents.size(); 9692 for (int j=0; j<NI; j++) { 9693 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9694 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9695 intent.setPriority(0); 9696 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9697 + a.className + " with priority > 0, forcing to 0"); 9698 } 9699 if (DEBUG_SHOW_INFO) { 9700 Log.v(TAG, " IntentFilter:"); 9701 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9702 } 9703 if (!intent.debugCheck()) { 9704 Log.w(TAG, "==> For Activity " + a.info.name); 9705 } 9706 addFilter(intent); 9707 } 9708 } 9709 9710 public final void removeActivity(PackageParser.Activity a, String type) { 9711 mActivities.remove(a.getComponentName()); 9712 if (DEBUG_SHOW_INFO) { 9713 Log.v(TAG, " " + type + " " 9714 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9715 : a.info.name) + ":"); 9716 Log.v(TAG, " Class=" + a.info.name); 9717 } 9718 final int NI = a.intents.size(); 9719 for (int j=0; j<NI; j++) { 9720 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9721 if (DEBUG_SHOW_INFO) { 9722 Log.v(TAG, " IntentFilter:"); 9723 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9724 } 9725 removeFilter(intent); 9726 } 9727 } 9728 9729 @Override 9730 protected boolean allowFilterResult( 9731 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9732 ActivityInfo filterAi = filter.activity.info; 9733 for (int i=dest.size()-1; i>=0; i--) { 9734 ActivityInfo destAi = dest.get(i).activityInfo; 9735 if (destAi.name == filterAi.name 9736 && destAi.packageName == filterAi.packageName) { 9737 return false; 9738 } 9739 } 9740 return true; 9741 } 9742 9743 @Override 9744 protected ActivityIntentInfo[] newArray(int size) { 9745 return new ActivityIntentInfo[size]; 9746 } 9747 9748 @Override 9749 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9750 if (!sUserManager.exists(userId)) return true; 9751 PackageParser.Package p = filter.activity.owner; 9752 if (p != null) { 9753 PackageSetting ps = (PackageSetting)p.mExtras; 9754 if (ps != null) { 9755 // System apps are never considered stopped for purposes of 9756 // filtering, because there may be no way for the user to 9757 // actually re-launch them. 9758 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9759 && ps.getStopped(userId); 9760 } 9761 } 9762 return false; 9763 } 9764 9765 @Override 9766 protected boolean isPackageForFilter(String packageName, 9767 PackageParser.ActivityIntentInfo info) { 9768 return packageName.equals(info.activity.owner.packageName); 9769 } 9770 9771 @Override 9772 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9773 int match, int userId) { 9774 if (!sUserManager.exists(userId)) return null; 9775 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9776 return null; 9777 } 9778 final PackageParser.Activity activity = info.activity; 9779 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9780 if (ps == null) { 9781 return null; 9782 } 9783 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9784 ps.readUserState(userId), userId); 9785 if (ai == null) { 9786 return null; 9787 } 9788 final ResolveInfo res = new ResolveInfo(); 9789 res.activityInfo = ai; 9790 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9791 res.filter = info; 9792 } 9793 if (info != null) { 9794 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9795 } 9796 res.priority = info.getPriority(); 9797 res.preferredOrder = activity.owner.mPreferredOrder; 9798 //System.out.println("Result: " + res.activityInfo.className + 9799 // " = " + res.priority); 9800 res.match = match; 9801 res.isDefault = info.hasDefault; 9802 res.labelRes = info.labelRes; 9803 res.nonLocalizedLabel = info.nonLocalizedLabel; 9804 if (userNeedsBadging(userId)) { 9805 res.noResourceId = true; 9806 } else { 9807 res.icon = info.icon; 9808 } 9809 res.iconResourceId = info.icon; 9810 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9811 return res; 9812 } 9813 9814 @Override 9815 protected void sortResults(List<ResolveInfo> results) { 9816 Collections.sort(results, mResolvePrioritySorter); 9817 } 9818 9819 @Override 9820 protected void dumpFilter(PrintWriter out, String prefix, 9821 PackageParser.ActivityIntentInfo filter) { 9822 out.print(prefix); out.print( 9823 Integer.toHexString(System.identityHashCode(filter.activity))); 9824 out.print(' '); 9825 filter.activity.printComponentShortName(out); 9826 out.print(" filter "); 9827 out.println(Integer.toHexString(System.identityHashCode(filter))); 9828 } 9829 9830 @Override 9831 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9832 return filter.activity; 9833 } 9834 9835 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9836 PackageParser.Activity activity = (PackageParser.Activity)label; 9837 out.print(prefix); out.print( 9838 Integer.toHexString(System.identityHashCode(activity))); 9839 out.print(' '); 9840 activity.printComponentShortName(out); 9841 if (count > 1) { 9842 out.print(" ("); out.print(count); out.print(" filters)"); 9843 } 9844 out.println(); 9845 } 9846 9847// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9848// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9849// final List<ResolveInfo> retList = Lists.newArrayList(); 9850// while (i.hasNext()) { 9851// final ResolveInfo resolveInfo = i.next(); 9852// if (isEnabledLP(resolveInfo.activityInfo)) { 9853// retList.add(resolveInfo); 9854// } 9855// } 9856// return retList; 9857// } 9858 9859 // Keys are String (activity class name), values are Activity. 9860 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9861 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9862 private int mFlags; 9863 } 9864 9865 private final class ServiceIntentResolver 9866 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9867 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9868 boolean defaultOnly, int userId) { 9869 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9870 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9871 } 9872 9873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9874 int userId) { 9875 if (!sUserManager.exists(userId)) return null; 9876 mFlags = flags; 9877 return super.queryIntent(intent, resolvedType, 9878 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9879 } 9880 9881 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9882 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9883 if (!sUserManager.exists(userId)) return null; 9884 if (packageServices == null) { 9885 return null; 9886 } 9887 mFlags = flags; 9888 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9889 final int N = packageServices.size(); 9890 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9891 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9892 9893 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9894 for (int i = 0; i < N; ++i) { 9895 intentFilters = packageServices.get(i).intents; 9896 if (intentFilters != null && intentFilters.size() > 0) { 9897 PackageParser.ServiceIntentInfo[] array = 9898 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9899 intentFilters.toArray(array); 9900 listCut.add(array); 9901 } 9902 } 9903 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9904 } 9905 9906 public final void addService(PackageParser.Service s) { 9907 mServices.put(s.getComponentName(), s); 9908 if (DEBUG_SHOW_INFO) { 9909 Log.v(TAG, " " 9910 + (s.info.nonLocalizedLabel != null 9911 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9912 Log.v(TAG, " Class=" + s.info.name); 9913 } 9914 final int NI = s.intents.size(); 9915 int j; 9916 for (j=0; j<NI; j++) { 9917 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9918 if (DEBUG_SHOW_INFO) { 9919 Log.v(TAG, " IntentFilter:"); 9920 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9921 } 9922 if (!intent.debugCheck()) { 9923 Log.w(TAG, "==> For Service " + s.info.name); 9924 } 9925 addFilter(intent); 9926 } 9927 } 9928 9929 public final void removeService(PackageParser.Service s) { 9930 mServices.remove(s.getComponentName()); 9931 if (DEBUG_SHOW_INFO) { 9932 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9933 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9934 Log.v(TAG, " Class=" + s.info.name); 9935 } 9936 final int NI = s.intents.size(); 9937 int j; 9938 for (j=0; j<NI; j++) { 9939 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9940 if (DEBUG_SHOW_INFO) { 9941 Log.v(TAG, " IntentFilter:"); 9942 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9943 } 9944 removeFilter(intent); 9945 } 9946 } 9947 9948 @Override 9949 protected boolean allowFilterResult( 9950 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9951 ServiceInfo filterSi = filter.service.info; 9952 for (int i=dest.size()-1; i>=0; i--) { 9953 ServiceInfo destAi = dest.get(i).serviceInfo; 9954 if (destAi.name == filterSi.name 9955 && destAi.packageName == filterSi.packageName) { 9956 return false; 9957 } 9958 } 9959 return true; 9960 } 9961 9962 @Override 9963 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9964 return new PackageParser.ServiceIntentInfo[size]; 9965 } 9966 9967 @Override 9968 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9969 if (!sUserManager.exists(userId)) return true; 9970 PackageParser.Package p = filter.service.owner; 9971 if (p != null) { 9972 PackageSetting ps = (PackageSetting)p.mExtras; 9973 if (ps != null) { 9974 // System apps are never considered stopped for purposes of 9975 // filtering, because there may be no way for the user to 9976 // actually re-launch them. 9977 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9978 && ps.getStopped(userId); 9979 } 9980 } 9981 return false; 9982 } 9983 9984 @Override 9985 protected boolean isPackageForFilter(String packageName, 9986 PackageParser.ServiceIntentInfo info) { 9987 return packageName.equals(info.service.owner.packageName); 9988 } 9989 9990 @Override 9991 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9992 int match, int userId) { 9993 if (!sUserManager.exists(userId)) return null; 9994 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9995 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9996 return null; 9997 } 9998 final PackageParser.Service service = info.service; 9999 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10000 if (ps == null) { 10001 return null; 10002 } 10003 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10004 ps.readUserState(userId), userId); 10005 if (si == null) { 10006 return null; 10007 } 10008 final ResolveInfo res = new ResolveInfo(); 10009 res.serviceInfo = si; 10010 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10011 res.filter = filter; 10012 } 10013 res.priority = info.getPriority(); 10014 res.preferredOrder = service.owner.mPreferredOrder; 10015 res.match = match; 10016 res.isDefault = info.hasDefault; 10017 res.labelRes = info.labelRes; 10018 res.nonLocalizedLabel = info.nonLocalizedLabel; 10019 res.icon = info.icon; 10020 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10021 return res; 10022 } 10023 10024 @Override 10025 protected void sortResults(List<ResolveInfo> results) { 10026 Collections.sort(results, mResolvePrioritySorter); 10027 } 10028 10029 @Override 10030 protected void dumpFilter(PrintWriter out, String prefix, 10031 PackageParser.ServiceIntentInfo filter) { 10032 out.print(prefix); out.print( 10033 Integer.toHexString(System.identityHashCode(filter.service))); 10034 out.print(' '); 10035 filter.service.printComponentShortName(out); 10036 out.print(" filter "); 10037 out.println(Integer.toHexString(System.identityHashCode(filter))); 10038 } 10039 10040 @Override 10041 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10042 return filter.service; 10043 } 10044 10045 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10046 PackageParser.Service service = (PackageParser.Service)label; 10047 out.print(prefix); out.print( 10048 Integer.toHexString(System.identityHashCode(service))); 10049 out.print(' '); 10050 service.printComponentShortName(out); 10051 if (count > 1) { 10052 out.print(" ("); out.print(count); out.print(" filters)"); 10053 } 10054 out.println(); 10055 } 10056 10057// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10058// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10059// final List<ResolveInfo> retList = Lists.newArrayList(); 10060// while (i.hasNext()) { 10061// final ResolveInfo resolveInfo = (ResolveInfo) i; 10062// if (isEnabledLP(resolveInfo.serviceInfo)) { 10063// retList.add(resolveInfo); 10064// } 10065// } 10066// return retList; 10067// } 10068 10069 // Keys are String (activity class name), values are Activity. 10070 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10071 = new ArrayMap<ComponentName, PackageParser.Service>(); 10072 private int mFlags; 10073 }; 10074 10075 private final class ProviderIntentResolver 10076 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10077 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10078 boolean defaultOnly, int userId) { 10079 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10080 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10081 } 10082 10083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10084 int userId) { 10085 if (!sUserManager.exists(userId)) 10086 return null; 10087 mFlags = flags; 10088 return super.queryIntent(intent, resolvedType, 10089 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10090 } 10091 10092 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10093 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10094 if (!sUserManager.exists(userId)) 10095 return null; 10096 if (packageProviders == null) { 10097 return null; 10098 } 10099 mFlags = flags; 10100 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10101 final int N = packageProviders.size(); 10102 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10103 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10104 10105 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10106 for (int i = 0; i < N; ++i) { 10107 intentFilters = packageProviders.get(i).intents; 10108 if (intentFilters != null && intentFilters.size() > 0) { 10109 PackageParser.ProviderIntentInfo[] array = 10110 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10111 intentFilters.toArray(array); 10112 listCut.add(array); 10113 } 10114 } 10115 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10116 } 10117 10118 public final void addProvider(PackageParser.Provider p) { 10119 if (mProviders.containsKey(p.getComponentName())) { 10120 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10121 return; 10122 } 10123 10124 mProviders.put(p.getComponentName(), p); 10125 if (DEBUG_SHOW_INFO) { 10126 Log.v(TAG, " " 10127 + (p.info.nonLocalizedLabel != null 10128 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10129 Log.v(TAG, " Class=" + p.info.name); 10130 } 10131 final int NI = p.intents.size(); 10132 int j; 10133 for (j = 0; j < NI; j++) { 10134 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10135 if (DEBUG_SHOW_INFO) { 10136 Log.v(TAG, " IntentFilter:"); 10137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10138 } 10139 if (!intent.debugCheck()) { 10140 Log.w(TAG, "==> For Provider " + p.info.name); 10141 } 10142 addFilter(intent); 10143 } 10144 } 10145 10146 public final void removeProvider(PackageParser.Provider p) { 10147 mProviders.remove(p.getComponentName()); 10148 if (DEBUG_SHOW_INFO) { 10149 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10150 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10151 Log.v(TAG, " Class=" + p.info.name); 10152 } 10153 final int NI = p.intents.size(); 10154 int j; 10155 for (j = 0; j < NI; j++) { 10156 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10157 if (DEBUG_SHOW_INFO) { 10158 Log.v(TAG, " IntentFilter:"); 10159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10160 } 10161 removeFilter(intent); 10162 } 10163 } 10164 10165 @Override 10166 protected boolean allowFilterResult( 10167 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10168 ProviderInfo filterPi = filter.provider.info; 10169 for (int i = dest.size() - 1; i >= 0; i--) { 10170 ProviderInfo destPi = dest.get(i).providerInfo; 10171 if (destPi.name == filterPi.name 10172 && destPi.packageName == filterPi.packageName) { 10173 return false; 10174 } 10175 } 10176 return true; 10177 } 10178 10179 @Override 10180 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10181 return new PackageParser.ProviderIntentInfo[size]; 10182 } 10183 10184 @Override 10185 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10186 if (!sUserManager.exists(userId)) 10187 return true; 10188 PackageParser.Package p = filter.provider.owner; 10189 if (p != null) { 10190 PackageSetting ps = (PackageSetting) p.mExtras; 10191 if (ps != null) { 10192 // System apps are never considered stopped for purposes of 10193 // filtering, because there may be no way for the user to 10194 // actually re-launch them. 10195 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10196 && ps.getStopped(userId); 10197 } 10198 } 10199 return false; 10200 } 10201 10202 @Override 10203 protected boolean isPackageForFilter(String packageName, 10204 PackageParser.ProviderIntentInfo info) { 10205 return packageName.equals(info.provider.owner.packageName); 10206 } 10207 10208 @Override 10209 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10210 int match, int userId) { 10211 if (!sUserManager.exists(userId)) 10212 return null; 10213 final PackageParser.ProviderIntentInfo info = filter; 10214 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10215 return null; 10216 } 10217 final PackageParser.Provider provider = info.provider; 10218 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10219 if (ps == null) { 10220 return null; 10221 } 10222 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10223 ps.readUserState(userId), userId); 10224 if (pi == null) { 10225 return null; 10226 } 10227 final ResolveInfo res = new ResolveInfo(); 10228 res.providerInfo = pi; 10229 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10230 res.filter = filter; 10231 } 10232 res.priority = info.getPriority(); 10233 res.preferredOrder = provider.owner.mPreferredOrder; 10234 res.match = match; 10235 res.isDefault = info.hasDefault; 10236 res.labelRes = info.labelRes; 10237 res.nonLocalizedLabel = info.nonLocalizedLabel; 10238 res.icon = info.icon; 10239 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10240 return res; 10241 } 10242 10243 @Override 10244 protected void sortResults(List<ResolveInfo> results) { 10245 Collections.sort(results, mResolvePrioritySorter); 10246 } 10247 10248 @Override 10249 protected void dumpFilter(PrintWriter out, String prefix, 10250 PackageParser.ProviderIntentInfo filter) { 10251 out.print(prefix); 10252 out.print( 10253 Integer.toHexString(System.identityHashCode(filter.provider))); 10254 out.print(' '); 10255 filter.provider.printComponentShortName(out); 10256 out.print(" filter "); 10257 out.println(Integer.toHexString(System.identityHashCode(filter))); 10258 } 10259 10260 @Override 10261 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10262 return filter.provider; 10263 } 10264 10265 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10266 PackageParser.Provider provider = (PackageParser.Provider)label; 10267 out.print(prefix); out.print( 10268 Integer.toHexString(System.identityHashCode(provider))); 10269 out.print(' '); 10270 provider.printComponentShortName(out); 10271 if (count > 1) { 10272 out.print(" ("); out.print(count); out.print(" filters)"); 10273 } 10274 out.println(); 10275 } 10276 10277 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10278 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10279 private int mFlags; 10280 } 10281 10282 private static final class EphemeralIntentResolver 10283 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10284 @Override 10285 protected EphemeralResolveIntentInfo[] newArray(int size) { 10286 return new EphemeralResolveIntentInfo[size]; 10287 } 10288 10289 @Override 10290 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10291 return true; 10292 } 10293 10294 @Override 10295 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10296 int userId) { 10297 if (!sUserManager.exists(userId)) { 10298 return null; 10299 } 10300 return info.getEphemeralResolveInfo(); 10301 } 10302 } 10303 10304 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10305 new Comparator<ResolveInfo>() { 10306 public int compare(ResolveInfo r1, ResolveInfo r2) { 10307 int v1 = r1.priority; 10308 int v2 = r2.priority; 10309 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10310 if (v1 != v2) { 10311 return (v1 > v2) ? -1 : 1; 10312 } 10313 v1 = r1.preferredOrder; 10314 v2 = r2.preferredOrder; 10315 if (v1 != v2) { 10316 return (v1 > v2) ? -1 : 1; 10317 } 10318 if (r1.isDefault != r2.isDefault) { 10319 return r1.isDefault ? -1 : 1; 10320 } 10321 v1 = r1.match; 10322 v2 = r2.match; 10323 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10324 if (v1 != v2) { 10325 return (v1 > v2) ? -1 : 1; 10326 } 10327 if (r1.system != r2.system) { 10328 return r1.system ? -1 : 1; 10329 } 10330 if (r1.activityInfo != null) { 10331 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10332 } 10333 if (r1.serviceInfo != null) { 10334 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10335 } 10336 if (r1.providerInfo != null) { 10337 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10338 } 10339 return 0; 10340 } 10341 }; 10342 10343 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10344 new Comparator<ProviderInfo>() { 10345 public int compare(ProviderInfo p1, ProviderInfo p2) { 10346 final int v1 = p1.initOrder; 10347 final int v2 = p2.initOrder; 10348 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10349 } 10350 }; 10351 10352 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10353 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10354 final int[] userIds) { 10355 mHandler.post(new Runnable() { 10356 @Override 10357 public void run() { 10358 try { 10359 final IActivityManager am = ActivityManagerNative.getDefault(); 10360 if (am == null) return; 10361 final int[] resolvedUserIds; 10362 if (userIds == null) { 10363 resolvedUserIds = am.getRunningUserIds(); 10364 } else { 10365 resolvedUserIds = userIds; 10366 } 10367 for (int id : resolvedUserIds) { 10368 final Intent intent = new Intent(action, 10369 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10370 if (extras != null) { 10371 intent.putExtras(extras); 10372 } 10373 if (targetPkg != null) { 10374 intent.setPackage(targetPkg); 10375 } 10376 // Modify the UID when posting to other users 10377 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10378 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10379 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10380 intent.putExtra(Intent.EXTRA_UID, uid); 10381 } 10382 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10383 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10384 if (DEBUG_BROADCASTS) { 10385 RuntimeException here = new RuntimeException("here"); 10386 here.fillInStackTrace(); 10387 Slog.d(TAG, "Sending to user " + id + ": " 10388 + intent.toShortString(false, true, false, false) 10389 + " " + intent.getExtras(), here); 10390 } 10391 am.broadcastIntent(null, intent, null, finishedReceiver, 10392 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10393 null, finishedReceiver != null, false, id); 10394 } 10395 } catch (RemoteException ex) { 10396 } 10397 } 10398 }); 10399 } 10400 10401 /** 10402 * Check if the external storage media is available. This is true if there 10403 * is a mounted external storage medium or if the external storage is 10404 * emulated. 10405 */ 10406 private boolean isExternalMediaAvailable() { 10407 return mMediaMounted || Environment.isExternalStorageEmulated(); 10408 } 10409 10410 @Override 10411 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10412 // writer 10413 synchronized (mPackages) { 10414 if (!isExternalMediaAvailable()) { 10415 // If the external storage is no longer mounted at this point, 10416 // the caller may not have been able to delete all of this 10417 // packages files and can not delete any more. Bail. 10418 return null; 10419 } 10420 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10421 if (lastPackage != null) { 10422 pkgs.remove(lastPackage); 10423 } 10424 if (pkgs.size() > 0) { 10425 return pkgs.get(0); 10426 } 10427 } 10428 return null; 10429 } 10430 10431 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10432 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10433 userId, andCode ? 1 : 0, packageName); 10434 if (mSystemReady) { 10435 msg.sendToTarget(); 10436 } else { 10437 if (mPostSystemReadyMessages == null) { 10438 mPostSystemReadyMessages = new ArrayList<>(); 10439 } 10440 mPostSystemReadyMessages.add(msg); 10441 } 10442 } 10443 10444 void startCleaningPackages() { 10445 // reader 10446 synchronized (mPackages) { 10447 if (!isExternalMediaAvailable()) { 10448 return; 10449 } 10450 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10451 return; 10452 } 10453 } 10454 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10455 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10456 IActivityManager am = ActivityManagerNative.getDefault(); 10457 if (am != null) { 10458 try { 10459 am.startService(null, intent, null, mContext.getOpPackageName(), 10460 UserHandle.USER_SYSTEM); 10461 } catch (RemoteException e) { 10462 } 10463 } 10464 } 10465 10466 @Override 10467 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10468 int installFlags, String installerPackageName, int userId) { 10469 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10470 10471 final int callingUid = Binder.getCallingUid(); 10472 enforceCrossUserPermission(callingUid, userId, 10473 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10474 10475 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10476 try { 10477 if (observer != null) { 10478 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10479 } 10480 } catch (RemoteException re) { 10481 } 10482 return; 10483 } 10484 10485 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10486 installFlags |= PackageManager.INSTALL_FROM_ADB; 10487 10488 } else { 10489 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10490 // about installerPackageName. 10491 10492 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10493 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10494 } 10495 10496 UserHandle user; 10497 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10498 user = UserHandle.ALL; 10499 } else { 10500 user = new UserHandle(userId); 10501 } 10502 10503 // Only system components can circumvent runtime permissions when installing. 10504 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10505 && mContext.checkCallingOrSelfPermission(Manifest.permission 10506 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10507 throw new SecurityException("You need the " 10508 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10509 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10510 } 10511 10512 final File originFile = new File(originPath); 10513 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10514 10515 final Message msg = mHandler.obtainMessage(INIT_COPY); 10516 final VerificationInfo verificationInfo = new VerificationInfo( 10517 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10518 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10519 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10520 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10521 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10522 msg.obj = params; 10523 10524 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10525 System.identityHashCode(msg.obj)); 10526 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10527 System.identityHashCode(msg.obj)); 10528 10529 mHandler.sendMessage(msg); 10530 } 10531 10532 void installStage(String packageName, File stagedDir, String stagedCid, 10533 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10534 String installerPackageName, int installerUid, UserHandle user) { 10535 if (DEBUG_EPHEMERAL) { 10536 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10537 Slog.d(TAG, "Ephemeral install of " + packageName); 10538 } 10539 } 10540 final VerificationInfo verificationInfo = new VerificationInfo( 10541 sessionParams.originatingUri, sessionParams.referrerUri, 10542 sessionParams.originatingUid, installerUid); 10543 10544 final OriginInfo origin; 10545 if (stagedDir != null) { 10546 origin = OriginInfo.fromStagedFile(stagedDir); 10547 } else { 10548 origin = OriginInfo.fromStagedContainer(stagedCid); 10549 } 10550 10551 final Message msg = mHandler.obtainMessage(INIT_COPY); 10552 final InstallParams params = new InstallParams(origin, null, observer, 10553 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10554 verificationInfo, user, sessionParams.abiOverride, 10555 sessionParams.grantedRuntimePermissions); 10556 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10557 msg.obj = params; 10558 10559 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10560 System.identityHashCode(msg.obj)); 10561 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10562 System.identityHashCode(msg.obj)); 10563 10564 mHandler.sendMessage(msg); 10565 } 10566 10567 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10568 int userId) { 10569 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10570 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10571 } 10572 10573 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10574 int appId, int userId) { 10575 Bundle extras = new Bundle(1); 10576 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10577 10578 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10579 packageName, extras, 0, null, null, new int[] {userId}); 10580 try { 10581 IActivityManager am = ActivityManagerNative.getDefault(); 10582 if (isSystem && am.isUserRunning(userId, 0)) { 10583 // The just-installed/enabled app is bundled on the system, so presumed 10584 // to be able to run automatically without needing an explicit launch. 10585 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10586 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10587 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10588 .setPackage(packageName); 10589 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10590 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10591 } 10592 } catch (RemoteException e) { 10593 // shouldn't happen 10594 Slog.w(TAG, "Unable to bootstrap installed package", e); 10595 } 10596 } 10597 10598 @Override 10599 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10600 int userId) { 10601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10602 PackageSetting pkgSetting; 10603 final int uid = Binder.getCallingUid(); 10604 enforceCrossUserPermission(uid, userId, 10605 true /* requireFullPermission */, true /* checkShell */, 10606 "setApplicationHiddenSetting for user " + userId); 10607 10608 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10609 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10610 return false; 10611 } 10612 10613 long callingId = Binder.clearCallingIdentity(); 10614 try { 10615 boolean sendAdded = false; 10616 boolean sendRemoved = false; 10617 // writer 10618 synchronized (mPackages) { 10619 pkgSetting = mSettings.mPackages.get(packageName); 10620 if (pkgSetting == null) { 10621 return false; 10622 } 10623 if (pkgSetting.getHidden(userId) != hidden) { 10624 pkgSetting.setHidden(hidden, userId); 10625 mSettings.writePackageRestrictionsLPr(userId); 10626 if (hidden) { 10627 sendRemoved = true; 10628 } else { 10629 sendAdded = true; 10630 } 10631 } 10632 } 10633 if (sendAdded) { 10634 sendPackageAddedForUser(packageName, pkgSetting, userId); 10635 return true; 10636 } 10637 if (sendRemoved) { 10638 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10639 "hiding pkg"); 10640 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10641 return true; 10642 } 10643 } finally { 10644 Binder.restoreCallingIdentity(callingId); 10645 } 10646 return false; 10647 } 10648 10649 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10650 int userId) { 10651 final PackageRemovedInfo info = new PackageRemovedInfo(); 10652 info.removedPackage = packageName; 10653 info.removedUsers = new int[] {userId}; 10654 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10655 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10656 } 10657 10658 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10659 if (pkgList.length > 0) { 10660 Bundle extras = new Bundle(1); 10661 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10662 10663 sendPackageBroadcast( 10664 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10665 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10666 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10667 new int[] {userId}); 10668 } 10669 } 10670 10671 /** 10672 * Returns true if application is not found or there was an error. Otherwise it returns 10673 * the hidden state of the package for the given user. 10674 */ 10675 @Override 10676 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10677 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10679 true /* requireFullPermission */, false /* checkShell */, 10680 "getApplicationHidden for user " + userId); 10681 PackageSetting pkgSetting; 10682 long callingId = Binder.clearCallingIdentity(); 10683 try { 10684 // writer 10685 synchronized (mPackages) { 10686 pkgSetting = mSettings.mPackages.get(packageName); 10687 if (pkgSetting == null) { 10688 return true; 10689 } 10690 return pkgSetting.getHidden(userId); 10691 } 10692 } finally { 10693 Binder.restoreCallingIdentity(callingId); 10694 } 10695 } 10696 10697 /** 10698 * @hide 10699 */ 10700 @Override 10701 public int installExistingPackageAsUser(String packageName, int userId) { 10702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10703 null); 10704 PackageSetting pkgSetting; 10705 final int uid = Binder.getCallingUid(); 10706 enforceCrossUserPermission(uid, userId, 10707 true /* requireFullPermission */, true /* checkShell */, 10708 "installExistingPackage for user " + userId); 10709 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10710 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10711 } 10712 10713 long callingId = Binder.clearCallingIdentity(); 10714 try { 10715 boolean installed = false; 10716 10717 // writer 10718 synchronized (mPackages) { 10719 pkgSetting = mSettings.mPackages.get(packageName); 10720 if (pkgSetting == null) { 10721 return PackageManager.INSTALL_FAILED_INVALID_URI; 10722 } 10723 if (!pkgSetting.getInstalled(userId)) { 10724 pkgSetting.setInstalled(true, userId); 10725 pkgSetting.setHidden(false, userId); 10726 mSettings.writePackageRestrictionsLPr(userId); 10727 installed = true; 10728 } 10729 } 10730 10731 if (installed) { 10732 if (pkgSetting.pkg != null) { 10733 prepareAppDataAfterInstall(pkgSetting.pkg); 10734 } 10735 sendPackageAddedForUser(packageName, pkgSetting, userId); 10736 } 10737 } finally { 10738 Binder.restoreCallingIdentity(callingId); 10739 } 10740 10741 return PackageManager.INSTALL_SUCCEEDED; 10742 } 10743 10744 boolean isUserRestricted(int userId, String restrictionKey) { 10745 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10746 if (restrictions.getBoolean(restrictionKey, false)) { 10747 Log.w(TAG, "User is restricted: " + restrictionKey); 10748 return true; 10749 } 10750 return false; 10751 } 10752 10753 @Override 10754 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10755 int userId) { 10756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10757 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10758 true /* requireFullPermission */, true /* checkShell */, 10759 "setPackagesSuspended for user " + userId); 10760 10761 if (ArrayUtils.isEmpty(packageNames)) { 10762 return packageNames; 10763 } 10764 10765 // List of package names for whom the suspended state has changed. 10766 List<String> changedPackages = new ArrayList<>(packageNames.length); 10767 // List of package names for whom the suspended state is not set as requested in this 10768 // method. 10769 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10770 for (int i = 0; i < packageNames.length; i++) { 10771 String packageName = packageNames[i]; 10772 long callingId = Binder.clearCallingIdentity(); 10773 try { 10774 boolean changed = false; 10775 final int appId; 10776 synchronized (mPackages) { 10777 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10778 if (pkgSetting == null) { 10779 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10780 + "\". Skipping suspending/un-suspending."); 10781 unactionedPackages.add(packageName); 10782 continue; 10783 } 10784 appId = pkgSetting.appId; 10785 if (pkgSetting.getSuspended(userId) != suspended) { 10786 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10787 unactionedPackages.add(packageName); 10788 continue; 10789 } 10790 pkgSetting.setSuspended(suspended, userId); 10791 mSettings.writePackageRestrictionsLPr(userId); 10792 changed = true; 10793 changedPackages.add(packageName); 10794 } 10795 } 10796 10797 if (changed && suspended) { 10798 killApplication(packageName, UserHandle.getUid(userId, appId), 10799 "suspending package"); 10800 } 10801 } finally { 10802 Binder.restoreCallingIdentity(callingId); 10803 } 10804 } 10805 10806 if (!changedPackages.isEmpty()) { 10807 sendPackagesSuspendedForUser(changedPackages.toArray( 10808 new String[changedPackages.size()]), userId, suspended); 10809 } 10810 10811 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10812 } 10813 10814 @Override 10815 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10816 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10817 true /* requireFullPermission */, false /* checkShell */, 10818 "isPackageSuspendedForUser for user " + userId); 10819 synchronized (mPackages) { 10820 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10821 return pkgSetting != null && pkgSetting.getSuspended(userId); 10822 } 10823 } 10824 10825 // TODO: investigate and add more restrictions for suspending crucial packages. 10826 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10827 if (isPackageDeviceAdmin(packageName, userId)) { 10828 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10829 + "\": has active device admin"); 10830 return false; 10831 } 10832 10833 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10834 if (packageName.equals(activeLauncherPackageName)) { 10835 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10836 + "\" because it is set as the active launcher"); 10837 return false; 10838 } 10839 10840 final PackageParser.Package pkg = mPackages.get(packageName); 10841 if (pkg != null && isPrivilegedApp(pkg)) { 10842 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10843 + "\" because it is a privileged app"); 10844 return false; 10845 } 10846 10847 return true; 10848 } 10849 10850 private String getActiveLauncherPackageName(int userId) { 10851 Intent intent = new Intent(Intent.ACTION_MAIN); 10852 intent.addCategory(Intent.CATEGORY_HOME); 10853 ResolveInfo resolveInfo = resolveIntent( 10854 intent, 10855 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10856 PackageManager.MATCH_DEFAULT_ONLY, 10857 userId); 10858 10859 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10860 } 10861 10862 @Override 10863 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10864 mContext.enforceCallingOrSelfPermission( 10865 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10866 "Only package verification agents can verify applications"); 10867 10868 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10869 final PackageVerificationResponse response = new PackageVerificationResponse( 10870 verificationCode, Binder.getCallingUid()); 10871 msg.arg1 = id; 10872 msg.obj = response; 10873 mHandler.sendMessage(msg); 10874 } 10875 10876 @Override 10877 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10878 long millisecondsToDelay) { 10879 mContext.enforceCallingOrSelfPermission( 10880 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10881 "Only package verification agents can extend verification timeouts"); 10882 10883 final PackageVerificationState state = mPendingVerification.get(id); 10884 final PackageVerificationResponse response = new PackageVerificationResponse( 10885 verificationCodeAtTimeout, Binder.getCallingUid()); 10886 10887 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10888 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10889 } 10890 if (millisecondsToDelay < 0) { 10891 millisecondsToDelay = 0; 10892 } 10893 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10894 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10895 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10896 } 10897 10898 if ((state != null) && !state.timeoutExtended()) { 10899 state.extendTimeout(); 10900 10901 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10902 msg.arg1 = id; 10903 msg.obj = response; 10904 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10905 } 10906 } 10907 10908 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10909 int verificationCode, UserHandle user) { 10910 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10911 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10912 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10913 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10914 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10915 10916 mContext.sendBroadcastAsUser(intent, user, 10917 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10918 } 10919 10920 private ComponentName matchComponentForVerifier(String packageName, 10921 List<ResolveInfo> receivers) { 10922 ActivityInfo targetReceiver = null; 10923 10924 final int NR = receivers.size(); 10925 for (int i = 0; i < NR; i++) { 10926 final ResolveInfo info = receivers.get(i); 10927 if (info.activityInfo == null) { 10928 continue; 10929 } 10930 10931 if (packageName.equals(info.activityInfo.packageName)) { 10932 targetReceiver = info.activityInfo; 10933 break; 10934 } 10935 } 10936 10937 if (targetReceiver == null) { 10938 return null; 10939 } 10940 10941 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10942 } 10943 10944 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10945 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10946 if (pkgInfo.verifiers.length == 0) { 10947 return null; 10948 } 10949 10950 final int N = pkgInfo.verifiers.length; 10951 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10952 for (int i = 0; i < N; i++) { 10953 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10954 10955 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10956 receivers); 10957 if (comp == null) { 10958 continue; 10959 } 10960 10961 final int verifierUid = getUidForVerifier(verifierInfo); 10962 if (verifierUid == -1) { 10963 continue; 10964 } 10965 10966 if (DEBUG_VERIFY) { 10967 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10968 + " with the correct signature"); 10969 } 10970 sufficientVerifiers.add(comp); 10971 verificationState.addSufficientVerifier(verifierUid); 10972 } 10973 10974 return sufficientVerifiers; 10975 } 10976 10977 private int getUidForVerifier(VerifierInfo verifierInfo) { 10978 synchronized (mPackages) { 10979 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10980 if (pkg == null) { 10981 return -1; 10982 } else if (pkg.mSignatures.length != 1) { 10983 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10984 + " has more than one signature; ignoring"); 10985 return -1; 10986 } 10987 10988 /* 10989 * If the public key of the package's signature does not match 10990 * our expected public key, then this is a different package and 10991 * we should skip. 10992 */ 10993 10994 final byte[] expectedPublicKey; 10995 try { 10996 final Signature verifierSig = pkg.mSignatures[0]; 10997 final PublicKey publicKey = verifierSig.getPublicKey(); 10998 expectedPublicKey = publicKey.getEncoded(); 10999 } catch (CertificateException e) { 11000 return -1; 11001 } 11002 11003 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11004 11005 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11006 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11007 + " does not have the expected public key; ignoring"); 11008 return -1; 11009 } 11010 11011 return pkg.applicationInfo.uid; 11012 } 11013 } 11014 11015 @Override 11016 public void finishPackageInstall(int token) { 11017 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11018 11019 if (DEBUG_INSTALL) { 11020 Slog.v(TAG, "BM finishing package install for " + token); 11021 } 11022 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11023 11024 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11025 mHandler.sendMessage(msg); 11026 } 11027 11028 /** 11029 * Get the verification agent timeout. 11030 * 11031 * @return verification timeout in milliseconds 11032 */ 11033 private long getVerificationTimeout() { 11034 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11035 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11036 DEFAULT_VERIFICATION_TIMEOUT); 11037 } 11038 11039 /** 11040 * Get the default verification agent response code. 11041 * 11042 * @return default verification response code 11043 */ 11044 private int getDefaultVerificationResponse() { 11045 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11046 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11047 DEFAULT_VERIFICATION_RESPONSE); 11048 } 11049 11050 /** 11051 * Check whether or not package verification has been enabled. 11052 * 11053 * @return true if verification should be performed 11054 */ 11055 private boolean isVerificationEnabled(int userId, int installFlags) { 11056 if (!DEFAULT_VERIFY_ENABLE) { 11057 return false; 11058 } 11059 // Ephemeral apps don't get the full verification treatment 11060 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11061 if (DEBUG_EPHEMERAL) { 11062 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11063 } 11064 return false; 11065 } 11066 11067 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11068 11069 // Check if installing from ADB 11070 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11071 // Do not run verification in a test harness environment 11072 if (ActivityManager.isRunningInTestHarness()) { 11073 return false; 11074 } 11075 if (ensureVerifyAppsEnabled) { 11076 return true; 11077 } 11078 // Check if the developer does not want package verification for ADB installs 11079 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11080 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11081 return false; 11082 } 11083 } 11084 11085 if (ensureVerifyAppsEnabled) { 11086 return true; 11087 } 11088 11089 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11090 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11091 } 11092 11093 @Override 11094 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11095 throws RemoteException { 11096 mContext.enforceCallingOrSelfPermission( 11097 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11098 "Only intentfilter verification agents can verify applications"); 11099 11100 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11101 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11102 Binder.getCallingUid(), verificationCode, failedDomains); 11103 msg.arg1 = id; 11104 msg.obj = response; 11105 mHandler.sendMessage(msg); 11106 } 11107 11108 @Override 11109 public int getIntentVerificationStatus(String packageName, int userId) { 11110 synchronized (mPackages) { 11111 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11112 } 11113 } 11114 11115 @Override 11116 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11117 mContext.enforceCallingOrSelfPermission( 11118 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11119 11120 boolean result = false; 11121 synchronized (mPackages) { 11122 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11123 } 11124 if (result) { 11125 scheduleWritePackageRestrictionsLocked(userId); 11126 } 11127 return result; 11128 } 11129 11130 @Override 11131 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11132 String packageName) { 11133 synchronized (mPackages) { 11134 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11135 } 11136 } 11137 11138 @Override 11139 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11140 if (TextUtils.isEmpty(packageName)) { 11141 return ParceledListSlice.emptyList(); 11142 } 11143 synchronized (mPackages) { 11144 PackageParser.Package pkg = mPackages.get(packageName); 11145 if (pkg == null || pkg.activities == null) { 11146 return ParceledListSlice.emptyList(); 11147 } 11148 final int count = pkg.activities.size(); 11149 ArrayList<IntentFilter> result = new ArrayList<>(); 11150 for (int n=0; n<count; n++) { 11151 PackageParser.Activity activity = pkg.activities.get(n); 11152 if (activity.intents != null && activity.intents.size() > 0) { 11153 result.addAll(activity.intents); 11154 } 11155 } 11156 return new ParceledListSlice<>(result); 11157 } 11158 } 11159 11160 @Override 11161 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11162 mContext.enforceCallingOrSelfPermission( 11163 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11164 11165 synchronized (mPackages) { 11166 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11167 if (packageName != null) { 11168 result |= updateIntentVerificationStatus(packageName, 11169 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11170 userId); 11171 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11172 packageName, userId); 11173 } 11174 return result; 11175 } 11176 } 11177 11178 @Override 11179 public String getDefaultBrowserPackageName(int userId) { 11180 synchronized (mPackages) { 11181 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11182 } 11183 } 11184 11185 /** 11186 * Get the "allow unknown sources" setting. 11187 * 11188 * @return the current "allow unknown sources" setting 11189 */ 11190 private int getUnknownSourcesSettings() { 11191 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11192 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11193 -1); 11194 } 11195 11196 @Override 11197 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11198 final int uid = Binder.getCallingUid(); 11199 // writer 11200 synchronized (mPackages) { 11201 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11202 if (targetPackageSetting == null) { 11203 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11204 } 11205 11206 PackageSetting installerPackageSetting; 11207 if (installerPackageName != null) { 11208 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11209 if (installerPackageSetting == null) { 11210 throw new IllegalArgumentException("Unknown installer package: " 11211 + installerPackageName); 11212 } 11213 } else { 11214 installerPackageSetting = null; 11215 } 11216 11217 Signature[] callerSignature; 11218 Object obj = mSettings.getUserIdLPr(uid); 11219 if (obj != null) { 11220 if (obj instanceof SharedUserSetting) { 11221 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11222 } else if (obj instanceof PackageSetting) { 11223 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11224 } else { 11225 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11226 } 11227 } else { 11228 throw new SecurityException("Unknown calling UID: " + uid); 11229 } 11230 11231 // Verify: can't set installerPackageName to a package that is 11232 // not signed with the same cert as the caller. 11233 if (installerPackageSetting != null) { 11234 if (compareSignatures(callerSignature, 11235 installerPackageSetting.signatures.mSignatures) 11236 != PackageManager.SIGNATURE_MATCH) { 11237 throw new SecurityException( 11238 "Caller does not have same cert as new installer package " 11239 + installerPackageName); 11240 } 11241 } 11242 11243 // Verify: if target already has an installer package, it must 11244 // be signed with the same cert as the caller. 11245 if (targetPackageSetting.installerPackageName != null) { 11246 PackageSetting setting = mSettings.mPackages.get( 11247 targetPackageSetting.installerPackageName); 11248 // If the currently set package isn't valid, then it's always 11249 // okay to change it. 11250 if (setting != null) { 11251 if (compareSignatures(callerSignature, 11252 setting.signatures.mSignatures) 11253 != PackageManager.SIGNATURE_MATCH) { 11254 throw new SecurityException( 11255 "Caller does not have same cert as old installer package " 11256 + targetPackageSetting.installerPackageName); 11257 } 11258 } 11259 } 11260 11261 // Okay! 11262 targetPackageSetting.installerPackageName = installerPackageName; 11263 scheduleWriteSettingsLocked(); 11264 } 11265 } 11266 11267 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11268 // Queue up an async operation since the package installation may take a little while. 11269 mHandler.post(new Runnable() { 11270 public void run() { 11271 mHandler.removeCallbacks(this); 11272 // Result object to be returned 11273 PackageInstalledInfo res = new PackageInstalledInfo(); 11274 res.setReturnCode(currentStatus); 11275 res.uid = -1; 11276 res.pkg = null; 11277 res.removedInfo = null; 11278 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11279 args.doPreInstall(res.returnCode); 11280 synchronized (mInstallLock) { 11281 installPackageTracedLI(args, res); 11282 } 11283 args.doPostInstall(res.returnCode, res.uid); 11284 } 11285 11286 // A restore should be performed at this point if (a) the install 11287 // succeeded, (b) the operation is not an update, and (c) the new 11288 // package has not opted out of backup participation. 11289 final boolean update = res.removedInfo != null 11290 && res.removedInfo.removedPackage != null; 11291 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11292 boolean doRestore = !update 11293 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11294 11295 // Set up the post-install work request bookkeeping. This will be used 11296 // and cleaned up by the post-install event handling regardless of whether 11297 // there's a restore pass performed. Token values are >= 1. 11298 int token; 11299 if (mNextInstallToken < 0) mNextInstallToken = 1; 11300 token = mNextInstallToken++; 11301 11302 PostInstallData data = new PostInstallData(args, res); 11303 mRunningInstalls.put(token, data); 11304 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11305 11306 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11307 // Pass responsibility to the Backup Manager. It will perform a 11308 // restore if appropriate, then pass responsibility back to the 11309 // Package Manager to run the post-install observer callbacks 11310 // and broadcasts. 11311 IBackupManager bm = IBackupManager.Stub.asInterface( 11312 ServiceManager.getService(Context.BACKUP_SERVICE)); 11313 if (bm != null) { 11314 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11315 + " to BM for possible restore"); 11316 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11317 try { 11318 // TODO: http://b/22388012 11319 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11320 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11321 } else { 11322 doRestore = false; 11323 } 11324 } catch (RemoteException e) { 11325 // can't happen; the backup manager is local 11326 } catch (Exception e) { 11327 Slog.e(TAG, "Exception trying to enqueue restore", e); 11328 doRestore = false; 11329 } 11330 } else { 11331 Slog.e(TAG, "Backup Manager not found!"); 11332 doRestore = false; 11333 } 11334 } 11335 11336 if (!doRestore) { 11337 // No restore possible, or the Backup Manager was mysteriously not 11338 // available -- just fire the post-install work request directly. 11339 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11340 11341 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11342 11343 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11344 mHandler.sendMessage(msg); 11345 } 11346 } 11347 }); 11348 } 11349 11350 private abstract class HandlerParams { 11351 private static final int MAX_RETRIES = 4; 11352 11353 /** 11354 * Number of times startCopy() has been attempted and had a non-fatal 11355 * error. 11356 */ 11357 private int mRetries = 0; 11358 11359 /** User handle for the user requesting the information or installation. */ 11360 private final UserHandle mUser; 11361 String traceMethod; 11362 int traceCookie; 11363 11364 HandlerParams(UserHandle user) { 11365 mUser = user; 11366 } 11367 11368 UserHandle getUser() { 11369 return mUser; 11370 } 11371 11372 HandlerParams setTraceMethod(String traceMethod) { 11373 this.traceMethod = traceMethod; 11374 return this; 11375 } 11376 11377 HandlerParams setTraceCookie(int traceCookie) { 11378 this.traceCookie = traceCookie; 11379 return this; 11380 } 11381 11382 final boolean startCopy() { 11383 boolean res; 11384 try { 11385 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11386 11387 if (++mRetries > MAX_RETRIES) { 11388 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11389 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11390 handleServiceError(); 11391 return false; 11392 } else { 11393 handleStartCopy(); 11394 res = true; 11395 } 11396 } catch (RemoteException e) { 11397 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11398 mHandler.sendEmptyMessage(MCS_RECONNECT); 11399 res = false; 11400 } 11401 handleReturnCode(); 11402 return res; 11403 } 11404 11405 final void serviceError() { 11406 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11407 handleServiceError(); 11408 handleReturnCode(); 11409 } 11410 11411 abstract void handleStartCopy() throws RemoteException; 11412 abstract void handleServiceError(); 11413 abstract void handleReturnCode(); 11414 } 11415 11416 class MeasureParams extends HandlerParams { 11417 private final PackageStats mStats; 11418 private boolean mSuccess; 11419 11420 private final IPackageStatsObserver mObserver; 11421 11422 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11423 super(new UserHandle(stats.userHandle)); 11424 mObserver = observer; 11425 mStats = stats; 11426 } 11427 11428 @Override 11429 public String toString() { 11430 return "MeasureParams{" 11431 + Integer.toHexString(System.identityHashCode(this)) 11432 + " " + mStats.packageName + "}"; 11433 } 11434 11435 @Override 11436 void handleStartCopy() throws RemoteException { 11437 synchronized (mInstallLock) { 11438 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11439 } 11440 11441 if (mSuccess) { 11442 final boolean mounted; 11443 if (Environment.isExternalStorageEmulated()) { 11444 mounted = true; 11445 } else { 11446 final String status = Environment.getExternalStorageState(); 11447 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11448 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11449 } 11450 11451 if (mounted) { 11452 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11453 11454 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11455 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11456 11457 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11458 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11459 11460 // Always subtract cache size, since it's a subdirectory 11461 mStats.externalDataSize -= mStats.externalCacheSize; 11462 11463 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11464 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11465 11466 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11467 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11468 } 11469 } 11470 } 11471 11472 @Override 11473 void handleReturnCode() { 11474 if (mObserver != null) { 11475 try { 11476 mObserver.onGetStatsCompleted(mStats, mSuccess); 11477 } catch (RemoteException e) { 11478 Slog.i(TAG, "Observer no longer exists."); 11479 } 11480 } 11481 } 11482 11483 @Override 11484 void handleServiceError() { 11485 Slog.e(TAG, "Could not measure application " + mStats.packageName 11486 + " external storage"); 11487 } 11488 } 11489 11490 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11491 throws RemoteException { 11492 long result = 0; 11493 for (File path : paths) { 11494 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11495 } 11496 return result; 11497 } 11498 11499 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11500 for (File path : paths) { 11501 try { 11502 mcs.clearDirectory(path.getAbsolutePath()); 11503 } catch (RemoteException e) { 11504 } 11505 } 11506 } 11507 11508 static class OriginInfo { 11509 /** 11510 * Location where install is coming from, before it has been 11511 * copied/renamed into place. This could be a single monolithic APK 11512 * file, or a cluster directory. This location may be untrusted. 11513 */ 11514 final File file; 11515 final String cid; 11516 11517 /** 11518 * Flag indicating that {@link #file} or {@link #cid} has already been 11519 * staged, meaning downstream users don't need to defensively copy the 11520 * contents. 11521 */ 11522 final boolean staged; 11523 11524 /** 11525 * Flag indicating that {@link #file} or {@link #cid} is an already 11526 * installed app that is being moved. 11527 */ 11528 final boolean existing; 11529 11530 final String resolvedPath; 11531 final File resolvedFile; 11532 11533 static OriginInfo fromNothing() { 11534 return new OriginInfo(null, null, false, false); 11535 } 11536 11537 static OriginInfo fromUntrustedFile(File file) { 11538 return new OriginInfo(file, null, false, false); 11539 } 11540 11541 static OriginInfo fromExistingFile(File file) { 11542 return new OriginInfo(file, null, false, true); 11543 } 11544 11545 static OriginInfo fromStagedFile(File file) { 11546 return new OriginInfo(file, null, true, false); 11547 } 11548 11549 static OriginInfo fromStagedContainer(String cid) { 11550 return new OriginInfo(null, cid, true, false); 11551 } 11552 11553 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11554 this.file = file; 11555 this.cid = cid; 11556 this.staged = staged; 11557 this.existing = existing; 11558 11559 if (cid != null) { 11560 resolvedPath = PackageHelper.getSdDir(cid); 11561 resolvedFile = new File(resolvedPath); 11562 } else if (file != null) { 11563 resolvedPath = file.getAbsolutePath(); 11564 resolvedFile = file; 11565 } else { 11566 resolvedPath = null; 11567 resolvedFile = null; 11568 } 11569 } 11570 } 11571 11572 static class MoveInfo { 11573 final int moveId; 11574 final String fromUuid; 11575 final String toUuid; 11576 final String packageName; 11577 final String dataAppName; 11578 final int appId; 11579 final String seinfo; 11580 final int targetSdkVersion; 11581 11582 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11583 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11584 this.moveId = moveId; 11585 this.fromUuid = fromUuid; 11586 this.toUuid = toUuid; 11587 this.packageName = packageName; 11588 this.dataAppName = dataAppName; 11589 this.appId = appId; 11590 this.seinfo = seinfo; 11591 this.targetSdkVersion = targetSdkVersion; 11592 } 11593 } 11594 11595 static class VerificationInfo { 11596 /** A constant used to indicate that a uid value is not present. */ 11597 public static final int NO_UID = -1; 11598 11599 /** URI referencing where the package was downloaded from. */ 11600 final Uri originatingUri; 11601 11602 /** HTTP referrer URI associated with the originatingURI. */ 11603 final Uri referrer; 11604 11605 /** UID of the application that the install request originated from. */ 11606 final int originatingUid; 11607 11608 /** UID of application requesting the install */ 11609 final int installerUid; 11610 11611 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11612 this.originatingUri = originatingUri; 11613 this.referrer = referrer; 11614 this.originatingUid = originatingUid; 11615 this.installerUid = installerUid; 11616 } 11617 } 11618 11619 class InstallParams extends HandlerParams { 11620 final OriginInfo origin; 11621 final MoveInfo move; 11622 final IPackageInstallObserver2 observer; 11623 int installFlags; 11624 final String installerPackageName; 11625 final String volumeUuid; 11626 private InstallArgs mArgs; 11627 private int mRet; 11628 final String packageAbiOverride; 11629 final String[] grantedRuntimePermissions; 11630 final VerificationInfo verificationInfo; 11631 11632 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11633 int installFlags, String installerPackageName, String volumeUuid, 11634 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11635 String[] grantedPermissions) { 11636 super(user); 11637 this.origin = origin; 11638 this.move = move; 11639 this.observer = observer; 11640 this.installFlags = installFlags; 11641 this.installerPackageName = installerPackageName; 11642 this.volumeUuid = volumeUuid; 11643 this.verificationInfo = verificationInfo; 11644 this.packageAbiOverride = packageAbiOverride; 11645 this.grantedRuntimePermissions = grantedPermissions; 11646 } 11647 11648 @Override 11649 public String toString() { 11650 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11651 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11652 } 11653 11654 private int installLocationPolicy(PackageInfoLite pkgLite) { 11655 String packageName = pkgLite.packageName; 11656 int installLocation = pkgLite.installLocation; 11657 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11658 // reader 11659 synchronized (mPackages) { 11660 // Currently installed package which the new package is attempting to replace or 11661 // null if no such package is installed. 11662 PackageParser.Package installedPkg = mPackages.get(packageName); 11663 // Package which currently owns the data which the new package will own if installed. 11664 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11665 // will be null whereas dataOwnerPkg will contain information about the package 11666 // which was uninstalled while keeping its data. 11667 PackageParser.Package dataOwnerPkg = installedPkg; 11668 if (dataOwnerPkg == null) { 11669 PackageSetting ps = mSettings.mPackages.get(packageName); 11670 if (ps != null) { 11671 dataOwnerPkg = ps.pkg; 11672 } 11673 } 11674 11675 if (dataOwnerPkg != null) { 11676 // If installed, the package will get access to data left on the device by its 11677 // predecessor. As a security measure, this is permited only if this is not a 11678 // version downgrade or if the predecessor package is marked as debuggable and 11679 // a downgrade is explicitly requested. 11680 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11681 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11682 try { 11683 checkDowngrade(dataOwnerPkg, pkgLite); 11684 } catch (PackageManagerException e) { 11685 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11686 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11687 } 11688 } 11689 } 11690 11691 if (installedPkg != null) { 11692 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11693 // Check for updated system application. 11694 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11695 if (onSd) { 11696 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11697 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11698 } 11699 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11700 } else { 11701 if (onSd) { 11702 // Install flag overrides everything. 11703 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11704 } 11705 // If current upgrade specifies particular preference 11706 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11707 // Application explicitly specified internal. 11708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11709 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11710 // App explictly prefers external. Let policy decide 11711 } else { 11712 // Prefer previous location 11713 if (isExternal(installedPkg)) { 11714 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11715 } 11716 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11717 } 11718 } 11719 } else { 11720 // Invalid install. Return error code 11721 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11722 } 11723 } 11724 } 11725 // All the special cases have been taken care of. 11726 // Return result based on recommended install location. 11727 if (onSd) { 11728 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11729 } 11730 return pkgLite.recommendedInstallLocation; 11731 } 11732 11733 /* 11734 * Invoke remote method to get package information and install 11735 * location values. Override install location based on default 11736 * policy if needed and then create install arguments based 11737 * on the install location. 11738 */ 11739 public void handleStartCopy() throws RemoteException { 11740 int ret = PackageManager.INSTALL_SUCCEEDED; 11741 11742 // If we're already staged, we've firmly committed to an install location 11743 if (origin.staged) { 11744 if (origin.file != null) { 11745 installFlags |= PackageManager.INSTALL_INTERNAL; 11746 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11747 } else if (origin.cid != null) { 11748 installFlags |= PackageManager.INSTALL_EXTERNAL; 11749 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11750 } else { 11751 throw new IllegalStateException("Invalid stage location"); 11752 } 11753 } 11754 11755 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11756 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11757 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11758 PackageInfoLite pkgLite = null; 11759 11760 if (onInt && onSd) { 11761 // Check if both bits are set. 11762 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11763 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11764 } else if (onSd && ephemeral) { 11765 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11766 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11767 } else { 11768 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11769 packageAbiOverride); 11770 11771 if (DEBUG_EPHEMERAL && ephemeral) { 11772 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11773 } 11774 11775 /* 11776 * If we have too little free space, try to free cache 11777 * before giving up. 11778 */ 11779 if (!origin.staged && pkgLite.recommendedInstallLocation 11780 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11781 // TODO: focus freeing disk space on the target device 11782 final StorageManager storage = StorageManager.from(mContext); 11783 final long lowThreshold = storage.getStorageLowBytes( 11784 Environment.getDataDirectory()); 11785 11786 final long sizeBytes = mContainerService.calculateInstalledSize( 11787 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11788 11789 try { 11790 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11791 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11792 installFlags, packageAbiOverride); 11793 } catch (InstallerException e) { 11794 Slog.w(TAG, "Failed to free cache", e); 11795 } 11796 11797 /* 11798 * The cache free must have deleted the file we 11799 * downloaded to install. 11800 * 11801 * TODO: fix the "freeCache" call to not delete 11802 * the file we care about. 11803 */ 11804 if (pkgLite.recommendedInstallLocation 11805 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11806 pkgLite.recommendedInstallLocation 11807 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11808 } 11809 } 11810 } 11811 11812 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11813 int loc = pkgLite.recommendedInstallLocation; 11814 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11815 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11816 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11817 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11818 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11819 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11820 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11821 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11822 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11823 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11824 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11825 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11826 } else { 11827 // Override with defaults if needed. 11828 loc = installLocationPolicy(pkgLite); 11829 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11830 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11831 } else if (!onSd && !onInt) { 11832 // Override install location with flags 11833 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11834 // Set the flag to install on external media. 11835 installFlags |= PackageManager.INSTALL_EXTERNAL; 11836 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11837 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11838 if (DEBUG_EPHEMERAL) { 11839 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11840 } 11841 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11842 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11843 |PackageManager.INSTALL_INTERNAL); 11844 } else { 11845 // Make sure the flag for installing on external 11846 // media is unset 11847 installFlags |= PackageManager.INSTALL_INTERNAL; 11848 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11849 } 11850 } 11851 } 11852 } 11853 11854 final InstallArgs args = createInstallArgs(this); 11855 mArgs = args; 11856 11857 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11858 // TODO: http://b/22976637 11859 // Apps installed for "all" users use the device owner to verify the app 11860 UserHandle verifierUser = getUser(); 11861 if (verifierUser == UserHandle.ALL) { 11862 verifierUser = UserHandle.SYSTEM; 11863 } 11864 11865 /* 11866 * Determine if we have any installed package verifiers. If we 11867 * do, then we'll defer to them to verify the packages. 11868 */ 11869 final int requiredUid = mRequiredVerifierPackage == null ? -1 11870 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11871 verifierUser.getIdentifier()); 11872 if (!origin.existing && requiredUid != -1 11873 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11874 final Intent verification = new Intent( 11875 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11876 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11877 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11878 PACKAGE_MIME_TYPE); 11879 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11880 11881 // Query all live verifiers based on current user state 11882 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11883 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11884 11885 if (DEBUG_VERIFY) { 11886 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11887 + verification.toString() + " with " + pkgLite.verifiers.length 11888 + " optional verifiers"); 11889 } 11890 11891 final int verificationId = mPendingVerificationToken++; 11892 11893 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11894 11895 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11896 installerPackageName); 11897 11898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11899 installFlags); 11900 11901 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11902 pkgLite.packageName); 11903 11904 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11905 pkgLite.versionCode); 11906 11907 if (verificationInfo != null) { 11908 if (verificationInfo.originatingUri != null) { 11909 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11910 verificationInfo.originatingUri); 11911 } 11912 if (verificationInfo.referrer != null) { 11913 verification.putExtra(Intent.EXTRA_REFERRER, 11914 verificationInfo.referrer); 11915 } 11916 if (verificationInfo.originatingUid >= 0) { 11917 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11918 verificationInfo.originatingUid); 11919 } 11920 if (verificationInfo.installerUid >= 0) { 11921 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11922 verificationInfo.installerUid); 11923 } 11924 } 11925 11926 final PackageVerificationState verificationState = new PackageVerificationState( 11927 requiredUid, args); 11928 11929 mPendingVerification.append(verificationId, verificationState); 11930 11931 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11932 receivers, verificationState); 11933 11934 /* 11935 * If any sufficient verifiers were listed in the package 11936 * manifest, attempt to ask them. 11937 */ 11938 if (sufficientVerifiers != null) { 11939 final int N = sufficientVerifiers.size(); 11940 if (N == 0) { 11941 Slog.i(TAG, "Additional verifiers required, but none installed."); 11942 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11943 } else { 11944 for (int i = 0; i < N; i++) { 11945 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11946 11947 final Intent sufficientIntent = new Intent(verification); 11948 sufficientIntent.setComponent(verifierComponent); 11949 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11950 } 11951 } 11952 } 11953 11954 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11955 mRequiredVerifierPackage, receivers); 11956 if (ret == PackageManager.INSTALL_SUCCEEDED 11957 && mRequiredVerifierPackage != null) { 11958 Trace.asyncTraceBegin( 11959 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11960 /* 11961 * Send the intent to the required verification agent, 11962 * but only start the verification timeout after the 11963 * target BroadcastReceivers have run. 11964 */ 11965 verification.setComponent(requiredVerifierComponent); 11966 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11967 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11968 new BroadcastReceiver() { 11969 @Override 11970 public void onReceive(Context context, Intent intent) { 11971 final Message msg = mHandler 11972 .obtainMessage(CHECK_PENDING_VERIFICATION); 11973 msg.arg1 = verificationId; 11974 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11975 } 11976 }, null, 0, null, null); 11977 11978 /* 11979 * We don't want the copy to proceed until verification 11980 * succeeds, so null out this field. 11981 */ 11982 mArgs = null; 11983 } 11984 } else { 11985 /* 11986 * No package verification is enabled, so immediately start 11987 * the remote call to initiate copy using temporary file. 11988 */ 11989 ret = args.copyApk(mContainerService, true); 11990 } 11991 } 11992 11993 mRet = ret; 11994 } 11995 11996 @Override 11997 void handleReturnCode() { 11998 // If mArgs is null, then MCS couldn't be reached. When it 11999 // reconnects, it will try again to install. At that point, this 12000 // will succeed. 12001 if (mArgs != null) { 12002 processPendingInstall(mArgs, mRet); 12003 } 12004 } 12005 12006 @Override 12007 void handleServiceError() { 12008 mArgs = createInstallArgs(this); 12009 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12010 } 12011 12012 public boolean isForwardLocked() { 12013 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12014 } 12015 } 12016 12017 /** 12018 * Used during creation of InstallArgs 12019 * 12020 * @param installFlags package installation flags 12021 * @return true if should be installed on external storage 12022 */ 12023 private static boolean installOnExternalAsec(int installFlags) { 12024 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12025 return false; 12026 } 12027 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12028 return true; 12029 } 12030 return false; 12031 } 12032 12033 /** 12034 * Used during creation of InstallArgs 12035 * 12036 * @param installFlags package installation flags 12037 * @return true if should be installed as forward locked 12038 */ 12039 private static boolean installForwardLocked(int installFlags) { 12040 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12041 } 12042 12043 private InstallArgs createInstallArgs(InstallParams params) { 12044 if (params.move != null) { 12045 return new MoveInstallArgs(params); 12046 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12047 return new AsecInstallArgs(params); 12048 } else { 12049 return new FileInstallArgs(params); 12050 } 12051 } 12052 12053 /** 12054 * Create args that describe an existing installed package. Typically used 12055 * when cleaning up old installs, or used as a move source. 12056 */ 12057 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12058 String resourcePath, String[] instructionSets) { 12059 final boolean isInAsec; 12060 if (installOnExternalAsec(installFlags)) { 12061 /* Apps on SD card are always in ASEC containers. */ 12062 isInAsec = true; 12063 } else if (installForwardLocked(installFlags) 12064 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12065 /* 12066 * Forward-locked apps are only in ASEC containers if they're the 12067 * new style 12068 */ 12069 isInAsec = true; 12070 } else { 12071 isInAsec = false; 12072 } 12073 12074 if (isInAsec) { 12075 return new AsecInstallArgs(codePath, instructionSets, 12076 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12077 } else { 12078 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12079 } 12080 } 12081 12082 static abstract class InstallArgs { 12083 /** @see InstallParams#origin */ 12084 final OriginInfo origin; 12085 /** @see InstallParams#move */ 12086 final MoveInfo move; 12087 12088 final IPackageInstallObserver2 observer; 12089 // Always refers to PackageManager flags only 12090 final int installFlags; 12091 final String installerPackageName; 12092 final String volumeUuid; 12093 final UserHandle user; 12094 final String abiOverride; 12095 final String[] installGrantPermissions; 12096 /** If non-null, drop an async trace when the install completes */ 12097 final String traceMethod; 12098 final int traceCookie; 12099 12100 // The list of instruction sets supported by this app. This is currently 12101 // only used during the rmdex() phase to clean up resources. We can get rid of this 12102 // if we move dex files under the common app path. 12103 /* nullable */ String[] instructionSets; 12104 12105 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12106 int installFlags, String installerPackageName, String volumeUuid, 12107 UserHandle user, String[] instructionSets, 12108 String abiOverride, String[] installGrantPermissions, 12109 String traceMethod, int traceCookie) { 12110 this.origin = origin; 12111 this.move = move; 12112 this.installFlags = installFlags; 12113 this.observer = observer; 12114 this.installerPackageName = installerPackageName; 12115 this.volumeUuid = volumeUuid; 12116 this.user = user; 12117 this.instructionSets = instructionSets; 12118 this.abiOverride = abiOverride; 12119 this.installGrantPermissions = installGrantPermissions; 12120 this.traceMethod = traceMethod; 12121 this.traceCookie = traceCookie; 12122 } 12123 12124 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12125 abstract int doPreInstall(int status); 12126 12127 /** 12128 * Rename package into final resting place. All paths on the given 12129 * scanned package should be updated to reflect the rename. 12130 */ 12131 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12132 abstract int doPostInstall(int status, int uid); 12133 12134 /** @see PackageSettingBase#codePathString */ 12135 abstract String getCodePath(); 12136 /** @see PackageSettingBase#resourcePathString */ 12137 abstract String getResourcePath(); 12138 12139 // Need installer lock especially for dex file removal. 12140 abstract void cleanUpResourcesLI(); 12141 abstract boolean doPostDeleteLI(boolean delete); 12142 12143 /** 12144 * Called before the source arguments are copied. This is used mostly 12145 * for MoveParams when it needs to read the source file to put it in the 12146 * destination. 12147 */ 12148 int doPreCopy() { 12149 return PackageManager.INSTALL_SUCCEEDED; 12150 } 12151 12152 /** 12153 * Called after the source arguments are copied. This is used mostly for 12154 * MoveParams when it needs to read the source file to put it in the 12155 * destination. 12156 * 12157 * @return 12158 */ 12159 int doPostCopy(int uid) { 12160 return PackageManager.INSTALL_SUCCEEDED; 12161 } 12162 12163 protected boolean isFwdLocked() { 12164 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12165 } 12166 12167 protected boolean isExternalAsec() { 12168 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12169 } 12170 12171 protected boolean isEphemeral() { 12172 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12173 } 12174 12175 UserHandle getUser() { 12176 return user; 12177 } 12178 } 12179 12180 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12181 if (!allCodePaths.isEmpty()) { 12182 if (instructionSets == null) { 12183 throw new IllegalStateException("instructionSet == null"); 12184 } 12185 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12186 for (String codePath : allCodePaths) { 12187 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12188 try { 12189 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12190 } catch (InstallerException ignored) { 12191 } 12192 } 12193 } 12194 } 12195 } 12196 12197 /** 12198 * Logic to handle installation of non-ASEC applications, including copying 12199 * and renaming logic. 12200 */ 12201 class FileInstallArgs extends InstallArgs { 12202 private File codeFile; 12203 private File resourceFile; 12204 12205 // Example topology: 12206 // /data/app/com.example/base.apk 12207 // /data/app/com.example/split_foo.apk 12208 // /data/app/com.example/lib/arm/libfoo.so 12209 // /data/app/com.example/lib/arm64/libfoo.so 12210 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12211 12212 /** New install */ 12213 FileInstallArgs(InstallParams params) { 12214 super(params.origin, params.move, params.observer, params.installFlags, 12215 params.installerPackageName, params.volumeUuid, 12216 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12217 params.grantedRuntimePermissions, 12218 params.traceMethod, params.traceCookie); 12219 if (isFwdLocked()) { 12220 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12221 } 12222 } 12223 12224 /** Existing install */ 12225 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12226 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12227 null, null, null, 0); 12228 this.codeFile = (codePath != null) ? new File(codePath) : null; 12229 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12230 } 12231 12232 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12234 try { 12235 return doCopyApk(imcs, temp); 12236 } finally { 12237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12238 } 12239 } 12240 12241 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12242 if (origin.staged) { 12243 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12244 codeFile = origin.file; 12245 resourceFile = origin.file; 12246 return PackageManager.INSTALL_SUCCEEDED; 12247 } 12248 12249 try { 12250 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12251 final File tempDir = 12252 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12253 codeFile = tempDir; 12254 resourceFile = tempDir; 12255 } catch (IOException e) { 12256 Slog.w(TAG, "Failed to create copy file: " + e); 12257 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12258 } 12259 12260 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12261 @Override 12262 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12263 if (!FileUtils.isValidExtFilename(name)) { 12264 throw new IllegalArgumentException("Invalid filename: " + name); 12265 } 12266 try { 12267 final File file = new File(codeFile, name); 12268 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12269 O_RDWR | O_CREAT, 0644); 12270 Os.chmod(file.getAbsolutePath(), 0644); 12271 return new ParcelFileDescriptor(fd); 12272 } catch (ErrnoException e) { 12273 throw new RemoteException("Failed to open: " + e.getMessage()); 12274 } 12275 } 12276 }; 12277 12278 int ret = PackageManager.INSTALL_SUCCEEDED; 12279 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12280 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12281 Slog.e(TAG, "Failed to copy package"); 12282 return ret; 12283 } 12284 12285 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12286 NativeLibraryHelper.Handle handle = null; 12287 try { 12288 handle = NativeLibraryHelper.Handle.create(codeFile); 12289 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12290 abiOverride); 12291 } catch (IOException e) { 12292 Slog.e(TAG, "Copying native libraries failed", e); 12293 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12294 } finally { 12295 IoUtils.closeQuietly(handle); 12296 } 12297 12298 return ret; 12299 } 12300 12301 int doPreInstall(int status) { 12302 if (status != PackageManager.INSTALL_SUCCEEDED) { 12303 cleanUp(); 12304 } 12305 return status; 12306 } 12307 12308 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12309 if (status != PackageManager.INSTALL_SUCCEEDED) { 12310 cleanUp(); 12311 return false; 12312 } 12313 12314 final File targetDir = codeFile.getParentFile(); 12315 final File beforeCodeFile = codeFile; 12316 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12317 12318 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12319 try { 12320 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12321 } catch (ErrnoException e) { 12322 Slog.w(TAG, "Failed to rename", e); 12323 return false; 12324 } 12325 12326 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12327 Slog.w(TAG, "Failed to restorecon"); 12328 return false; 12329 } 12330 12331 // Reflect the rename internally 12332 codeFile = afterCodeFile; 12333 resourceFile = afterCodeFile; 12334 12335 // Reflect the rename in scanned details 12336 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12337 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12338 afterCodeFile, pkg.baseCodePath)); 12339 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12340 afterCodeFile, pkg.splitCodePaths)); 12341 12342 // Reflect the rename in app info 12343 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12344 pkg.setApplicationInfoCodePath(pkg.codePath); 12345 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12346 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12347 pkg.setApplicationInfoResourcePath(pkg.codePath); 12348 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12349 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12350 12351 return true; 12352 } 12353 12354 int doPostInstall(int status, int uid) { 12355 if (status != PackageManager.INSTALL_SUCCEEDED) { 12356 cleanUp(); 12357 } 12358 return status; 12359 } 12360 12361 @Override 12362 String getCodePath() { 12363 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12364 } 12365 12366 @Override 12367 String getResourcePath() { 12368 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12369 } 12370 12371 private boolean cleanUp() { 12372 if (codeFile == null || !codeFile.exists()) { 12373 return false; 12374 } 12375 12376 removeCodePathLI(codeFile); 12377 12378 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12379 resourceFile.delete(); 12380 } 12381 12382 return true; 12383 } 12384 12385 void cleanUpResourcesLI() { 12386 // Try enumerating all code paths before deleting 12387 List<String> allCodePaths = Collections.EMPTY_LIST; 12388 if (codeFile != null && codeFile.exists()) { 12389 try { 12390 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12391 allCodePaths = pkg.getAllCodePaths(); 12392 } catch (PackageParserException e) { 12393 // Ignored; we tried our best 12394 } 12395 } 12396 12397 cleanUp(); 12398 removeDexFiles(allCodePaths, instructionSets); 12399 } 12400 12401 boolean doPostDeleteLI(boolean delete) { 12402 // XXX err, shouldn't we respect the delete flag? 12403 cleanUpResourcesLI(); 12404 return true; 12405 } 12406 } 12407 12408 private boolean isAsecExternal(String cid) { 12409 final String asecPath = PackageHelper.getSdFilesystem(cid); 12410 return !asecPath.startsWith(mAsecInternalPath); 12411 } 12412 12413 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12414 PackageManagerException { 12415 if (copyRet < 0) { 12416 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12417 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12418 throw new PackageManagerException(copyRet, message); 12419 } 12420 } 12421 } 12422 12423 /** 12424 * Extract the MountService "container ID" from the full code path of an 12425 * .apk. 12426 */ 12427 static String cidFromCodePath(String fullCodePath) { 12428 int eidx = fullCodePath.lastIndexOf("/"); 12429 String subStr1 = fullCodePath.substring(0, eidx); 12430 int sidx = subStr1.lastIndexOf("/"); 12431 return subStr1.substring(sidx+1, eidx); 12432 } 12433 12434 /** 12435 * Logic to handle installation of ASEC applications, including copying and 12436 * renaming logic. 12437 */ 12438 class AsecInstallArgs extends InstallArgs { 12439 static final String RES_FILE_NAME = "pkg.apk"; 12440 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12441 12442 String cid; 12443 String packagePath; 12444 String resourcePath; 12445 12446 /** New install */ 12447 AsecInstallArgs(InstallParams params) { 12448 super(params.origin, params.move, params.observer, params.installFlags, 12449 params.installerPackageName, params.volumeUuid, 12450 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12451 params.grantedRuntimePermissions, 12452 params.traceMethod, params.traceCookie); 12453 } 12454 12455 /** Existing install */ 12456 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12457 boolean isExternal, boolean isForwardLocked) { 12458 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12459 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12460 instructionSets, null, null, null, 0); 12461 // Hackily pretend we're still looking at a full code path 12462 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12463 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12464 } 12465 12466 // Extract cid from fullCodePath 12467 int eidx = fullCodePath.lastIndexOf("/"); 12468 String subStr1 = fullCodePath.substring(0, eidx); 12469 int sidx = subStr1.lastIndexOf("/"); 12470 cid = subStr1.substring(sidx+1, eidx); 12471 setMountPath(subStr1); 12472 } 12473 12474 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12475 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12476 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12477 instructionSets, null, null, null, 0); 12478 this.cid = cid; 12479 setMountPath(PackageHelper.getSdDir(cid)); 12480 } 12481 12482 void createCopyFile() { 12483 cid = mInstallerService.allocateExternalStageCidLegacy(); 12484 } 12485 12486 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12487 if (origin.staged && origin.cid != null) { 12488 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12489 cid = origin.cid; 12490 setMountPath(PackageHelper.getSdDir(cid)); 12491 return PackageManager.INSTALL_SUCCEEDED; 12492 } 12493 12494 if (temp) { 12495 createCopyFile(); 12496 } else { 12497 /* 12498 * Pre-emptively destroy the container since it's destroyed if 12499 * copying fails due to it existing anyway. 12500 */ 12501 PackageHelper.destroySdDir(cid); 12502 } 12503 12504 final String newMountPath = imcs.copyPackageToContainer( 12505 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12506 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12507 12508 if (newMountPath != null) { 12509 setMountPath(newMountPath); 12510 return PackageManager.INSTALL_SUCCEEDED; 12511 } else { 12512 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12513 } 12514 } 12515 12516 @Override 12517 String getCodePath() { 12518 return packagePath; 12519 } 12520 12521 @Override 12522 String getResourcePath() { 12523 return resourcePath; 12524 } 12525 12526 int doPreInstall(int status) { 12527 if (status != PackageManager.INSTALL_SUCCEEDED) { 12528 // Destroy container 12529 PackageHelper.destroySdDir(cid); 12530 } else { 12531 boolean mounted = PackageHelper.isContainerMounted(cid); 12532 if (!mounted) { 12533 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12534 Process.SYSTEM_UID); 12535 if (newMountPath != null) { 12536 setMountPath(newMountPath); 12537 } else { 12538 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12539 } 12540 } 12541 } 12542 return status; 12543 } 12544 12545 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12546 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12547 String newMountPath = null; 12548 if (PackageHelper.isContainerMounted(cid)) { 12549 // Unmount the container 12550 if (!PackageHelper.unMountSdDir(cid)) { 12551 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12552 return false; 12553 } 12554 } 12555 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12556 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12557 " which might be stale. Will try to clean up."); 12558 // Clean up the stale container and proceed to recreate. 12559 if (!PackageHelper.destroySdDir(newCacheId)) { 12560 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12561 return false; 12562 } 12563 // Successfully cleaned up stale container. Try to rename again. 12564 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12565 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12566 + " inspite of cleaning it up."); 12567 return false; 12568 } 12569 } 12570 if (!PackageHelper.isContainerMounted(newCacheId)) { 12571 Slog.w(TAG, "Mounting container " + newCacheId); 12572 newMountPath = PackageHelper.mountSdDir(newCacheId, 12573 getEncryptKey(), Process.SYSTEM_UID); 12574 } else { 12575 newMountPath = PackageHelper.getSdDir(newCacheId); 12576 } 12577 if (newMountPath == null) { 12578 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12579 return false; 12580 } 12581 Log.i(TAG, "Succesfully renamed " + cid + 12582 " to " + newCacheId + 12583 " at new path: " + newMountPath); 12584 cid = newCacheId; 12585 12586 final File beforeCodeFile = new File(packagePath); 12587 setMountPath(newMountPath); 12588 final File afterCodeFile = new File(packagePath); 12589 12590 // Reflect the rename in scanned details 12591 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12592 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12593 afterCodeFile, pkg.baseCodePath)); 12594 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12595 afterCodeFile, pkg.splitCodePaths)); 12596 12597 // Reflect the rename in app info 12598 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12599 pkg.setApplicationInfoCodePath(pkg.codePath); 12600 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12601 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12602 pkg.setApplicationInfoResourcePath(pkg.codePath); 12603 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12604 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12605 12606 return true; 12607 } 12608 12609 private void setMountPath(String mountPath) { 12610 final File mountFile = new File(mountPath); 12611 12612 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12613 if (monolithicFile.exists()) { 12614 packagePath = monolithicFile.getAbsolutePath(); 12615 if (isFwdLocked()) { 12616 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12617 } else { 12618 resourcePath = packagePath; 12619 } 12620 } else { 12621 packagePath = mountFile.getAbsolutePath(); 12622 resourcePath = packagePath; 12623 } 12624 } 12625 12626 int doPostInstall(int status, int uid) { 12627 if (status != PackageManager.INSTALL_SUCCEEDED) { 12628 cleanUp(); 12629 } else { 12630 final int groupOwner; 12631 final String protectedFile; 12632 if (isFwdLocked()) { 12633 groupOwner = UserHandle.getSharedAppGid(uid); 12634 protectedFile = RES_FILE_NAME; 12635 } else { 12636 groupOwner = -1; 12637 protectedFile = null; 12638 } 12639 12640 if (uid < Process.FIRST_APPLICATION_UID 12641 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12642 Slog.e(TAG, "Failed to finalize " + cid); 12643 PackageHelper.destroySdDir(cid); 12644 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12645 } 12646 12647 boolean mounted = PackageHelper.isContainerMounted(cid); 12648 if (!mounted) { 12649 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12650 } 12651 } 12652 return status; 12653 } 12654 12655 private void cleanUp() { 12656 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12657 12658 // Destroy secure container 12659 PackageHelper.destroySdDir(cid); 12660 } 12661 12662 private List<String> getAllCodePaths() { 12663 final File codeFile = new File(getCodePath()); 12664 if (codeFile != null && codeFile.exists()) { 12665 try { 12666 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12667 return pkg.getAllCodePaths(); 12668 } catch (PackageParserException e) { 12669 // Ignored; we tried our best 12670 } 12671 } 12672 return Collections.EMPTY_LIST; 12673 } 12674 12675 void cleanUpResourcesLI() { 12676 // Enumerate all code paths before deleting 12677 cleanUpResourcesLI(getAllCodePaths()); 12678 } 12679 12680 private void cleanUpResourcesLI(List<String> allCodePaths) { 12681 cleanUp(); 12682 removeDexFiles(allCodePaths, instructionSets); 12683 } 12684 12685 String getPackageName() { 12686 return getAsecPackageName(cid); 12687 } 12688 12689 boolean doPostDeleteLI(boolean delete) { 12690 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12691 final List<String> allCodePaths = getAllCodePaths(); 12692 boolean mounted = PackageHelper.isContainerMounted(cid); 12693 if (mounted) { 12694 // Unmount first 12695 if (PackageHelper.unMountSdDir(cid)) { 12696 mounted = false; 12697 } 12698 } 12699 if (!mounted && delete) { 12700 cleanUpResourcesLI(allCodePaths); 12701 } 12702 return !mounted; 12703 } 12704 12705 @Override 12706 int doPreCopy() { 12707 if (isFwdLocked()) { 12708 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12709 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12710 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12711 } 12712 } 12713 12714 return PackageManager.INSTALL_SUCCEEDED; 12715 } 12716 12717 @Override 12718 int doPostCopy(int uid) { 12719 if (isFwdLocked()) { 12720 if (uid < Process.FIRST_APPLICATION_UID 12721 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12722 RES_FILE_NAME)) { 12723 Slog.e(TAG, "Failed to finalize " + cid); 12724 PackageHelper.destroySdDir(cid); 12725 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12726 } 12727 } 12728 12729 return PackageManager.INSTALL_SUCCEEDED; 12730 } 12731 } 12732 12733 /** 12734 * Logic to handle movement of existing installed applications. 12735 */ 12736 class MoveInstallArgs extends InstallArgs { 12737 private File codeFile; 12738 private File resourceFile; 12739 12740 /** New install */ 12741 MoveInstallArgs(InstallParams params) { 12742 super(params.origin, params.move, params.observer, params.installFlags, 12743 params.installerPackageName, params.volumeUuid, 12744 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12745 params.grantedRuntimePermissions, 12746 params.traceMethod, params.traceCookie); 12747 } 12748 12749 int copyApk(IMediaContainerService imcs, boolean temp) { 12750 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12751 + move.fromUuid + " to " + move.toUuid); 12752 synchronized (mInstaller) { 12753 try { 12754 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12755 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12756 } catch (InstallerException e) { 12757 Slog.w(TAG, "Failed to move app", e); 12758 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12759 } 12760 } 12761 12762 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12763 resourceFile = codeFile; 12764 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12765 12766 return PackageManager.INSTALL_SUCCEEDED; 12767 } 12768 12769 int doPreInstall(int status) { 12770 if (status != PackageManager.INSTALL_SUCCEEDED) { 12771 cleanUp(move.toUuid); 12772 } 12773 return status; 12774 } 12775 12776 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12777 if (status != PackageManager.INSTALL_SUCCEEDED) { 12778 cleanUp(move.toUuid); 12779 return false; 12780 } 12781 12782 // Reflect the move in app info 12783 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12784 pkg.setApplicationInfoCodePath(pkg.codePath); 12785 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12786 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12787 pkg.setApplicationInfoResourcePath(pkg.codePath); 12788 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12789 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12790 12791 return true; 12792 } 12793 12794 int doPostInstall(int status, int uid) { 12795 if (status == PackageManager.INSTALL_SUCCEEDED) { 12796 cleanUp(move.fromUuid); 12797 } else { 12798 cleanUp(move.toUuid); 12799 } 12800 return status; 12801 } 12802 12803 @Override 12804 String getCodePath() { 12805 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12806 } 12807 12808 @Override 12809 String getResourcePath() { 12810 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12811 } 12812 12813 private boolean cleanUp(String volumeUuid) { 12814 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12815 move.dataAppName); 12816 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12817 synchronized (mInstallLock) { 12818 // Clean up both app data and code 12819 removeDataDirsLI(volumeUuid, move.packageName); 12820 removeCodePathLI(codeFile); 12821 } 12822 return true; 12823 } 12824 12825 void cleanUpResourcesLI() { 12826 throw new UnsupportedOperationException(); 12827 } 12828 12829 boolean doPostDeleteLI(boolean delete) { 12830 throw new UnsupportedOperationException(); 12831 } 12832 } 12833 12834 static String getAsecPackageName(String packageCid) { 12835 int idx = packageCid.lastIndexOf("-"); 12836 if (idx == -1) { 12837 return packageCid; 12838 } 12839 return packageCid.substring(0, idx); 12840 } 12841 12842 // Utility method used to create code paths based on package name and available index. 12843 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12844 String idxStr = ""; 12845 int idx = 1; 12846 // Fall back to default value of idx=1 if prefix is not 12847 // part of oldCodePath 12848 if (oldCodePath != null) { 12849 String subStr = oldCodePath; 12850 // Drop the suffix right away 12851 if (suffix != null && subStr.endsWith(suffix)) { 12852 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12853 } 12854 // If oldCodePath already contains prefix find out the 12855 // ending index to either increment or decrement. 12856 int sidx = subStr.lastIndexOf(prefix); 12857 if (sidx != -1) { 12858 subStr = subStr.substring(sidx + prefix.length()); 12859 if (subStr != null) { 12860 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12861 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12862 } 12863 try { 12864 idx = Integer.parseInt(subStr); 12865 if (idx <= 1) { 12866 idx++; 12867 } else { 12868 idx--; 12869 } 12870 } catch(NumberFormatException e) { 12871 } 12872 } 12873 } 12874 } 12875 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12876 return prefix + idxStr; 12877 } 12878 12879 private File getNextCodePath(File targetDir, String packageName) { 12880 int suffix = 1; 12881 File result; 12882 do { 12883 result = new File(targetDir, packageName + "-" + suffix); 12884 suffix++; 12885 } while (result.exists()); 12886 return result; 12887 } 12888 12889 // Utility method that returns the relative package path with respect 12890 // to the installation directory. Like say for /data/data/com.test-1.apk 12891 // string com.test-1 is returned. 12892 static String deriveCodePathName(String codePath) { 12893 if (codePath == null) { 12894 return null; 12895 } 12896 final File codeFile = new File(codePath); 12897 final String name = codeFile.getName(); 12898 if (codeFile.isDirectory()) { 12899 return name; 12900 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12901 final int lastDot = name.lastIndexOf('.'); 12902 return name.substring(0, lastDot); 12903 } else { 12904 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12905 return null; 12906 } 12907 } 12908 12909 static class PackageInstalledInfo { 12910 String name; 12911 int uid; 12912 // The set of users that originally had this package installed. 12913 int[] origUsers; 12914 // The set of users that now have this package installed. 12915 int[] newUsers; 12916 PackageParser.Package pkg; 12917 int returnCode; 12918 String returnMsg; 12919 PackageRemovedInfo removedInfo; 12920 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12921 12922 public void setError(int code, String msg) { 12923 setReturnCode(code); 12924 setReturnMessage(msg); 12925 Slog.w(TAG, msg); 12926 } 12927 12928 public void setError(String msg, PackageParserException e) { 12929 setReturnCode(e.error); 12930 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12931 Slog.w(TAG, msg, e); 12932 } 12933 12934 public void setError(String msg, PackageManagerException e) { 12935 returnCode = e.error; 12936 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12937 Slog.w(TAG, msg, e); 12938 } 12939 12940 public void setReturnCode(int returnCode) { 12941 this.returnCode = returnCode; 12942 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12943 for (int i = 0; i < childCount; i++) { 12944 addedChildPackages.valueAt(i).returnCode = returnCode; 12945 } 12946 } 12947 12948 private void setReturnMessage(String returnMsg) { 12949 this.returnMsg = returnMsg; 12950 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12951 for (int i = 0; i < childCount; i++) { 12952 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12953 } 12954 } 12955 12956 // In some error cases we want to convey more info back to the observer 12957 String origPackage; 12958 String origPermission; 12959 } 12960 12961 /* 12962 * Install a non-existing package. 12963 */ 12964 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12965 UserHandle user, String installerPackageName, String volumeUuid, 12966 PackageInstalledInfo res) { 12967 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12968 12969 // Remember this for later, in case we need to rollback this install 12970 String pkgName = pkg.packageName; 12971 12972 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12973 12974 synchronized(mPackages) { 12975 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12976 // A package with the same name is already installed, though 12977 // it has been renamed to an older name. The package we 12978 // are trying to install should be installed as an update to 12979 // the existing one, but that has not been requested, so bail. 12980 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12981 + " without first uninstalling package running as " 12982 + mSettings.mRenamedPackages.get(pkgName)); 12983 return; 12984 } 12985 if (mPackages.containsKey(pkgName)) { 12986 // Don't allow installation over an existing package with the same name. 12987 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12988 + " without first uninstalling."); 12989 return; 12990 } 12991 } 12992 12993 try { 12994 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12995 System.currentTimeMillis(), user); 12996 12997 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12998 12999 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13000 prepareAppDataAfterInstall(newPackage); 13001 13002 } else { 13003 // Remove package from internal structures, but keep around any 13004 // data that might have already existed 13005 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13006 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13007 } 13008 } catch (PackageManagerException e) { 13009 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13010 } 13011 13012 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13013 } 13014 13015 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13016 // Can't rotate keys during boot or if sharedUser. 13017 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13018 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13019 return false; 13020 } 13021 // app is using upgradeKeySets; make sure all are valid 13022 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13023 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13024 for (int i = 0; i < upgradeKeySets.length; i++) { 13025 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13026 Slog.wtf(TAG, "Package " 13027 + (oldPs.name != null ? oldPs.name : "<null>") 13028 + " contains upgrade-key-set reference to unknown key-set: " 13029 + upgradeKeySets[i] 13030 + " reverting to signatures check."); 13031 return false; 13032 } 13033 } 13034 return true; 13035 } 13036 13037 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13038 // Upgrade keysets are being used. Determine if new package has a superset of the 13039 // required keys. 13040 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13041 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13042 for (int i = 0; i < upgradeKeySets.length; i++) { 13043 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13044 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13045 return true; 13046 } 13047 } 13048 return false; 13049 } 13050 13051 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13052 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13053 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13054 13055 final PackageParser.Package oldPackage; 13056 final String pkgName = pkg.packageName; 13057 final int[] allUsers; 13058 13059 // First find the old package info and check signatures 13060 synchronized(mPackages) { 13061 oldPackage = mPackages.get(pkgName); 13062 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13063 if (isEphemeral && !oldIsEphemeral) { 13064 // can't downgrade from full to ephemeral 13065 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13066 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13067 return; 13068 } 13069 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13070 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13071 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13072 if (!checkUpgradeKeySetLP(ps, pkg)) { 13073 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13074 "New package not signed by keys specified by upgrade-keysets: " 13075 + pkgName); 13076 return; 13077 } 13078 } else { 13079 // default to original signature matching 13080 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13081 != PackageManager.SIGNATURE_MATCH) { 13082 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13083 "New package has a different signature: " + pkgName); 13084 return; 13085 } 13086 } 13087 13088 // In case of rollback, remember per-user/profile install state 13089 allUsers = sUserManager.getUserIds(); 13090 } 13091 13092 // Update what is removed 13093 res.removedInfo = new PackageRemovedInfo(); 13094 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13095 res.removedInfo.removedPackage = oldPackage.packageName; 13096 res.removedInfo.isUpdate = true; 13097 final int childCount = (oldPackage.childPackages != null) 13098 ? oldPackage.childPackages.size() : 0; 13099 for (int i = 0; i < childCount; i++) { 13100 boolean childPackageUpdated = false; 13101 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13102 if (res.addedChildPackages != null) { 13103 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13104 if (childRes != null) { 13105 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13106 childRes.removedInfo.removedPackage = childPkg.packageName; 13107 childRes.removedInfo.isUpdate = true; 13108 childPackageUpdated = true; 13109 } 13110 } 13111 if (!childPackageUpdated) { 13112 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13113 childRemovedRes.removedPackage = childPkg.packageName; 13114 childRemovedRes.isUpdate = false; 13115 childRemovedRes.dataRemoved = true; 13116 synchronized (mPackages) { 13117 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13118 if (childPs != null) { 13119 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13120 } 13121 } 13122 if (res.removedInfo.removedChildPackages == null) { 13123 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13124 } 13125 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13126 } 13127 } 13128 13129 boolean sysPkg = (isSystemApp(oldPackage)); 13130 if (sysPkg) { 13131 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13132 user, allUsers, installerPackageName, res); 13133 } else { 13134 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13135 user, allUsers, installerPackageName, res); 13136 } 13137 } 13138 13139 public List<String> getPreviousCodePaths(String packageName) { 13140 final PackageSetting ps = mSettings.mPackages.get(packageName); 13141 final List<String> result = new ArrayList<String>(); 13142 if (ps != null && ps.oldCodePaths != null) { 13143 result.addAll(ps.oldCodePaths); 13144 } 13145 return result; 13146 } 13147 13148 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13149 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13150 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13151 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13152 + deletedPackage); 13153 13154 String pkgName = deletedPackage.packageName; 13155 boolean deletedPkg = true; 13156 boolean addedPkg = false; 13157 boolean updatedSettings = false; 13158 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13159 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13160 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13161 13162 final long origUpdateTime = (pkg.mExtras != null) 13163 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13164 13165 // First delete the existing package while retaining the data directory 13166 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13167 res.removedInfo, true, pkg)) { 13168 // If the existing package wasn't successfully deleted 13169 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13170 deletedPkg = false; 13171 } else { 13172 // Successfully deleted the old package; proceed with replace. 13173 13174 // If deleted package lived in a container, give users a chance to 13175 // relinquish resources before killing. 13176 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13177 if (DEBUG_INSTALL) { 13178 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13179 } 13180 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13181 final ArrayList<String> pkgList = new ArrayList<String>(1); 13182 pkgList.add(deletedPackage.applicationInfo.packageName); 13183 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13184 } 13185 13186 deleteCodeCacheDirsLI(pkg); 13187 13188 try { 13189 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13190 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13191 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13192 13193 // Update the in-memory copy of the previous code paths. 13194 PackageSetting ps = mSettings.mPackages.get(pkgName); 13195 if (!killApp) { 13196 if (ps.oldCodePaths == null) { 13197 ps.oldCodePaths = new ArraySet<>(); 13198 } 13199 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13200 if (deletedPackage.splitCodePaths != null) { 13201 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13202 } 13203 } else { 13204 ps.oldCodePaths = null; 13205 } 13206 if (ps.childPackageNames != null) { 13207 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13208 final String childPkgName = ps.childPackageNames.get(i); 13209 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13210 childPs.oldCodePaths = ps.oldCodePaths; 13211 } 13212 } 13213 prepareAppDataAfterInstall(newPackage); 13214 addedPkg = true; 13215 } catch (PackageManagerException e) { 13216 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13217 } 13218 } 13219 13220 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13221 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13222 13223 // Revert all internal state mutations and added folders for the failed install 13224 if (addedPkg) { 13225 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13226 res.removedInfo, true, null); 13227 } 13228 13229 // Restore the old package 13230 if (deletedPkg) { 13231 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13232 File restoreFile = new File(deletedPackage.codePath); 13233 // Parse old package 13234 boolean oldExternal = isExternal(deletedPackage); 13235 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13236 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13237 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13238 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13239 try { 13240 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13241 null); 13242 } catch (PackageManagerException e) { 13243 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13244 + e.getMessage()); 13245 return; 13246 } 13247 13248 synchronized (mPackages) { 13249 // Ensure the installer package name up to date 13250 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13251 13252 // Update permissions for restored package 13253 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13254 13255 mSettings.writeLPr(); 13256 } 13257 13258 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13259 } 13260 } else { 13261 synchronized (mPackages) { 13262 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13263 if (ps != null) { 13264 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13265 if (res.removedInfo.removedChildPackages != null) { 13266 final int childCount = res.removedInfo.removedChildPackages.size(); 13267 // Iterate in reverse as we may modify the collection 13268 for (int i = childCount - 1; i >= 0; i--) { 13269 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13270 if (res.addedChildPackages.containsKey(childPackageName)) { 13271 res.removedInfo.removedChildPackages.removeAt(i); 13272 } else { 13273 PackageRemovedInfo childInfo = res.removedInfo 13274 .removedChildPackages.valueAt(i); 13275 childInfo.removedForAllUsers = mPackages.get( 13276 childInfo.removedPackage) == null; 13277 } 13278 } 13279 } 13280 } 13281 } 13282 } 13283 } 13284 13285 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13286 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13287 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13288 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13289 + ", old=" + deletedPackage); 13290 13291 final boolean disabledSystem; 13292 13293 // Set the system/privileged flags as needed 13294 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13295 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13296 != 0) { 13297 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13298 } 13299 13300 // Kill package processes including services, providers, etc. 13301 killPackage(deletedPackage, "replace sys pkg"); 13302 13303 // Remove existing system package 13304 removePackageLI(deletedPackage, true); 13305 13306 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13307 if (!disabledSystem) { 13308 // We didn't need to disable the .apk as a current system package, 13309 // which means we are replacing another update that is already 13310 // installed. We need to make sure to delete the older one's .apk. 13311 res.removedInfo.args = createInstallArgsForExisting(0, 13312 deletedPackage.applicationInfo.getCodePath(), 13313 deletedPackage.applicationInfo.getResourcePath(), 13314 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13315 } else { 13316 res.removedInfo.args = null; 13317 } 13318 13319 // Successfully disabled the old package. Now proceed with re-installation 13320 deleteCodeCacheDirsLI(pkg); 13321 13322 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13323 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13324 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13325 13326 PackageParser.Package newPackage = null; 13327 try { 13328 // Add the package to the internal data structures 13329 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13330 13331 // Set the update and install times 13332 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13333 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13334 System.currentTimeMillis()); 13335 13336 // Check for shared user id changes 13337 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13338 deletedPackage, newPackage); 13339 if (invalidPackageName != null) { 13340 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13341 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13342 + " to " + invalidPackageName); 13343 } 13344 13345 // Update the package dynamic state if succeeded 13346 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13347 // Now that the install succeeded make sure we remove data 13348 // directories for any child package the update removed. 13349 final int deletedChildCount = (deletedPackage.childPackages != null) 13350 ? deletedPackage.childPackages.size() : 0; 13351 final int newChildCount = (newPackage.childPackages != null) 13352 ? newPackage.childPackages.size() : 0; 13353 for (int i = 0; i < deletedChildCount; i++) { 13354 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13355 boolean childPackageDeleted = true; 13356 for (int j = 0; j < newChildCount; j++) { 13357 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13358 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13359 childPackageDeleted = false; 13360 break; 13361 } 13362 } 13363 if (childPackageDeleted) { 13364 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13365 deletedChildPkg.packageName); 13366 if (ps != null && res.removedInfo.removedChildPackages != null) { 13367 PackageRemovedInfo removedChildRes = res.removedInfo 13368 .removedChildPackages.get(deletedChildPkg.packageName); 13369 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13370 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13371 } 13372 } 13373 } 13374 13375 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13376 prepareAppDataAfterInstall(newPackage); 13377 } 13378 } catch (PackageManagerException e) { 13379 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13380 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13381 } 13382 13383 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13384 // Re installation failed. Restore old information 13385 // Remove new pkg information 13386 if (newPackage != null) { 13387 removeInstalledPackageLI(newPackage, true); 13388 } 13389 // Add back the old system package 13390 try { 13391 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13392 } catch (PackageManagerException e) { 13393 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13394 } 13395 13396 synchronized (mPackages) { 13397 if (disabledSystem) { 13398 enableSystemPackageLPw(deletedPackage); 13399 } 13400 13401 // Ensure the installer package name up to date 13402 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13403 13404 // Update permissions for restored package 13405 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13406 13407 mSettings.writeLPr(); 13408 } 13409 13410 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13411 + " after failed upgrade"); 13412 } 13413 } 13414 13415 /** 13416 * Checks whether the parent or any of the child packages have a change shared 13417 * user. For a package to be a valid update the shred users of the parent and 13418 * the children should match. We may later support changing child shared users. 13419 * @param oldPkg The updated package. 13420 * @param newPkg The update package. 13421 * @return The shared user that change between the versions. 13422 */ 13423 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13424 PackageParser.Package newPkg) { 13425 // Check parent shared user 13426 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13427 return newPkg.packageName; 13428 } 13429 // Check child shared users 13430 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13431 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13432 for (int i = 0; i < newChildCount; i++) { 13433 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13434 // If this child was present, did it have the same shared user? 13435 for (int j = 0; j < oldChildCount; j++) { 13436 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13437 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13438 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13439 return newChildPkg.packageName; 13440 } 13441 } 13442 } 13443 return null; 13444 } 13445 13446 private void removeNativeBinariesLI(PackageSetting ps) { 13447 // Remove the lib path for the parent package 13448 if (ps != null) { 13449 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13450 // Remove the lib path for the child packages 13451 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13452 for (int i = 0; i < childCount; i++) { 13453 PackageSetting childPs = null; 13454 synchronized (mPackages) { 13455 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13456 } 13457 if (childPs != null) { 13458 NativeLibraryHelper.removeNativeBinariesLI(childPs 13459 .legacyNativeLibraryPathString); 13460 } 13461 } 13462 } 13463 } 13464 13465 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13466 // Enable the parent package 13467 mSettings.enableSystemPackageLPw(pkg.packageName); 13468 // Enable the child packages 13469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13470 for (int i = 0; i < childCount; i++) { 13471 PackageParser.Package childPkg = pkg.childPackages.get(i); 13472 mSettings.enableSystemPackageLPw(childPkg.packageName); 13473 } 13474 } 13475 13476 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13477 PackageParser.Package newPkg) { 13478 // Disable the parent package (parent always replaced) 13479 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13480 // Disable the child packages 13481 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13482 for (int i = 0; i < childCount; i++) { 13483 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13484 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13485 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13486 } 13487 return disabled; 13488 } 13489 13490 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13491 String installerPackageName) { 13492 // Enable the parent package 13493 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13494 // Enable the child packages 13495 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13496 for (int i = 0; i < childCount; i++) { 13497 PackageParser.Package childPkg = pkg.childPackages.get(i); 13498 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13499 } 13500 } 13501 13502 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13503 // Collect all used permissions in the UID 13504 ArraySet<String> usedPermissions = new ArraySet<>(); 13505 final int packageCount = su.packages.size(); 13506 for (int i = 0; i < packageCount; i++) { 13507 PackageSetting ps = su.packages.valueAt(i); 13508 if (ps.pkg == null) { 13509 continue; 13510 } 13511 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13512 for (int j = 0; j < requestedPermCount; j++) { 13513 String permission = ps.pkg.requestedPermissions.get(j); 13514 BasePermission bp = mSettings.mPermissions.get(permission); 13515 if (bp != null) { 13516 usedPermissions.add(permission); 13517 } 13518 } 13519 } 13520 13521 PermissionsState permissionsState = su.getPermissionsState(); 13522 // Prune install permissions 13523 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13524 final int installPermCount = installPermStates.size(); 13525 for (int i = installPermCount - 1; i >= 0; i--) { 13526 PermissionState permissionState = installPermStates.get(i); 13527 if (!usedPermissions.contains(permissionState.getName())) { 13528 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13529 if (bp != null) { 13530 permissionsState.revokeInstallPermission(bp); 13531 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13532 PackageManager.MASK_PERMISSION_FLAGS, 0); 13533 } 13534 } 13535 } 13536 13537 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13538 13539 // Prune runtime permissions 13540 for (int userId : allUserIds) { 13541 List<PermissionState> runtimePermStates = permissionsState 13542 .getRuntimePermissionStates(userId); 13543 final int runtimePermCount = runtimePermStates.size(); 13544 for (int i = runtimePermCount - 1; i >= 0; i--) { 13545 PermissionState permissionState = runtimePermStates.get(i); 13546 if (!usedPermissions.contains(permissionState.getName())) { 13547 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13548 if (bp != null) { 13549 permissionsState.revokeRuntimePermission(bp, userId); 13550 permissionsState.updatePermissionFlags(bp, userId, 13551 PackageManager.MASK_PERMISSION_FLAGS, 0); 13552 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13553 runtimePermissionChangedUserIds, userId); 13554 } 13555 } 13556 } 13557 } 13558 13559 return runtimePermissionChangedUserIds; 13560 } 13561 13562 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13563 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13564 // Update the parent package setting 13565 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13566 res, user); 13567 // Update the child packages setting 13568 final int childCount = (newPackage.childPackages != null) 13569 ? newPackage.childPackages.size() : 0; 13570 for (int i = 0; i < childCount; i++) { 13571 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13572 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13573 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13574 childRes.origUsers, childRes, user); 13575 } 13576 } 13577 13578 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13579 String installerPackageName, int[] allUsers, int[] installedForUsers, 13580 PackageInstalledInfo res, UserHandle user) { 13581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13582 13583 String pkgName = newPackage.packageName; 13584 synchronized (mPackages) { 13585 //write settings. the installStatus will be incomplete at this stage. 13586 //note that the new package setting would have already been 13587 //added to mPackages. It hasn't been persisted yet. 13588 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13590 mSettings.writeLPr(); 13591 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13592 } 13593 13594 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13595 synchronized (mPackages) { 13596 updatePermissionsLPw(newPackage.packageName, newPackage, 13597 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13598 ? UPDATE_PERMISSIONS_ALL : 0)); 13599 // For system-bundled packages, we assume that installing an upgraded version 13600 // of the package implies that the user actually wants to run that new code, 13601 // so we enable the package. 13602 PackageSetting ps = mSettings.mPackages.get(pkgName); 13603 final int userId = user.getIdentifier(); 13604 if (ps != null) { 13605 if (isSystemApp(newPackage)) { 13606 if (DEBUG_INSTALL) { 13607 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13608 } 13609 // Enable system package for requested users 13610 if (res.origUsers != null) { 13611 for (int origUserId : res.origUsers) { 13612 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13613 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13614 origUserId, installerPackageName); 13615 } 13616 } 13617 } 13618 // Also convey the prior install/uninstall state 13619 if (allUsers != null && installedForUsers != null) { 13620 for (int currentUserId : allUsers) { 13621 final boolean installed = ArrayUtils.contains( 13622 installedForUsers, currentUserId); 13623 if (DEBUG_INSTALL) { 13624 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13625 } 13626 ps.setInstalled(installed, currentUserId); 13627 } 13628 // these install state changes will be persisted in the 13629 // upcoming call to mSettings.writeLPr(). 13630 } 13631 } 13632 // It's implied that when a user requests installation, they want the app to be 13633 // installed and enabled. 13634 if (userId != UserHandle.USER_ALL) { 13635 ps.setInstalled(true, userId); 13636 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13637 } 13638 } 13639 res.name = pkgName; 13640 res.uid = newPackage.applicationInfo.uid; 13641 res.pkg = newPackage; 13642 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13643 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13644 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13645 //to update install status 13646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13647 mSettings.writeLPr(); 13648 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13649 } 13650 13651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13652 } 13653 13654 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13655 try { 13656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13657 installPackageLI(args, res); 13658 } finally { 13659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13660 } 13661 } 13662 13663 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13664 final int installFlags = args.installFlags; 13665 final String installerPackageName = args.installerPackageName; 13666 final String volumeUuid = args.volumeUuid; 13667 final File tmpPackageFile = new File(args.getCodePath()); 13668 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13669 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13670 || (args.volumeUuid != null)); 13671 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13672 boolean replace = false; 13673 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13674 if (args.move != null) { 13675 // moving a complete application; perform an initial scan on the new install location 13676 scanFlags |= SCAN_INITIAL; 13677 } 13678 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13679 scanFlags |= SCAN_DONT_KILL_APP; 13680 } 13681 13682 // Result object to be returned 13683 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13684 13685 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13686 13687 // Sanity check 13688 if (ephemeral && (forwardLocked || onExternal)) { 13689 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13690 + " external=" + onExternal); 13691 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13692 return; 13693 } 13694 13695 // Retrieve PackageSettings and parse package 13696 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13697 | PackageParser.PARSE_ENFORCE_CODE 13698 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13699 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13700 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13701 PackageParser pp = new PackageParser(); 13702 pp.setSeparateProcesses(mSeparateProcesses); 13703 pp.setDisplayMetrics(mMetrics); 13704 13705 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13706 final PackageParser.Package pkg; 13707 try { 13708 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13709 } catch (PackageParserException e) { 13710 res.setError("Failed parse during installPackageLI", e); 13711 return; 13712 } finally { 13713 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13714 } 13715 13716 // If we are installing a clustered package add results for the children 13717 if (pkg.childPackages != null) { 13718 synchronized (mPackages) { 13719 final int childCount = pkg.childPackages.size(); 13720 for (int i = 0; i < childCount; i++) { 13721 PackageParser.Package childPkg = pkg.childPackages.get(i); 13722 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13723 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13724 childRes.pkg = childPkg; 13725 childRes.name = childPkg.packageName; 13726 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13727 if (childPs != null) { 13728 childRes.origUsers = childPs.queryInstalledUsers( 13729 sUserManager.getUserIds(), true); 13730 } 13731 if ((mPackages.containsKey(childPkg.packageName))) { 13732 childRes.removedInfo = new PackageRemovedInfo(); 13733 childRes.removedInfo.removedPackage = childPkg.packageName; 13734 } 13735 if (res.addedChildPackages == null) { 13736 res.addedChildPackages = new ArrayMap<>(); 13737 } 13738 res.addedChildPackages.put(childPkg.packageName, childRes); 13739 } 13740 } 13741 } 13742 13743 // If package doesn't declare API override, mark that we have an install 13744 // time CPU ABI override. 13745 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13746 pkg.cpuAbiOverride = args.abiOverride; 13747 } 13748 13749 String pkgName = res.name = pkg.packageName; 13750 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13751 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13752 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13753 return; 13754 } 13755 } 13756 13757 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13758 try { 13759 PackageParser.collectCertificates(pkg, parseFlags); 13760 } catch (PackageParserException e) { 13761 res.setError("Failed collect during installPackageLI", e); 13762 return; 13763 } finally { 13764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13765 } 13766 13767 // Get rid of all references to package scan path via parser. 13768 pp = null; 13769 String oldCodePath = null; 13770 boolean systemApp = false; 13771 synchronized (mPackages) { 13772 // Check if installing already existing package 13773 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13774 String oldName = mSettings.mRenamedPackages.get(pkgName); 13775 if (pkg.mOriginalPackages != null 13776 && pkg.mOriginalPackages.contains(oldName) 13777 && mPackages.containsKey(oldName)) { 13778 // This package is derived from an original package, 13779 // and this device has been updating from that original 13780 // name. We must continue using the original name, so 13781 // rename the new package here. 13782 pkg.setPackageName(oldName); 13783 pkgName = pkg.packageName; 13784 replace = true; 13785 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13786 + oldName + " pkgName=" + pkgName); 13787 } else if (mPackages.containsKey(pkgName)) { 13788 // This package, under its official name, already exists 13789 // on the device; we should replace it. 13790 replace = true; 13791 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13792 } 13793 13794 // Child packages are installed through the parent package 13795 if (pkg.parentPackage != null) { 13796 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13797 "Package " + pkg.packageName + " is child of package " 13798 + pkg.parentPackage.parentPackage + ". Child packages " 13799 + "can be updated only through the parent package."); 13800 return; 13801 } 13802 13803 if (replace) { 13804 // Prevent apps opting out from runtime permissions 13805 PackageParser.Package oldPackage = mPackages.get(pkgName); 13806 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13807 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13808 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13809 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13810 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13811 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13812 + " doesn't support runtime permissions but the old" 13813 + " target SDK " + oldTargetSdk + " does."); 13814 return; 13815 } 13816 13817 // Prevent installing of child packages 13818 if (oldPackage.parentPackage != null) { 13819 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13820 "Package " + pkg.packageName + " is child of package " 13821 + oldPackage.parentPackage + ". Child packages " 13822 + "can be updated only through the parent package."); 13823 return; 13824 } 13825 } 13826 } 13827 13828 PackageSetting ps = mSettings.mPackages.get(pkgName); 13829 if (ps != null) { 13830 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13831 13832 // Quick sanity check that we're signed correctly if updating; 13833 // we'll check this again later when scanning, but we want to 13834 // bail early here before tripping over redefined permissions. 13835 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13836 if (!checkUpgradeKeySetLP(ps, pkg)) { 13837 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13838 + pkg.packageName + " upgrade keys do not match the " 13839 + "previously installed version"); 13840 return; 13841 } 13842 } else { 13843 try { 13844 verifySignaturesLP(ps, pkg); 13845 } catch (PackageManagerException e) { 13846 res.setError(e.error, e.getMessage()); 13847 return; 13848 } 13849 } 13850 13851 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13852 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13853 systemApp = (ps.pkg.applicationInfo.flags & 13854 ApplicationInfo.FLAG_SYSTEM) != 0; 13855 } 13856 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13857 } 13858 13859 // Check whether the newly-scanned package wants to define an already-defined perm 13860 int N = pkg.permissions.size(); 13861 for (int i = N-1; i >= 0; i--) { 13862 PackageParser.Permission perm = pkg.permissions.get(i); 13863 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13864 if (bp != null) { 13865 // If the defining package is signed with our cert, it's okay. This 13866 // also includes the "updating the same package" case, of course. 13867 // "updating same package" could also involve key-rotation. 13868 final boolean sigsOk; 13869 if (bp.sourcePackage.equals(pkg.packageName) 13870 && (bp.packageSetting instanceof PackageSetting) 13871 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13872 scanFlags))) { 13873 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13874 } else { 13875 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13876 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13877 } 13878 if (!sigsOk) { 13879 // If the owning package is the system itself, we log but allow 13880 // install to proceed; we fail the install on all other permission 13881 // redefinitions. 13882 if (!bp.sourcePackage.equals("android")) { 13883 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13884 + pkg.packageName + " attempting to redeclare permission " 13885 + perm.info.name + " already owned by " + bp.sourcePackage); 13886 res.origPermission = perm.info.name; 13887 res.origPackage = bp.sourcePackage; 13888 return; 13889 } else { 13890 Slog.w(TAG, "Package " + pkg.packageName 13891 + " attempting to redeclare system permission " 13892 + perm.info.name + "; ignoring new declaration"); 13893 pkg.permissions.remove(i); 13894 } 13895 } 13896 } 13897 } 13898 } 13899 13900 if (systemApp) { 13901 if (onExternal) { 13902 // Abort update; system app can't be replaced with app on sdcard 13903 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13904 "Cannot install updates to system apps on sdcard"); 13905 return; 13906 } else if (ephemeral) { 13907 // Abort update; system app can't be replaced with an ephemeral app 13908 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13909 "Cannot update a system app with an ephemeral app"); 13910 return; 13911 } 13912 } 13913 13914 if (args.move != null) { 13915 // We did an in-place move, so dex is ready to roll 13916 scanFlags |= SCAN_NO_DEX; 13917 scanFlags |= SCAN_MOVE; 13918 13919 synchronized (mPackages) { 13920 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13921 if (ps == null) { 13922 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13923 "Missing settings for moved package " + pkgName); 13924 } 13925 13926 // We moved the entire application as-is, so bring over the 13927 // previously derived ABI information. 13928 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13929 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13930 } 13931 13932 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13933 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13934 scanFlags |= SCAN_NO_DEX; 13935 13936 try { 13937 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13938 args.abiOverride : pkg.cpuAbiOverride); 13939 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13940 true /* extract libs */); 13941 } catch (PackageManagerException pme) { 13942 Slog.e(TAG, "Error deriving application ABI", pme); 13943 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13944 return; 13945 } 13946 13947 13948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13949 // Do not run PackageDexOptimizer through the local performDexOpt 13950 // method because `pkg` is not in `mPackages` yet. 13951 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13952 false /* useProfiles */, true /* extractOnly */); 13953 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13954 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13955 String msg = "Extracking package failed for " + pkgName; 13956 res.setError(INSTALL_FAILED_DEXOPT, msg); 13957 return; 13958 } 13959 } 13960 13961 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13962 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13963 return; 13964 } 13965 13966 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13967 13968 if (replace) { 13969 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13970 installerPackageName, res); 13971 } else { 13972 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13973 args.user, installerPackageName, volumeUuid, res); 13974 } 13975 synchronized (mPackages) { 13976 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13977 if (ps != null) { 13978 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13979 } 13980 13981 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13982 for (int i = 0; i < childCount; i++) { 13983 PackageParser.Package childPkg = pkg.childPackages.get(i); 13984 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13985 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13986 if (childPs != null) { 13987 childRes.newUsers = childPs.queryInstalledUsers( 13988 sUserManager.getUserIds(), true); 13989 } 13990 } 13991 } 13992 } 13993 13994 private void startIntentFilterVerifications(int userId, boolean replacing, 13995 PackageParser.Package pkg) { 13996 if (mIntentFilterVerifierComponent == null) { 13997 Slog.w(TAG, "No IntentFilter verification will not be done as " 13998 + "there is no IntentFilterVerifier available!"); 13999 return; 14000 } 14001 14002 final int verifierUid = getPackageUid( 14003 mIntentFilterVerifierComponent.getPackageName(), 14004 MATCH_DEBUG_TRIAGED_MISSING, 14005 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14006 14007 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14008 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14009 mHandler.sendMessage(msg); 14010 14011 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14012 for (int i = 0; i < childCount; i++) { 14013 PackageParser.Package childPkg = pkg.childPackages.get(i); 14014 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14015 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14016 mHandler.sendMessage(msg); 14017 } 14018 } 14019 14020 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14021 PackageParser.Package pkg) { 14022 int size = pkg.activities.size(); 14023 if (size == 0) { 14024 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14025 "No activity, so no need to verify any IntentFilter!"); 14026 return; 14027 } 14028 14029 final boolean hasDomainURLs = hasDomainURLs(pkg); 14030 if (!hasDomainURLs) { 14031 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14032 "No domain URLs, so no need to verify any IntentFilter!"); 14033 return; 14034 } 14035 14036 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14037 + " if any IntentFilter from the " + size 14038 + " Activities needs verification ..."); 14039 14040 int count = 0; 14041 final String packageName = pkg.packageName; 14042 14043 synchronized (mPackages) { 14044 // If this is a new install and we see that we've already run verification for this 14045 // package, we have nothing to do: it means the state was restored from backup. 14046 if (!replacing) { 14047 IntentFilterVerificationInfo ivi = 14048 mSettings.getIntentFilterVerificationLPr(packageName); 14049 if (ivi != null) { 14050 if (DEBUG_DOMAIN_VERIFICATION) { 14051 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14052 + ivi.getStatusString()); 14053 } 14054 return; 14055 } 14056 } 14057 14058 // If any filters need to be verified, then all need to be. 14059 boolean needToVerify = false; 14060 for (PackageParser.Activity a : pkg.activities) { 14061 for (ActivityIntentInfo filter : a.intents) { 14062 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14063 if (DEBUG_DOMAIN_VERIFICATION) { 14064 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14065 } 14066 needToVerify = true; 14067 break; 14068 } 14069 } 14070 } 14071 14072 if (needToVerify) { 14073 final int verificationId = mIntentFilterVerificationToken++; 14074 for (PackageParser.Activity a : pkg.activities) { 14075 for (ActivityIntentInfo filter : a.intents) { 14076 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14077 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14078 "Verification needed for IntentFilter:" + filter.toString()); 14079 mIntentFilterVerifier.addOneIntentFilterVerification( 14080 verifierUid, userId, verificationId, filter, packageName); 14081 count++; 14082 } 14083 } 14084 } 14085 } 14086 } 14087 14088 if (count > 0) { 14089 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14090 + " IntentFilter verification" + (count > 1 ? "s" : "") 14091 + " for userId:" + userId); 14092 mIntentFilterVerifier.startVerifications(userId); 14093 } else { 14094 if (DEBUG_DOMAIN_VERIFICATION) { 14095 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14096 } 14097 } 14098 } 14099 14100 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14101 final ComponentName cn = filter.activity.getComponentName(); 14102 final String packageName = cn.getPackageName(); 14103 14104 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14105 packageName); 14106 if (ivi == null) { 14107 return true; 14108 } 14109 int status = ivi.getStatus(); 14110 switch (status) { 14111 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14112 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14113 return true; 14114 14115 default: 14116 // Nothing to do 14117 return false; 14118 } 14119 } 14120 14121 private static boolean isMultiArch(ApplicationInfo info) { 14122 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14123 } 14124 14125 private static boolean isExternal(PackageParser.Package pkg) { 14126 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14127 } 14128 14129 private static boolean isExternal(PackageSetting ps) { 14130 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14131 } 14132 14133 private static boolean isEphemeral(PackageParser.Package pkg) { 14134 return pkg.applicationInfo.isEphemeralApp(); 14135 } 14136 14137 private static boolean isEphemeral(PackageSetting ps) { 14138 return ps.pkg != null && isEphemeral(ps.pkg); 14139 } 14140 14141 private static boolean isSystemApp(PackageParser.Package pkg) { 14142 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14143 } 14144 14145 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14146 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14147 } 14148 14149 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14150 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14151 } 14152 14153 private static boolean isSystemApp(PackageSetting ps) { 14154 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14155 } 14156 14157 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14158 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14159 } 14160 14161 private int packageFlagsToInstallFlags(PackageSetting ps) { 14162 int installFlags = 0; 14163 if (isEphemeral(ps)) { 14164 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14165 } 14166 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14167 // This existing package was an external ASEC install when we have 14168 // the external flag without a UUID 14169 installFlags |= PackageManager.INSTALL_EXTERNAL; 14170 } 14171 if (ps.isForwardLocked()) { 14172 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14173 } 14174 return installFlags; 14175 } 14176 14177 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14178 if (isExternal(pkg)) { 14179 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14180 return StorageManager.UUID_PRIMARY_PHYSICAL; 14181 } else { 14182 return pkg.volumeUuid; 14183 } 14184 } else { 14185 return StorageManager.UUID_PRIVATE_INTERNAL; 14186 } 14187 } 14188 14189 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14190 if (isExternal(pkg)) { 14191 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14192 return mSettings.getExternalVersion(); 14193 } else { 14194 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14195 } 14196 } else { 14197 return mSettings.getInternalVersion(); 14198 } 14199 } 14200 14201 private void deleteTempPackageFiles() { 14202 final FilenameFilter filter = new FilenameFilter() { 14203 public boolean accept(File dir, String name) { 14204 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14205 } 14206 }; 14207 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14208 file.delete(); 14209 } 14210 } 14211 14212 @Override 14213 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14214 int flags) { 14215 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14216 flags); 14217 } 14218 14219 @Override 14220 public void deletePackage(final String packageName, 14221 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14222 mContext.enforceCallingOrSelfPermission( 14223 android.Manifest.permission.DELETE_PACKAGES, null); 14224 Preconditions.checkNotNull(packageName); 14225 Preconditions.checkNotNull(observer); 14226 final int uid = Binder.getCallingUid(); 14227 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14228 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14229 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14230 mContext.enforceCallingOrSelfPermission( 14231 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14232 "deletePackage for user " + userId); 14233 } 14234 14235 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14236 try { 14237 observer.onPackageDeleted(packageName, 14238 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14239 } catch (RemoteException re) { 14240 } 14241 return; 14242 } 14243 14244 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14245 try { 14246 observer.onPackageDeleted(packageName, 14247 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14248 } catch (RemoteException re) { 14249 } 14250 return; 14251 } 14252 14253 if (DEBUG_REMOVE) { 14254 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14255 + " deleteAllUsers: " + deleteAllUsers ); 14256 } 14257 // Queue up an async operation since the package deletion may take a little while. 14258 mHandler.post(new Runnable() { 14259 public void run() { 14260 mHandler.removeCallbacks(this); 14261 int returnCode; 14262 if (!deleteAllUsers) { 14263 returnCode = deletePackageX(packageName, userId, flags); 14264 } else { 14265 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14266 // If nobody is blocking uninstall, proceed with delete for all users 14267 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14268 returnCode = deletePackageX(packageName, userId, flags); 14269 } else { 14270 // Otherwise uninstall individually for users with blockUninstalls=false 14271 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14272 for (int userId : users) { 14273 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14274 returnCode = deletePackageX(packageName, userId, userFlags); 14275 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14276 Slog.w(TAG, "Package delete failed for user " + userId 14277 + ", returnCode " + returnCode); 14278 } 14279 } 14280 } 14281 // The app has only been marked uninstalled for certain users. 14282 // We still need to report that delete was blocked 14283 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14284 } 14285 } 14286 try { 14287 observer.onPackageDeleted(packageName, returnCode, null); 14288 } catch (RemoteException e) { 14289 Log.i(TAG, "Observer no longer exists."); 14290 } //end catch 14291 } //end run 14292 }); 14293 } 14294 14295 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14296 int[] result = EMPTY_INT_ARRAY; 14297 for (int userId : userIds) { 14298 if (getBlockUninstallForUser(packageName, userId)) { 14299 result = ArrayUtils.appendInt(result, userId); 14300 } 14301 } 14302 return result; 14303 } 14304 14305 @Override 14306 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14307 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14308 } 14309 14310 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14311 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14312 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14313 try { 14314 if (dpm != null) { 14315 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14316 /* callingUserOnly =*/ false); 14317 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14318 : deviceOwnerComponentName.getPackageName(); 14319 // Does the package contains the device owner? 14320 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14321 // this check is probably not needed, since DO should be registered as a device 14322 // admin on some user too. (Original bug for this: b/17657954) 14323 if (packageName.equals(deviceOwnerPackageName)) { 14324 return true; 14325 } 14326 // Does it contain a device admin for any user? 14327 int[] users; 14328 if (userId == UserHandle.USER_ALL) { 14329 users = sUserManager.getUserIds(); 14330 } else { 14331 users = new int[]{userId}; 14332 } 14333 for (int i = 0; i < users.length; ++i) { 14334 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14335 return true; 14336 } 14337 } 14338 } 14339 } catch (RemoteException e) { 14340 } 14341 return false; 14342 } 14343 14344 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14345 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14346 } 14347 14348 /** 14349 * This method is an internal method that could be get invoked either 14350 * to delete an installed package or to clean up a failed installation. 14351 * After deleting an installed package, a broadcast is sent to notify any 14352 * listeners that the package has been installed. For cleaning up a failed 14353 * installation, the broadcast is not necessary since the package's 14354 * installation wouldn't have sent the initial broadcast either 14355 * The key steps in deleting a package are 14356 * deleting the package information in internal structures like mPackages, 14357 * deleting the packages base directories through installd 14358 * updating mSettings to reflect current status 14359 * persisting settings for later use 14360 * sending a broadcast if necessary 14361 */ 14362 private int deletePackageX(String packageName, int userId, int flags) { 14363 final PackageRemovedInfo info = new PackageRemovedInfo(); 14364 final boolean res; 14365 14366 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14367 ? UserHandle.ALL : new UserHandle(userId); 14368 14369 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14370 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14371 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14372 } 14373 14374 PackageSetting uninstalledPs = null; 14375 14376 // for the uninstall-updates case and restricted profiles, remember the per- 14377 // user handle installed state 14378 int[] allUsers; 14379 synchronized (mPackages) { 14380 uninstalledPs = mSettings.mPackages.get(packageName); 14381 if (uninstalledPs == null) { 14382 Slog.w(TAG, "Not removing non-existent package " + packageName); 14383 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14384 } 14385 allUsers = sUserManager.getUserIds(); 14386 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14387 } 14388 14389 synchronized (mInstallLock) { 14390 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14391 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14392 flags | REMOVE_CHATTY, info, true, null); 14393 synchronized (mPackages) { 14394 if (res) { 14395 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14396 } 14397 } 14398 } 14399 14400 if (res) { 14401 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14402 info.sendPackageRemovedBroadcasts(killApp); 14403 info.sendSystemPackageUpdatedBroadcasts(); 14404 info.sendSystemPackageAppearedBroadcasts(); 14405 } 14406 // Force a gc here. 14407 Runtime.getRuntime().gc(); 14408 // Delete the resources here after sending the broadcast to let 14409 // other processes clean up before deleting resources. 14410 if (info.args != null) { 14411 synchronized (mInstallLock) { 14412 info.args.doPostDeleteLI(true); 14413 } 14414 } 14415 14416 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14417 } 14418 14419 class PackageRemovedInfo { 14420 String removedPackage; 14421 int uid = -1; 14422 int removedAppId = -1; 14423 int[] origUsers; 14424 int[] removedUsers = null; 14425 boolean isRemovedPackageSystemUpdate = false; 14426 boolean isUpdate; 14427 boolean dataRemoved; 14428 boolean removedForAllUsers; 14429 // Clean up resources deleted packages. 14430 InstallArgs args = null; 14431 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14432 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14433 14434 void sendPackageRemovedBroadcasts(boolean killApp) { 14435 sendPackageRemovedBroadcastInternal(killApp); 14436 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14437 for (int i = 0; i < childCount; i++) { 14438 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14439 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14440 } 14441 } 14442 14443 void sendSystemPackageUpdatedBroadcasts() { 14444 if (isRemovedPackageSystemUpdate) { 14445 sendSystemPackageUpdatedBroadcastsInternal(); 14446 final int childCount = (removedChildPackages != null) 14447 ? removedChildPackages.size() : 0; 14448 for (int i = 0; i < childCount; i++) { 14449 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14450 if (childInfo.isRemovedPackageSystemUpdate) { 14451 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14452 } 14453 } 14454 } 14455 } 14456 14457 void sendSystemPackageAppearedBroadcasts() { 14458 final int packageCount = (appearedChildPackages != null) 14459 ? appearedChildPackages.size() : 0; 14460 for (int i = 0; i < packageCount; i++) { 14461 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14462 for (int userId : installedInfo.newUsers) { 14463 sendPackageAddedForUser(installedInfo.name, true, 14464 UserHandle.getAppId(installedInfo.uid), userId); 14465 } 14466 } 14467 } 14468 14469 private void sendSystemPackageUpdatedBroadcastsInternal() { 14470 Bundle extras = new Bundle(2); 14471 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14472 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14473 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14474 extras, 0, null, null, null); 14475 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14476 extras, 0, null, null, null); 14477 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14478 null, 0, removedPackage, null, null); 14479 } 14480 14481 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14482 Bundle extras = new Bundle(2); 14483 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14484 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14485 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14486 if (isUpdate || isRemovedPackageSystemUpdate) { 14487 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14488 } 14489 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14490 if (removedPackage != null) { 14491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14492 extras, 0, null, null, removedUsers); 14493 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14494 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14495 removedPackage, extras, 0, null, null, removedUsers); 14496 } 14497 } 14498 if (removedAppId >= 0) { 14499 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14500 removedUsers); 14501 } 14502 } 14503 } 14504 14505 /* 14506 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14507 * flag is not set, the data directory is removed as well. 14508 * make sure this flag is set for partially installed apps. If not its meaningless to 14509 * delete a partially installed application. 14510 */ 14511 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14512 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14513 String packageName = ps.name; 14514 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14515 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14516 // Retrieve object to delete permissions for shared user later on 14517 final PackageSetting deletedPs; 14518 // reader 14519 synchronized (mPackages) { 14520 deletedPs = mSettings.mPackages.get(packageName); 14521 if (outInfo != null) { 14522 outInfo.removedPackage = packageName; 14523 outInfo.removedUsers = deletedPs != null 14524 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14525 : null; 14526 } 14527 } 14528 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14529 removeDataDirsLI(ps.volumeUuid, packageName); 14530 if (outInfo != null) { 14531 outInfo.dataRemoved = true; 14532 } 14533 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14534 } 14535 // writer 14536 synchronized (mPackages) { 14537 if (deletedPs != null) { 14538 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14539 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14540 clearDefaultBrowserIfNeeded(packageName); 14541 if (outInfo != null) { 14542 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14543 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14544 } 14545 updatePermissionsLPw(deletedPs.name, null, 0); 14546 if (deletedPs.sharedUser != null) { 14547 // Remove permissions associated with package. Since runtime 14548 // permissions are per user we have to kill the removed package 14549 // or packages running under the shared user of the removed 14550 // package if revoking the permissions requested only by the removed 14551 // package is successful and this causes a change in gids. 14552 for (int userId : UserManagerService.getInstance().getUserIds()) { 14553 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14554 userId); 14555 if (userIdToKill == UserHandle.USER_ALL 14556 || userIdToKill >= UserHandle.USER_SYSTEM) { 14557 // If gids changed for this user, kill all affected packages. 14558 mHandler.post(new Runnable() { 14559 @Override 14560 public void run() { 14561 // This has to happen with no lock held. 14562 killApplication(deletedPs.name, deletedPs.appId, 14563 KILL_APP_REASON_GIDS_CHANGED); 14564 } 14565 }); 14566 break; 14567 } 14568 } 14569 } 14570 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14571 } 14572 // make sure to preserve per-user disabled state if this removal was just 14573 // a downgrade of a system app to the factory package 14574 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14575 if (DEBUG_REMOVE) { 14576 Slog.d(TAG, "Propagating install state across downgrade"); 14577 } 14578 for (int userId : allUserHandles) { 14579 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14580 if (DEBUG_REMOVE) { 14581 Slog.d(TAG, " user " + userId + " => " + installed); 14582 } 14583 ps.setInstalled(installed, userId); 14584 } 14585 } 14586 } 14587 // can downgrade to reader 14588 if (writeSettings) { 14589 // Save settings now 14590 mSettings.writeLPr(); 14591 } 14592 } 14593 if (outInfo != null) { 14594 // A user ID was deleted here. Go through all users and remove it 14595 // from KeyStore. 14596 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14597 } 14598 } 14599 14600 static boolean locationIsPrivileged(File path) { 14601 try { 14602 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14603 .getCanonicalPath(); 14604 return path.getCanonicalPath().startsWith(privilegedAppDir); 14605 } catch (IOException e) { 14606 Slog.e(TAG, "Unable to access code path " + path); 14607 } 14608 return false; 14609 } 14610 14611 /* 14612 * Tries to delete system package. 14613 */ 14614 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14615 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14616 boolean writeSettings) { 14617 if (deletedPs.parentPackageName != null) { 14618 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14619 return false; 14620 } 14621 14622 final boolean applyUserRestrictions 14623 = (allUserHandles != null) && (outInfo.origUsers != null); 14624 final PackageSetting disabledPs; 14625 // Confirm if the system package has been updated 14626 // An updated system app can be deleted. This will also have to restore 14627 // the system pkg from system partition 14628 // reader 14629 synchronized (mPackages) { 14630 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14631 } 14632 14633 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14634 + " disabledPs=" + disabledPs); 14635 14636 if (disabledPs == null) { 14637 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14638 return false; 14639 } else if (DEBUG_REMOVE) { 14640 Slog.d(TAG, "Deleting system pkg from data partition"); 14641 } 14642 14643 if (DEBUG_REMOVE) { 14644 if (applyUserRestrictions) { 14645 Slog.d(TAG, "Remembering install states:"); 14646 for (int userId : allUserHandles) { 14647 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14648 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14649 } 14650 } 14651 } 14652 14653 // Delete the updated package 14654 outInfo.isRemovedPackageSystemUpdate = true; 14655 if (outInfo.removedChildPackages != null) { 14656 final int childCount = (deletedPs.childPackageNames != null) 14657 ? deletedPs.childPackageNames.size() : 0; 14658 for (int i = 0; i < childCount; i++) { 14659 String childPackageName = deletedPs.childPackageNames.get(i); 14660 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14661 .contains(childPackageName)) { 14662 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14663 childPackageName); 14664 if (childInfo != null) { 14665 childInfo.isRemovedPackageSystemUpdate = true; 14666 } 14667 } 14668 } 14669 } 14670 14671 if (disabledPs.versionCode < deletedPs.versionCode) { 14672 // Delete data for downgrades 14673 flags &= ~PackageManager.DELETE_KEEP_DATA; 14674 } else { 14675 // Preserve data by setting flag 14676 flags |= PackageManager.DELETE_KEEP_DATA; 14677 } 14678 14679 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14680 outInfo, writeSettings, disabledPs.pkg); 14681 if (!ret) { 14682 return false; 14683 } 14684 14685 // writer 14686 synchronized (mPackages) { 14687 // Reinstate the old system package 14688 enableSystemPackageLPw(disabledPs.pkg); 14689 // Remove any native libraries from the upgraded package. 14690 removeNativeBinariesLI(deletedPs); 14691 } 14692 14693 // Install the system package 14694 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14695 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14696 if (locationIsPrivileged(disabledPs.codePath)) { 14697 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14698 } 14699 14700 final PackageParser.Package newPkg; 14701 try { 14702 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14703 } catch (PackageManagerException e) { 14704 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14705 + e.getMessage()); 14706 return false; 14707 } 14708 14709 prepareAppDataAfterInstall(newPkg); 14710 14711 // writer 14712 synchronized (mPackages) { 14713 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14714 14715 // Propagate the permissions state as we do not want to drop on the floor 14716 // runtime permissions. The update permissions method below will take 14717 // care of removing obsolete permissions and grant install permissions. 14718 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14719 updatePermissionsLPw(newPkg.packageName, newPkg, 14720 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14721 14722 if (applyUserRestrictions) { 14723 if (DEBUG_REMOVE) { 14724 Slog.d(TAG, "Propagating install state across reinstall"); 14725 } 14726 for (int userId : allUserHandles) { 14727 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14728 if (DEBUG_REMOVE) { 14729 Slog.d(TAG, " user " + userId + " => " + installed); 14730 } 14731 ps.setInstalled(installed, userId); 14732 14733 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14734 } 14735 // Regardless of writeSettings we need to ensure that this restriction 14736 // state propagation is persisted 14737 mSettings.writeAllUsersPackageRestrictionsLPr(); 14738 } 14739 // can downgrade to reader here 14740 if (writeSettings) { 14741 mSettings.writeLPr(); 14742 } 14743 } 14744 return true; 14745 } 14746 14747 private boolean deleteInstalledPackageLI(PackageSetting ps, 14748 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14749 PackageRemovedInfo outInfo, boolean writeSettings, 14750 PackageParser.Package replacingPackage) { 14751 synchronized (mPackages) { 14752 if (outInfo != null) { 14753 outInfo.uid = ps.appId; 14754 } 14755 14756 if (outInfo != null && outInfo.removedChildPackages != null) { 14757 final int childCount = (ps.childPackageNames != null) 14758 ? ps.childPackageNames.size() : 0; 14759 for (int i = 0; i < childCount; i++) { 14760 String childPackageName = ps.childPackageNames.get(i); 14761 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14762 if (childPs == null) { 14763 return false; 14764 } 14765 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14766 childPackageName); 14767 if (childInfo != null) { 14768 childInfo.uid = childPs.appId; 14769 } 14770 } 14771 } 14772 } 14773 14774 // Delete package data from internal structures and also remove data if flag is set 14775 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14776 14777 // Delete the child packages data 14778 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14779 for (int i = 0; i < childCount; i++) { 14780 PackageSetting childPs; 14781 synchronized (mPackages) { 14782 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14783 } 14784 if (childPs != null) { 14785 PackageRemovedInfo childOutInfo = (outInfo != null 14786 && outInfo.removedChildPackages != null) 14787 ? outInfo.removedChildPackages.get(childPs.name) : null; 14788 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14789 && (replacingPackage != null 14790 && !replacingPackage.hasChildPackage(childPs.name)) 14791 ? flags & ~DELETE_KEEP_DATA : flags; 14792 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14793 deleteFlags, writeSettings); 14794 } 14795 } 14796 14797 // Delete application code and resources only for parent packages 14798 if (ps.parentPackageName == null) { 14799 if (deleteCodeAndResources && (outInfo != null)) { 14800 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14801 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14802 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14803 } 14804 } 14805 14806 return true; 14807 } 14808 14809 @Override 14810 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14811 int userId) { 14812 mContext.enforceCallingOrSelfPermission( 14813 android.Manifest.permission.DELETE_PACKAGES, null); 14814 synchronized (mPackages) { 14815 PackageSetting ps = mSettings.mPackages.get(packageName); 14816 if (ps == null) { 14817 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14818 return false; 14819 } 14820 if (!ps.getInstalled(userId)) { 14821 // Can't block uninstall for an app that is not installed or enabled. 14822 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14823 return false; 14824 } 14825 ps.setBlockUninstall(blockUninstall, userId); 14826 mSettings.writePackageRestrictionsLPr(userId); 14827 } 14828 return true; 14829 } 14830 14831 @Override 14832 public boolean getBlockUninstallForUser(String packageName, int userId) { 14833 synchronized (mPackages) { 14834 PackageSetting ps = mSettings.mPackages.get(packageName); 14835 if (ps == null) { 14836 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14837 return false; 14838 } 14839 return ps.getBlockUninstall(userId); 14840 } 14841 } 14842 14843 @Override 14844 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14845 int callingUid = Binder.getCallingUid(); 14846 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14847 throw new SecurityException( 14848 "setRequiredForSystemUser can only be run by the system or root"); 14849 } 14850 synchronized (mPackages) { 14851 PackageSetting ps = mSettings.mPackages.get(packageName); 14852 if (ps == null) { 14853 Log.w(TAG, "Package doesn't exist: " + packageName); 14854 return false; 14855 } 14856 if (systemUserApp) { 14857 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14858 } else { 14859 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14860 } 14861 mSettings.writeLPr(); 14862 } 14863 return true; 14864 } 14865 14866 /* 14867 * This method handles package deletion in general 14868 */ 14869 private boolean deletePackageLI(String packageName, UserHandle user, 14870 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14871 PackageRemovedInfo outInfo, boolean writeSettings, 14872 PackageParser.Package replacingPackage) { 14873 if (packageName == null) { 14874 Slog.w(TAG, "Attempt to delete null packageName."); 14875 return false; 14876 } 14877 14878 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14879 14880 PackageSetting ps; 14881 14882 synchronized (mPackages) { 14883 ps = mSettings.mPackages.get(packageName); 14884 if (ps == null) { 14885 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14886 return false; 14887 } 14888 14889 if (ps.parentPackageName != null && (!isSystemApp(ps) 14890 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14891 if (DEBUG_REMOVE) { 14892 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14893 + ((user == null) ? UserHandle.USER_ALL : user)); 14894 } 14895 final int removedUserId = (user != null) ? user.getIdentifier() 14896 : UserHandle.USER_ALL; 14897 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14898 return false; 14899 } 14900 markPackageUninstalledForUserLPw(ps, user); 14901 scheduleWritePackageRestrictionsLocked(user); 14902 return true; 14903 } 14904 } 14905 14906 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14907 && user.getIdentifier() != UserHandle.USER_ALL)) { 14908 // The caller is asking that the package only be deleted for a single 14909 // user. To do this, we just mark its uninstalled state and delete 14910 // its data. If this is a system app, we only allow this to happen if 14911 // they have set the special DELETE_SYSTEM_APP which requests different 14912 // semantics than normal for uninstalling system apps. 14913 markPackageUninstalledForUserLPw(ps, user); 14914 14915 if (!isSystemApp(ps)) { 14916 // Do not uninstall the APK if an app should be cached 14917 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14918 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14919 // Other user still have this package installed, so all 14920 // we need to do is clear this user's data and save that 14921 // it is uninstalled. 14922 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14923 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14924 return false; 14925 } 14926 scheduleWritePackageRestrictionsLocked(user); 14927 return true; 14928 } else { 14929 // We need to set it back to 'installed' so the uninstall 14930 // broadcasts will be sent correctly. 14931 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14932 ps.setInstalled(true, user.getIdentifier()); 14933 } 14934 } else { 14935 // This is a system app, so we assume that the 14936 // other users still have this package installed, so all 14937 // we need to do is clear this user's data and save that 14938 // it is uninstalled. 14939 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14940 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14941 return false; 14942 } 14943 scheduleWritePackageRestrictionsLocked(user); 14944 return true; 14945 } 14946 } 14947 14948 // If we are deleting a composite package for all users, keep track 14949 // of result for each child. 14950 if (ps.childPackageNames != null && outInfo != null) { 14951 synchronized (mPackages) { 14952 final int childCount = ps.childPackageNames.size(); 14953 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14954 for (int i = 0; i < childCount; i++) { 14955 String childPackageName = ps.childPackageNames.get(i); 14956 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14957 childInfo.removedPackage = childPackageName; 14958 outInfo.removedChildPackages.put(childPackageName, childInfo); 14959 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14960 if (childPs != null) { 14961 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14962 } 14963 } 14964 } 14965 } 14966 14967 boolean ret = false; 14968 if (isSystemApp(ps)) { 14969 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14970 // When an updated system application is deleted we delete the existing resources 14971 // as well and fall back to existing code in system partition 14972 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14973 } else { 14974 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14975 // Kill application pre-emptively especially for apps on sd. 14976 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14977 if (killApp) { 14978 killApplication(packageName, ps.appId, "uninstall pkg"); 14979 } 14980 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14981 outInfo, writeSettings, replacingPackage); 14982 } 14983 14984 // Take a note whether we deleted the package for all users 14985 if (outInfo != null) { 14986 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14987 if (outInfo.removedChildPackages != null) { 14988 synchronized (mPackages) { 14989 final int childCount = outInfo.removedChildPackages.size(); 14990 for (int i = 0; i < childCount; i++) { 14991 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14992 if (childInfo != null) { 14993 childInfo.removedForAllUsers = mPackages.get( 14994 childInfo.removedPackage) == null; 14995 } 14996 } 14997 } 14998 } 14999 // If we uninstalled an update to a system app there may be some 15000 // child packages that appeared as they are declared in the system 15001 // app but were not declared in the update. 15002 if (isSystemApp(ps)) { 15003 synchronized (mPackages) { 15004 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15005 final int childCount = (updatedPs.childPackageNames != null) 15006 ? updatedPs.childPackageNames.size() : 0; 15007 for (int i = 0; i < childCount; i++) { 15008 String childPackageName = updatedPs.childPackageNames.get(i); 15009 if (outInfo.removedChildPackages == null 15010 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15011 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15012 if (childPs == null) { 15013 continue; 15014 } 15015 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15016 installRes.name = childPackageName; 15017 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15018 installRes.pkg = mPackages.get(childPackageName); 15019 installRes.uid = childPs.pkg.applicationInfo.uid; 15020 if (outInfo.appearedChildPackages == null) { 15021 outInfo.appearedChildPackages = new ArrayMap<>(); 15022 } 15023 outInfo.appearedChildPackages.put(childPackageName, installRes); 15024 } 15025 } 15026 } 15027 } 15028 } 15029 15030 return ret; 15031 } 15032 15033 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15034 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15035 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15036 for (int nextUserId : userIds) { 15037 if (DEBUG_REMOVE) { 15038 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15039 } 15040 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15041 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15042 false /*hidden*/, false /*suspended*/, null, null, null, 15043 false /*blockUninstall*/, 15044 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15045 } 15046 } 15047 15048 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15049 PackageRemovedInfo outInfo) { 15050 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15051 : new int[] {userId}; 15052 for (int nextUserId : userIds) { 15053 if (DEBUG_REMOVE) { 15054 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15055 + nextUserId); 15056 } 15057 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15058 try { 15059 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15060 } catch (InstallerException e) { 15061 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15062 return false; 15063 } 15064 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15065 schedulePackageCleaning(ps.name, nextUserId, false); 15066 synchronized (mPackages) { 15067 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15068 scheduleWritePackageRestrictionsLocked(nextUserId); 15069 } 15070 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15071 } 15072 } 15073 15074 if (outInfo != null) { 15075 outInfo.removedPackage = ps.name; 15076 outInfo.removedAppId = ps.appId; 15077 outInfo.removedUsers = userIds; 15078 } 15079 15080 return true; 15081 } 15082 15083 private final class ClearStorageConnection implements ServiceConnection { 15084 IMediaContainerService mContainerService; 15085 15086 @Override 15087 public void onServiceConnected(ComponentName name, IBinder service) { 15088 synchronized (this) { 15089 mContainerService = IMediaContainerService.Stub.asInterface(service); 15090 notifyAll(); 15091 } 15092 } 15093 15094 @Override 15095 public void onServiceDisconnected(ComponentName name) { 15096 } 15097 } 15098 15099 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15100 final boolean mounted; 15101 if (Environment.isExternalStorageEmulated()) { 15102 mounted = true; 15103 } else { 15104 final String status = Environment.getExternalStorageState(); 15105 15106 mounted = status.equals(Environment.MEDIA_MOUNTED) 15107 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15108 } 15109 15110 if (!mounted) { 15111 return; 15112 } 15113 15114 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15115 int[] users; 15116 if (userId == UserHandle.USER_ALL) { 15117 users = sUserManager.getUserIds(); 15118 } else { 15119 users = new int[] { userId }; 15120 } 15121 final ClearStorageConnection conn = new ClearStorageConnection(); 15122 if (mContext.bindServiceAsUser( 15123 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15124 try { 15125 for (int curUser : users) { 15126 long timeout = SystemClock.uptimeMillis() + 5000; 15127 synchronized (conn) { 15128 long now = SystemClock.uptimeMillis(); 15129 while (conn.mContainerService == null && now < timeout) { 15130 try { 15131 conn.wait(timeout - now); 15132 } catch (InterruptedException e) { 15133 } 15134 } 15135 } 15136 if (conn.mContainerService == null) { 15137 return; 15138 } 15139 15140 final UserEnvironment userEnv = new UserEnvironment(curUser); 15141 clearDirectory(conn.mContainerService, 15142 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15143 if (allData) { 15144 clearDirectory(conn.mContainerService, 15145 userEnv.buildExternalStorageAppDataDirs(packageName)); 15146 clearDirectory(conn.mContainerService, 15147 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15148 } 15149 } 15150 } finally { 15151 mContext.unbindService(conn); 15152 } 15153 } 15154 } 15155 15156 @Override 15157 public void clearApplicationUserData(final String packageName, 15158 final IPackageDataObserver observer, final int userId) { 15159 mContext.enforceCallingOrSelfPermission( 15160 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15161 15162 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15163 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15164 15165 final DevicePolicyManagerInternal dpmi = LocalServices 15166 .getService(DevicePolicyManagerInternal.class); 15167 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15168 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15169 } 15170 // Queue up an async operation since the package deletion may take a little while. 15171 mHandler.post(new Runnable() { 15172 public void run() { 15173 mHandler.removeCallbacks(this); 15174 final boolean succeeded; 15175 synchronized (mInstallLock) { 15176 succeeded = clearApplicationUserDataLI(packageName, userId); 15177 } 15178 clearExternalStorageDataSync(packageName, userId, true); 15179 if (succeeded) { 15180 // invoke DeviceStorageMonitor's update method to clear any notifications 15181 DeviceStorageMonitorInternal dsm = LocalServices 15182 .getService(DeviceStorageMonitorInternal.class); 15183 if (dsm != null) { 15184 dsm.checkMemory(); 15185 } 15186 } 15187 if(observer != null) { 15188 try { 15189 observer.onRemoveCompleted(packageName, succeeded); 15190 } catch (RemoteException e) { 15191 Log.i(TAG, "Observer no longer exists."); 15192 } 15193 } //end if observer 15194 } //end run 15195 }); 15196 } 15197 15198 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15199 if (packageName == null) { 15200 Slog.w(TAG, "Attempt to delete null packageName."); 15201 return false; 15202 } 15203 15204 // Try finding details about the requested package 15205 PackageParser.Package pkg; 15206 synchronized (mPackages) { 15207 pkg = mPackages.get(packageName); 15208 if (pkg == null) { 15209 final PackageSetting ps = mSettings.mPackages.get(packageName); 15210 if (ps != null) { 15211 pkg = ps.pkg; 15212 } 15213 } 15214 15215 if (pkg == null) { 15216 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15217 return false; 15218 } 15219 15220 PackageSetting ps = (PackageSetting) pkg.mExtras; 15221 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15222 } 15223 15224 // Always delete data directories for package, even if we found no other 15225 // record of app. This helps users recover from UID mismatches without 15226 // resorting to a full data wipe. 15227 // TODO: triage flags as part of 26466827 15228 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15229 try { 15230 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15231 } catch (InstallerException e) { 15232 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15233 return false; 15234 } 15235 15236 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15237 removeKeystoreDataIfNeeded(userId, appId); 15238 15239 // Create a native library symlink only if we have native libraries 15240 // and if the native libraries are 32 bit libraries. We do not provide 15241 // this symlink for 64 bit libraries. 15242 if (pkg.applicationInfo.primaryCpuAbi != null && 15243 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15244 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15245 try { 15246 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15247 nativeLibPath, userId); 15248 } catch (InstallerException e) { 15249 Slog.w(TAG, "Failed linking native library dir", e); 15250 return false; 15251 } 15252 } 15253 15254 return true; 15255 } 15256 15257 /** 15258 * Reverts user permission state changes (permissions and flags) in 15259 * all packages for a given user. 15260 * 15261 * @param userId The device user for which to do a reset. 15262 */ 15263 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15264 final int packageCount = mPackages.size(); 15265 for (int i = 0; i < packageCount; i++) { 15266 PackageParser.Package pkg = mPackages.valueAt(i); 15267 PackageSetting ps = (PackageSetting) pkg.mExtras; 15268 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15269 } 15270 } 15271 15272 /** 15273 * Reverts user permission state changes (permissions and flags). 15274 * 15275 * @param ps The package for which to reset. 15276 * @param userId The device user for which to do a reset. 15277 */ 15278 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15279 final PackageSetting ps, final int userId) { 15280 if (ps.pkg == null) { 15281 return; 15282 } 15283 15284 // These are flags that can change base on user actions. 15285 final int userSettableMask = FLAG_PERMISSION_USER_SET 15286 | FLAG_PERMISSION_USER_FIXED 15287 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15288 | FLAG_PERMISSION_REVIEW_REQUIRED; 15289 15290 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15291 | FLAG_PERMISSION_POLICY_FIXED; 15292 15293 boolean writeInstallPermissions = false; 15294 boolean writeRuntimePermissions = false; 15295 15296 final int permissionCount = ps.pkg.requestedPermissions.size(); 15297 for (int i = 0; i < permissionCount; i++) { 15298 String permission = ps.pkg.requestedPermissions.get(i); 15299 15300 BasePermission bp = mSettings.mPermissions.get(permission); 15301 if (bp == null) { 15302 continue; 15303 } 15304 15305 // If shared user we just reset the state to which only this app contributed. 15306 if (ps.sharedUser != null) { 15307 boolean used = false; 15308 final int packageCount = ps.sharedUser.packages.size(); 15309 for (int j = 0; j < packageCount; j++) { 15310 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15311 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15312 && pkg.pkg.requestedPermissions.contains(permission)) { 15313 used = true; 15314 break; 15315 } 15316 } 15317 if (used) { 15318 continue; 15319 } 15320 } 15321 15322 PermissionsState permissionsState = ps.getPermissionsState(); 15323 15324 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15325 15326 // Always clear the user settable flags. 15327 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15328 bp.name) != null; 15329 // If permission review is enabled and this is a legacy app, mark the 15330 // permission as requiring a review as this is the initial state. 15331 int flags = 0; 15332 if (Build.PERMISSIONS_REVIEW_REQUIRED 15333 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15334 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15335 } 15336 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15337 if (hasInstallState) { 15338 writeInstallPermissions = true; 15339 } else { 15340 writeRuntimePermissions = true; 15341 } 15342 } 15343 15344 // Below is only runtime permission handling. 15345 if (!bp.isRuntime()) { 15346 continue; 15347 } 15348 15349 // Never clobber system or policy. 15350 if ((oldFlags & policyOrSystemFlags) != 0) { 15351 continue; 15352 } 15353 15354 // If this permission was granted by default, make sure it is. 15355 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15356 if (permissionsState.grantRuntimePermission(bp, userId) 15357 != PERMISSION_OPERATION_FAILURE) { 15358 writeRuntimePermissions = true; 15359 } 15360 // If permission review is enabled the permissions for a legacy apps 15361 // are represented as constantly granted runtime ones, so don't revoke. 15362 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15363 // Otherwise, reset the permission. 15364 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15365 switch (revokeResult) { 15366 case PERMISSION_OPERATION_SUCCESS: { 15367 writeRuntimePermissions = true; 15368 } break; 15369 15370 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15371 writeRuntimePermissions = true; 15372 final int appId = ps.appId; 15373 mHandler.post(new Runnable() { 15374 @Override 15375 public void run() { 15376 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15377 } 15378 }); 15379 } break; 15380 } 15381 } 15382 } 15383 15384 // Synchronously write as we are taking permissions away. 15385 if (writeRuntimePermissions) { 15386 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15387 } 15388 15389 // Synchronously write as we are taking permissions away. 15390 if (writeInstallPermissions) { 15391 mSettings.writeLPr(); 15392 } 15393 } 15394 15395 /** 15396 * Remove entries from the keystore daemon. Will only remove it if the 15397 * {@code appId} is valid. 15398 */ 15399 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15400 if (appId < 0) { 15401 return; 15402 } 15403 15404 final KeyStore keyStore = KeyStore.getInstance(); 15405 if (keyStore != null) { 15406 if (userId == UserHandle.USER_ALL) { 15407 for (final int individual : sUserManager.getUserIds()) { 15408 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15409 } 15410 } else { 15411 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15412 } 15413 } else { 15414 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15415 } 15416 } 15417 15418 @Override 15419 public void deleteApplicationCacheFiles(final String packageName, 15420 final IPackageDataObserver observer) { 15421 mContext.enforceCallingOrSelfPermission( 15422 android.Manifest.permission.DELETE_CACHE_FILES, null); 15423 // Queue up an async operation since the package deletion may take a little while. 15424 final int userId = UserHandle.getCallingUserId(); 15425 mHandler.post(new Runnable() { 15426 public void run() { 15427 mHandler.removeCallbacks(this); 15428 final boolean succeded; 15429 synchronized (mInstallLock) { 15430 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15431 } 15432 clearExternalStorageDataSync(packageName, userId, false); 15433 if (observer != null) { 15434 try { 15435 observer.onRemoveCompleted(packageName, succeded); 15436 } catch (RemoteException e) { 15437 Log.i(TAG, "Observer no longer exists."); 15438 } 15439 } //end if observer 15440 } //end run 15441 }); 15442 } 15443 15444 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15445 if (packageName == null) { 15446 Slog.w(TAG, "Attempt to delete null packageName."); 15447 return false; 15448 } 15449 PackageParser.Package p; 15450 synchronized (mPackages) { 15451 p = mPackages.get(packageName); 15452 } 15453 if (p == null) { 15454 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15455 return false; 15456 } 15457 final ApplicationInfo applicationInfo = p.applicationInfo; 15458 if (applicationInfo == null) { 15459 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15460 return false; 15461 } 15462 // TODO: triage flags as part of 26466827 15463 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15464 try { 15465 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15466 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15467 } catch (InstallerException e) { 15468 Slog.w(TAG, "Couldn't remove cache files for package " 15469 + packageName + " u" + userId, e); 15470 return false; 15471 } 15472 return true; 15473 } 15474 15475 @Override 15476 public void getPackageSizeInfo(final String packageName, int userHandle, 15477 final IPackageStatsObserver observer) { 15478 mContext.enforceCallingOrSelfPermission( 15479 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15480 if (packageName == null) { 15481 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15482 } 15483 15484 PackageStats stats = new PackageStats(packageName, userHandle); 15485 15486 /* 15487 * Queue up an async operation since the package measurement may take a 15488 * little while. 15489 */ 15490 Message msg = mHandler.obtainMessage(INIT_COPY); 15491 msg.obj = new MeasureParams(stats, observer); 15492 mHandler.sendMessage(msg); 15493 } 15494 15495 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15496 PackageStats pStats) { 15497 if (packageName == null) { 15498 Slog.w(TAG, "Attempt to get size of null packageName."); 15499 return false; 15500 } 15501 PackageParser.Package p; 15502 boolean dataOnly = false; 15503 String libDirRoot = null; 15504 String asecPath = null; 15505 PackageSetting ps = null; 15506 synchronized (mPackages) { 15507 p = mPackages.get(packageName); 15508 ps = mSettings.mPackages.get(packageName); 15509 if(p == null) { 15510 dataOnly = true; 15511 if((ps == null) || (ps.pkg == null)) { 15512 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15513 return false; 15514 } 15515 p = ps.pkg; 15516 } 15517 if (ps != null) { 15518 libDirRoot = ps.legacyNativeLibraryPathString; 15519 } 15520 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15521 final long token = Binder.clearCallingIdentity(); 15522 try { 15523 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15524 if (secureContainerId != null) { 15525 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15526 } 15527 } finally { 15528 Binder.restoreCallingIdentity(token); 15529 } 15530 } 15531 } 15532 String publicSrcDir = null; 15533 if(!dataOnly) { 15534 final ApplicationInfo applicationInfo = p.applicationInfo; 15535 if (applicationInfo == null) { 15536 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15537 return false; 15538 } 15539 if (p.isForwardLocked()) { 15540 publicSrcDir = applicationInfo.getBaseResourcePath(); 15541 } 15542 } 15543 // TODO: extend to measure size of split APKs 15544 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15545 // not just the first level. 15546 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15547 // just the primary. 15548 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15549 15550 String apkPath; 15551 File packageDir = new File(p.codePath); 15552 15553 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15554 apkPath = packageDir.getAbsolutePath(); 15555 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15556 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15557 libDirRoot = null; 15558 } 15559 } else { 15560 apkPath = p.baseCodePath; 15561 } 15562 15563 // TODO: triage flags as part of 26466827 15564 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15565 try { 15566 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15567 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15568 } catch (InstallerException e) { 15569 return false; 15570 } 15571 15572 // Fix-up for forward-locked applications in ASEC containers. 15573 if (!isExternal(p)) { 15574 pStats.codeSize += pStats.externalCodeSize; 15575 pStats.externalCodeSize = 0L; 15576 } 15577 15578 return true; 15579 } 15580 15581 private int getUidTargetSdkVersionLockedLPr(int uid) { 15582 Object obj = mSettings.getUserIdLPr(uid); 15583 if (obj instanceof SharedUserSetting) { 15584 final SharedUserSetting sus = (SharedUserSetting) obj; 15585 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15586 final Iterator<PackageSetting> it = sus.packages.iterator(); 15587 while (it.hasNext()) { 15588 final PackageSetting ps = it.next(); 15589 if (ps.pkg != null) { 15590 int v = ps.pkg.applicationInfo.targetSdkVersion; 15591 if (v < vers) vers = v; 15592 } 15593 } 15594 return vers; 15595 } else if (obj instanceof PackageSetting) { 15596 final PackageSetting ps = (PackageSetting) obj; 15597 if (ps.pkg != null) { 15598 return ps.pkg.applicationInfo.targetSdkVersion; 15599 } 15600 } 15601 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15602 } 15603 15604 @Override 15605 public void addPreferredActivity(IntentFilter filter, int match, 15606 ComponentName[] set, ComponentName activity, int userId) { 15607 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15608 "Adding preferred"); 15609 } 15610 15611 private void addPreferredActivityInternal(IntentFilter filter, int match, 15612 ComponentName[] set, ComponentName activity, boolean always, int userId, 15613 String opname) { 15614 // writer 15615 int callingUid = Binder.getCallingUid(); 15616 enforceCrossUserPermission(callingUid, userId, 15617 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15618 if (filter.countActions() == 0) { 15619 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15620 return; 15621 } 15622 synchronized (mPackages) { 15623 if (mContext.checkCallingOrSelfPermission( 15624 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15625 != PackageManager.PERMISSION_GRANTED) { 15626 if (getUidTargetSdkVersionLockedLPr(callingUid) 15627 < Build.VERSION_CODES.FROYO) { 15628 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15629 + callingUid); 15630 return; 15631 } 15632 mContext.enforceCallingOrSelfPermission( 15633 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15634 } 15635 15636 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15637 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15638 + userId + ":"); 15639 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15640 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15641 scheduleWritePackageRestrictionsLocked(userId); 15642 } 15643 } 15644 15645 @Override 15646 public void replacePreferredActivity(IntentFilter filter, int match, 15647 ComponentName[] set, ComponentName activity, int userId) { 15648 if (filter.countActions() != 1) { 15649 throw new IllegalArgumentException( 15650 "replacePreferredActivity expects filter to have only 1 action."); 15651 } 15652 if (filter.countDataAuthorities() != 0 15653 || filter.countDataPaths() != 0 15654 || filter.countDataSchemes() > 1 15655 || filter.countDataTypes() != 0) { 15656 throw new IllegalArgumentException( 15657 "replacePreferredActivity expects filter to have no data authorities, " + 15658 "paths, or types; and at most one scheme."); 15659 } 15660 15661 final int callingUid = Binder.getCallingUid(); 15662 enforceCrossUserPermission(callingUid, userId, 15663 true /* requireFullPermission */, false /* checkShell */, 15664 "replace preferred activity"); 15665 synchronized (mPackages) { 15666 if (mContext.checkCallingOrSelfPermission( 15667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15668 != PackageManager.PERMISSION_GRANTED) { 15669 if (getUidTargetSdkVersionLockedLPr(callingUid) 15670 < Build.VERSION_CODES.FROYO) { 15671 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15672 + Binder.getCallingUid()); 15673 return; 15674 } 15675 mContext.enforceCallingOrSelfPermission( 15676 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15677 } 15678 15679 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15680 if (pir != null) { 15681 // Get all of the existing entries that exactly match this filter. 15682 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15683 if (existing != null && existing.size() == 1) { 15684 PreferredActivity cur = existing.get(0); 15685 if (DEBUG_PREFERRED) { 15686 Slog.i(TAG, "Checking replace of preferred:"); 15687 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15688 if (!cur.mPref.mAlways) { 15689 Slog.i(TAG, " -- CUR; not mAlways!"); 15690 } else { 15691 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15692 Slog.i(TAG, " -- CUR: mSet=" 15693 + Arrays.toString(cur.mPref.mSetComponents)); 15694 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15695 Slog.i(TAG, " -- NEW: mMatch=" 15696 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15697 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15698 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15699 } 15700 } 15701 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15702 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15703 && cur.mPref.sameSet(set)) { 15704 // Setting the preferred activity to what it happens to be already 15705 if (DEBUG_PREFERRED) { 15706 Slog.i(TAG, "Replacing with same preferred activity " 15707 + cur.mPref.mShortComponent + " for user " 15708 + userId + ":"); 15709 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15710 } 15711 return; 15712 } 15713 } 15714 15715 if (existing != null) { 15716 if (DEBUG_PREFERRED) { 15717 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15718 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15719 } 15720 for (int i = 0; i < existing.size(); i++) { 15721 PreferredActivity pa = existing.get(i); 15722 if (DEBUG_PREFERRED) { 15723 Slog.i(TAG, "Removing existing preferred activity " 15724 + pa.mPref.mComponent + ":"); 15725 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15726 } 15727 pir.removeFilter(pa); 15728 } 15729 } 15730 } 15731 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15732 "Replacing preferred"); 15733 } 15734 } 15735 15736 @Override 15737 public void clearPackagePreferredActivities(String packageName) { 15738 final int uid = Binder.getCallingUid(); 15739 // writer 15740 synchronized (mPackages) { 15741 PackageParser.Package pkg = mPackages.get(packageName); 15742 if (pkg == null || pkg.applicationInfo.uid != uid) { 15743 if (mContext.checkCallingOrSelfPermission( 15744 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15745 != PackageManager.PERMISSION_GRANTED) { 15746 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15747 < Build.VERSION_CODES.FROYO) { 15748 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15749 + Binder.getCallingUid()); 15750 return; 15751 } 15752 mContext.enforceCallingOrSelfPermission( 15753 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15754 } 15755 } 15756 15757 int user = UserHandle.getCallingUserId(); 15758 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15759 scheduleWritePackageRestrictionsLocked(user); 15760 } 15761 } 15762 } 15763 15764 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15765 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15766 ArrayList<PreferredActivity> removed = null; 15767 boolean changed = false; 15768 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15769 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15770 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15771 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15772 continue; 15773 } 15774 Iterator<PreferredActivity> it = pir.filterIterator(); 15775 while (it.hasNext()) { 15776 PreferredActivity pa = it.next(); 15777 // Mark entry for removal only if it matches the package name 15778 // and the entry is of type "always". 15779 if (packageName == null || 15780 (pa.mPref.mComponent.getPackageName().equals(packageName) 15781 && pa.mPref.mAlways)) { 15782 if (removed == null) { 15783 removed = new ArrayList<PreferredActivity>(); 15784 } 15785 removed.add(pa); 15786 } 15787 } 15788 if (removed != null) { 15789 for (int j=0; j<removed.size(); j++) { 15790 PreferredActivity pa = removed.get(j); 15791 pir.removeFilter(pa); 15792 } 15793 changed = true; 15794 } 15795 } 15796 return changed; 15797 } 15798 15799 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15800 private void clearIntentFilterVerificationsLPw(int userId) { 15801 final int packageCount = mPackages.size(); 15802 for (int i = 0; i < packageCount; i++) { 15803 PackageParser.Package pkg = mPackages.valueAt(i); 15804 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15805 } 15806 } 15807 15808 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15809 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15810 if (userId == UserHandle.USER_ALL) { 15811 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15812 sUserManager.getUserIds())) { 15813 for (int oneUserId : sUserManager.getUserIds()) { 15814 scheduleWritePackageRestrictionsLocked(oneUserId); 15815 } 15816 } 15817 } else { 15818 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15819 scheduleWritePackageRestrictionsLocked(userId); 15820 } 15821 } 15822 } 15823 15824 void clearDefaultBrowserIfNeeded(String packageName) { 15825 for (int oneUserId : sUserManager.getUserIds()) { 15826 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15827 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15828 if (packageName.equals(defaultBrowserPackageName)) { 15829 setDefaultBrowserPackageName(null, oneUserId); 15830 } 15831 } 15832 } 15833 15834 @Override 15835 public void resetApplicationPreferences(int userId) { 15836 mContext.enforceCallingOrSelfPermission( 15837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15838 // writer 15839 synchronized (mPackages) { 15840 final long identity = Binder.clearCallingIdentity(); 15841 try { 15842 clearPackagePreferredActivitiesLPw(null, userId); 15843 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15844 // TODO: We have to reset the default SMS and Phone. This requires 15845 // significant refactoring to keep all default apps in the package 15846 // manager (cleaner but more work) or have the services provide 15847 // callbacks to the package manager to request a default app reset. 15848 applyFactoryDefaultBrowserLPw(userId); 15849 clearIntentFilterVerificationsLPw(userId); 15850 primeDomainVerificationsLPw(userId); 15851 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15852 scheduleWritePackageRestrictionsLocked(userId); 15853 } finally { 15854 Binder.restoreCallingIdentity(identity); 15855 } 15856 } 15857 } 15858 15859 @Override 15860 public int getPreferredActivities(List<IntentFilter> outFilters, 15861 List<ComponentName> outActivities, String packageName) { 15862 15863 int num = 0; 15864 final int userId = UserHandle.getCallingUserId(); 15865 // reader 15866 synchronized (mPackages) { 15867 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15868 if (pir != null) { 15869 final Iterator<PreferredActivity> it = pir.filterIterator(); 15870 while (it.hasNext()) { 15871 final PreferredActivity pa = it.next(); 15872 if (packageName == null 15873 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15874 && pa.mPref.mAlways)) { 15875 if (outFilters != null) { 15876 outFilters.add(new IntentFilter(pa)); 15877 } 15878 if (outActivities != null) { 15879 outActivities.add(pa.mPref.mComponent); 15880 } 15881 } 15882 } 15883 } 15884 } 15885 15886 return num; 15887 } 15888 15889 @Override 15890 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15891 int userId) { 15892 int callingUid = Binder.getCallingUid(); 15893 if (callingUid != Process.SYSTEM_UID) { 15894 throw new SecurityException( 15895 "addPersistentPreferredActivity can only be run by the system"); 15896 } 15897 if (filter.countActions() == 0) { 15898 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15899 return; 15900 } 15901 synchronized (mPackages) { 15902 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15903 ":"); 15904 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15905 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15906 new PersistentPreferredActivity(filter, activity)); 15907 scheduleWritePackageRestrictionsLocked(userId); 15908 } 15909 } 15910 15911 @Override 15912 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15913 int callingUid = Binder.getCallingUid(); 15914 if (callingUid != Process.SYSTEM_UID) { 15915 throw new SecurityException( 15916 "clearPackagePersistentPreferredActivities can only be run by the system"); 15917 } 15918 ArrayList<PersistentPreferredActivity> removed = null; 15919 boolean changed = false; 15920 synchronized (mPackages) { 15921 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15922 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15923 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15924 .valueAt(i); 15925 if (userId != thisUserId) { 15926 continue; 15927 } 15928 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15929 while (it.hasNext()) { 15930 PersistentPreferredActivity ppa = it.next(); 15931 // Mark entry for removal only if it matches the package name. 15932 if (ppa.mComponent.getPackageName().equals(packageName)) { 15933 if (removed == null) { 15934 removed = new ArrayList<PersistentPreferredActivity>(); 15935 } 15936 removed.add(ppa); 15937 } 15938 } 15939 if (removed != null) { 15940 for (int j=0; j<removed.size(); j++) { 15941 PersistentPreferredActivity ppa = removed.get(j); 15942 ppir.removeFilter(ppa); 15943 } 15944 changed = true; 15945 } 15946 } 15947 15948 if (changed) { 15949 scheduleWritePackageRestrictionsLocked(userId); 15950 } 15951 } 15952 } 15953 15954 /** 15955 * Common machinery for picking apart a restored XML blob and passing 15956 * it to a caller-supplied functor to be applied to the running system. 15957 */ 15958 private void restoreFromXml(XmlPullParser parser, int userId, 15959 String expectedStartTag, BlobXmlRestorer functor) 15960 throws IOException, XmlPullParserException { 15961 int type; 15962 while ((type = parser.next()) != XmlPullParser.START_TAG 15963 && type != XmlPullParser.END_DOCUMENT) { 15964 } 15965 if (type != XmlPullParser.START_TAG) { 15966 // oops didn't find a start tag?! 15967 if (DEBUG_BACKUP) { 15968 Slog.e(TAG, "Didn't find start tag during restore"); 15969 } 15970 return; 15971 } 15972Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15973 // this is supposed to be TAG_PREFERRED_BACKUP 15974 if (!expectedStartTag.equals(parser.getName())) { 15975 if (DEBUG_BACKUP) { 15976 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15977 } 15978 return; 15979 } 15980 15981 // skip interfering stuff, then we're aligned with the backing implementation 15982 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15983Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15984 functor.apply(parser, userId); 15985 } 15986 15987 private interface BlobXmlRestorer { 15988 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15989 } 15990 15991 /** 15992 * Non-Binder method, support for the backup/restore mechanism: write the 15993 * full set of preferred activities in its canonical XML format. Returns the 15994 * XML output as a byte array, or null if there is none. 15995 */ 15996 @Override 15997 public byte[] getPreferredActivityBackup(int userId) { 15998 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15999 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16000 } 16001 16002 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16003 try { 16004 final XmlSerializer serializer = new FastXmlSerializer(); 16005 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16006 serializer.startDocument(null, true); 16007 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16008 16009 synchronized (mPackages) { 16010 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16011 } 16012 16013 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16014 serializer.endDocument(); 16015 serializer.flush(); 16016 } catch (Exception e) { 16017 if (DEBUG_BACKUP) { 16018 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16019 } 16020 return null; 16021 } 16022 16023 return dataStream.toByteArray(); 16024 } 16025 16026 @Override 16027 public void restorePreferredActivities(byte[] backup, int userId) { 16028 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16029 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16030 } 16031 16032 try { 16033 final XmlPullParser parser = Xml.newPullParser(); 16034 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16035 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16036 new BlobXmlRestorer() { 16037 @Override 16038 public void apply(XmlPullParser parser, int userId) 16039 throws XmlPullParserException, IOException { 16040 synchronized (mPackages) { 16041 mSettings.readPreferredActivitiesLPw(parser, userId); 16042 } 16043 } 16044 } ); 16045 } catch (Exception e) { 16046 if (DEBUG_BACKUP) { 16047 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16048 } 16049 } 16050 } 16051 16052 /** 16053 * Non-Binder method, support for the backup/restore mechanism: write the 16054 * default browser (etc) settings in its canonical XML format. Returns the default 16055 * browser XML representation as a byte array, or null if there is none. 16056 */ 16057 @Override 16058 public byte[] getDefaultAppsBackup(int userId) { 16059 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16060 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16061 } 16062 16063 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16064 try { 16065 final XmlSerializer serializer = new FastXmlSerializer(); 16066 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16067 serializer.startDocument(null, true); 16068 serializer.startTag(null, TAG_DEFAULT_APPS); 16069 16070 synchronized (mPackages) { 16071 mSettings.writeDefaultAppsLPr(serializer, userId); 16072 } 16073 16074 serializer.endTag(null, TAG_DEFAULT_APPS); 16075 serializer.endDocument(); 16076 serializer.flush(); 16077 } catch (Exception e) { 16078 if (DEBUG_BACKUP) { 16079 Slog.e(TAG, "Unable to write default apps for backup", e); 16080 } 16081 return null; 16082 } 16083 16084 return dataStream.toByteArray(); 16085 } 16086 16087 @Override 16088 public void restoreDefaultApps(byte[] backup, int userId) { 16089 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16090 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16091 } 16092 16093 try { 16094 final XmlPullParser parser = Xml.newPullParser(); 16095 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16096 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16097 new BlobXmlRestorer() { 16098 @Override 16099 public void apply(XmlPullParser parser, int userId) 16100 throws XmlPullParserException, IOException { 16101 synchronized (mPackages) { 16102 mSettings.readDefaultAppsLPw(parser, userId); 16103 } 16104 } 16105 } ); 16106 } catch (Exception e) { 16107 if (DEBUG_BACKUP) { 16108 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16109 } 16110 } 16111 } 16112 16113 @Override 16114 public byte[] getIntentFilterVerificationBackup(int userId) { 16115 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16116 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16117 } 16118 16119 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16120 try { 16121 final XmlSerializer serializer = new FastXmlSerializer(); 16122 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16123 serializer.startDocument(null, true); 16124 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16125 16126 synchronized (mPackages) { 16127 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16128 } 16129 16130 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16131 serializer.endDocument(); 16132 serializer.flush(); 16133 } catch (Exception e) { 16134 if (DEBUG_BACKUP) { 16135 Slog.e(TAG, "Unable to write default apps for backup", e); 16136 } 16137 return null; 16138 } 16139 16140 return dataStream.toByteArray(); 16141 } 16142 16143 @Override 16144 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16145 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16146 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16147 } 16148 16149 try { 16150 final XmlPullParser parser = Xml.newPullParser(); 16151 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16152 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16153 new BlobXmlRestorer() { 16154 @Override 16155 public void apply(XmlPullParser parser, int userId) 16156 throws XmlPullParserException, IOException { 16157 synchronized (mPackages) { 16158 mSettings.readAllDomainVerificationsLPr(parser, userId); 16159 mSettings.writeLPr(); 16160 } 16161 } 16162 } ); 16163 } catch (Exception e) { 16164 if (DEBUG_BACKUP) { 16165 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16166 } 16167 } 16168 } 16169 16170 @Override 16171 public byte[] getPermissionGrantBackup(int userId) { 16172 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16173 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16174 } 16175 16176 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16177 try { 16178 final XmlSerializer serializer = new FastXmlSerializer(); 16179 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16180 serializer.startDocument(null, true); 16181 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16182 16183 synchronized (mPackages) { 16184 serializeRuntimePermissionGrantsLPr(serializer, userId); 16185 } 16186 16187 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16188 serializer.endDocument(); 16189 serializer.flush(); 16190 } catch (Exception e) { 16191 if (DEBUG_BACKUP) { 16192 Slog.e(TAG, "Unable to write default apps for backup", e); 16193 } 16194 return null; 16195 } 16196 16197 return dataStream.toByteArray(); 16198 } 16199 16200 @Override 16201 public void restorePermissionGrants(byte[] backup, int userId) { 16202 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16203 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16204 } 16205 16206 try { 16207 final XmlPullParser parser = Xml.newPullParser(); 16208 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16209 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16210 new BlobXmlRestorer() { 16211 @Override 16212 public void apply(XmlPullParser parser, int userId) 16213 throws XmlPullParserException, IOException { 16214 synchronized (mPackages) { 16215 processRestoredPermissionGrantsLPr(parser, userId); 16216 } 16217 } 16218 } ); 16219 } catch (Exception e) { 16220 if (DEBUG_BACKUP) { 16221 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16222 } 16223 } 16224 } 16225 16226 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16227 throws IOException { 16228 serializer.startTag(null, TAG_ALL_GRANTS); 16229 16230 final int N = mSettings.mPackages.size(); 16231 for (int i = 0; i < N; i++) { 16232 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16233 boolean pkgGrantsKnown = false; 16234 16235 PermissionsState packagePerms = ps.getPermissionsState(); 16236 16237 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16238 final int grantFlags = state.getFlags(); 16239 // only look at grants that are not system/policy fixed 16240 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16241 final boolean isGranted = state.isGranted(); 16242 // And only back up the user-twiddled state bits 16243 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16244 final String packageName = mSettings.mPackages.keyAt(i); 16245 if (!pkgGrantsKnown) { 16246 serializer.startTag(null, TAG_GRANT); 16247 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16248 pkgGrantsKnown = true; 16249 } 16250 16251 final boolean userSet = 16252 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16253 final boolean userFixed = 16254 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16255 final boolean revoke = 16256 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16257 16258 serializer.startTag(null, TAG_PERMISSION); 16259 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16260 if (isGranted) { 16261 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16262 } 16263 if (userSet) { 16264 serializer.attribute(null, ATTR_USER_SET, "true"); 16265 } 16266 if (userFixed) { 16267 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16268 } 16269 if (revoke) { 16270 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16271 } 16272 serializer.endTag(null, TAG_PERMISSION); 16273 } 16274 } 16275 } 16276 16277 if (pkgGrantsKnown) { 16278 serializer.endTag(null, TAG_GRANT); 16279 } 16280 } 16281 16282 serializer.endTag(null, TAG_ALL_GRANTS); 16283 } 16284 16285 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16286 throws XmlPullParserException, IOException { 16287 String pkgName = null; 16288 int outerDepth = parser.getDepth(); 16289 int type; 16290 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16291 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16292 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16293 continue; 16294 } 16295 16296 final String tagName = parser.getName(); 16297 if (tagName.equals(TAG_GRANT)) { 16298 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16299 if (DEBUG_BACKUP) { 16300 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16301 } 16302 } else if (tagName.equals(TAG_PERMISSION)) { 16303 16304 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16305 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16306 16307 int newFlagSet = 0; 16308 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16309 newFlagSet |= FLAG_PERMISSION_USER_SET; 16310 } 16311 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16312 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16313 } 16314 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16315 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16316 } 16317 if (DEBUG_BACKUP) { 16318 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16319 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16320 } 16321 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16322 if (ps != null) { 16323 // Already installed so we apply the grant immediately 16324 if (DEBUG_BACKUP) { 16325 Slog.v(TAG, " + already installed; applying"); 16326 } 16327 PermissionsState perms = ps.getPermissionsState(); 16328 BasePermission bp = mSettings.mPermissions.get(permName); 16329 if (bp != null) { 16330 if (isGranted) { 16331 perms.grantRuntimePermission(bp, userId); 16332 } 16333 if (newFlagSet != 0) { 16334 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16335 } 16336 } 16337 } else { 16338 // Need to wait for post-restore install to apply the grant 16339 if (DEBUG_BACKUP) { 16340 Slog.v(TAG, " - not yet installed; saving for later"); 16341 } 16342 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16343 isGranted, newFlagSet, userId); 16344 } 16345 } else { 16346 PackageManagerService.reportSettingsProblem(Log.WARN, 16347 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16348 XmlUtils.skipCurrentTag(parser); 16349 } 16350 } 16351 16352 scheduleWriteSettingsLocked(); 16353 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16354 } 16355 16356 @Override 16357 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16358 int sourceUserId, int targetUserId, int flags) { 16359 mContext.enforceCallingOrSelfPermission( 16360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16361 int callingUid = Binder.getCallingUid(); 16362 enforceOwnerRights(ownerPackage, callingUid); 16363 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16364 if (intentFilter.countActions() == 0) { 16365 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16366 return; 16367 } 16368 synchronized (mPackages) { 16369 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16370 ownerPackage, targetUserId, flags); 16371 CrossProfileIntentResolver resolver = 16372 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16373 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16374 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16375 if (existing != null) { 16376 int size = existing.size(); 16377 for (int i = 0; i < size; i++) { 16378 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16379 return; 16380 } 16381 } 16382 } 16383 resolver.addFilter(newFilter); 16384 scheduleWritePackageRestrictionsLocked(sourceUserId); 16385 } 16386 } 16387 16388 @Override 16389 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16390 mContext.enforceCallingOrSelfPermission( 16391 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16392 int callingUid = Binder.getCallingUid(); 16393 enforceOwnerRights(ownerPackage, callingUid); 16394 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16395 synchronized (mPackages) { 16396 CrossProfileIntentResolver resolver = 16397 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16398 ArraySet<CrossProfileIntentFilter> set = 16399 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16400 for (CrossProfileIntentFilter filter : set) { 16401 if (filter.getOwnerPackage().equals(ownerPackage)) { 16402 resolver.removeFilter(filter); 16403 } 16404 } 16405 scheduleWritePackageRestrictionsLocked(sourceUserId); 16406 } 16407 } 16408 16409 // Enforcing that callingUid is owning pkg on userId 16410 private void enforceOwnerRights(String pkg, int callingUid) { 16411 // The system owns everything. 16412 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16413 return; 16414 } 16415 int callingUserId = UserHandle.getUserId(callingUid); 16416 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16417 if (pi == null) { 16418 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16419 + callingUserId); 16420 } 16421 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16422 throw new SecurityException("Calling uid " + callingUid 16423 + " does not own package " + pkg); 16424 } 16425 } 16426 16427 @Override 16428 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16429 Intent intent = new Intent(Intent.ACTION_MAIN); 16430 intent.addCategory(Intent.CATEGORY_HOME); 16431 16432 final int callingUserId = UserHandle.getCallingUserId(); 16433 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16434 PackageManager.GET_META_DATA, callingUserId); 16435 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16436 true, false, false, callingUserId); 16437 16438 allHomeCandidates.clear(); 16439 if (list != null) { 16440 for (ResolveInfo ri : list) { 16441 allHomeCandidates.add(ri); 16442 } 16443 } 16444 return (preferred == null || preferred.activityInfo == null) 16445 ? null 16446 : new ComponentName(preferred.activityInfo.packageName, 16447 preferred.activityInfo.name); 16448 } 16449 16450 @Override 16451 public void setApplicationEnabledSetting(String appPackageName, 16452 int newState, int flags, int userId, String callingPackage) { 16453 if (!sUserManager.exists(userId)) return; 16454 if (callingPackage == null) { 16455 callingPackage = Integer.toString(Binder.getCallingUid()); 16456 } 16457 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16458 } 16459 16460 @Override 16461 public void setComponentEnabledSetting(ComponentName componentName, 16462 int newState, int flags, int userId) { 16463 if (!sUserManager.exists(userId)) return; 16464 setEnabledSetting(componentName.getPackageName(), 16465 componentName.getClassName(), newState, flags, userId, null); 16466 } 16467 16468 private void setEnabledSetting(final String packageName, String className, int newState, 16469 final int flags, int userId, String callingPackage) { 16470 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16471 || newState == COMPONENT_ENABLED_STATE_ENABLED 16472 || newState == COMPONENT_ENABLED_STATE_DISABLED 16473 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16474 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16475 throw new IllegalArgumentException("Invalid new component state: " 16476 + newState); 16477 } 16478 PackageSetting pkgSetting; 16479 final int uid = Binder.getCallingUid(); 16480 final int permission = mContext.checkCallingOrSelfPermission( 16481 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16482 enforceCrossUserPermission(uid, userId, 16483 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16484 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16485 boolean sendNow = false; 16486 boolean isApp = (className == null); 16487 String componentName = isApp ? packageName : className; 16488 int packageUid = -1; 16489 ArrayList<String> components; 16490 16491 // writer 16492 synchronized (mPackages) { 16493 pkgSetting = mSettings.mPackages.get(packageName); 16494 if (pkgSetting == null) { 16495 if (className == null) { 16496 throw new IllegalArgumentException("Unknown package: " + packageName); 16497 } 16498 throw new IllegalArgumentException( 16499 "Unknown component: " + packageName + "/" + className); 16500 } 16501 // Allow root and verify that userId is not being specified by a different user 16502 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16503 throw new SecurityException( 16504 "Permission Denial: attempt to change component state from pid=" 16505 + Binder.getCallingPid() 16506 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16507 } 16508 if (className == null) { 16509 // We're dealing with an application/package level state change 16510 if (pkgSetting.getEnabled(userId) == newState) { 16511 // Nothing to do 16512 return; 16513 } 16514 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16515 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16516 // Don't care about who enables an app. 16517 callingPackage = null; 16518 } 16519 pkgSetting.setEnabled(newState, userId, callingPackage); 16520 // pkgSetting.pkg.mSetEnabled = newState; 16521 } else { 16522 // We're dealing with a component level state change 16523 // First, verify that this is a valid class name. 16524 PackageParser.Package pkg = pkgSetting.pkg; 16525 if (pkg == null || !pkg.hasComponentClassName(className)) { 16526 if (pkg != null && 16527 pkg.applicationInfo.targetSdkVersion >= 16528 Build.VERSION_CODES.JELLY_BEAN) { 16529 throw new IllegalArgumentException("Component class " + className 16530 + " does not exist in " + packageName); 16531 } else { 16532 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16533 + className + " does not exist in " + packageName); 16534 } 16535 } 16536 switch (newState) { 16537 case COMPONENT_ENABLED_STATE_ENABLED: 16538 if (!pkgSetting.enableComponentLPw(className, userId)) { 16539 return; 16540 } 16541 break; 16542 case COMPONENT_ENABLED_STATE_DISABLED: 16543 if (!pkgSetting.disableComponentLPw(className, userId)) { 16544 return; 16545 } 16546 break; 16547 case COMPONENT_ENABLED_STATE_DEFAULT: 16548 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16549 return; 16550 } 16551 break; 16552 default: 16553 Slog.e(TAG, "Invalid new component state: " + newState); 16554 return; 16555 } 16556 } 16557 scheduleWritePackageRestrictionsLocked(userId); 16558 components = mPendingBroadcasts.get(userId, packageName); 16559 final boolean newPackage = components == null; 16560 if (newPackage) { 16561 components = new ArrayList<String>(); 16562 } 16563 if (!components.contains(componentName)) { 16564 components.add(componentName); 16565 } 16566 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16567 sendNow = true; 16568 // Purge entry from pending broadcast list if another one exists already 16569 // since we are sending one right away. 16570 mPendingBroadcasts.remove(userId, packageName); 16571 } else { 16572 if (newPackage) { 16573 mPendingBroadcasts.put(userId, packageName, components); 16574 } 16575 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16576 // Schedule a message 16577 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16578 } 16579 } 16580 } 16581 16582 long callingId = Binder.clearCallingIdentity(); 16583 try { 16584 if (sendNow) { 16585 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16586 sendPackageChangedBroadcast(packageName, 16587 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16588 } 16589 } finally { 16590 Binder.restoreCallingIdentity(callingId); 16591 } 16592 } 16593 16594 private void sendPackageChangedBroadcast(String packageName, 16595 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16596 if (DEBUG_INSTALL) 16597 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16598 + componentNames); 16599 Bundle extras = new Bundle(4); 16600 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16601 String nameList[] = new String[componentNames.size()]; 16602 componentNames.toArray(nameList); 16603 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16604 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16605 extras.putInt(Intent.EXTRA_UID, packageUid); 16606 // If this is not reporting a change of the overall package, then only send it 16607 // to registered receivers. We don't want to launch a swath of apps for every 16608 // little component state change. 16609 final int flags = !componentNames.contains(packageName) 16610 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16611 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16612 new int[] {UserHandle.getUserId(packageUid)}); 16613 } 16614 16615 @Override 16616 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16617 if (!sUserManager.exists(userId)) return; 16618 final int uid = Binder.getCallingUid(); 16619 final int permission = mContext.checkCallingOrSelfPermission( 16620 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16621 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16622 enforceCrossUserPermission(uid, userId, 16623 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16624 // writer 16625 synchronized (mPackages) { 16626 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16627 allowedByPermission, uid, userId)) { 16628 scheduleWritePackageRestrictionsLocked(userId); 16629 } 16630 } 16631 } 16632 16633 @Override 16634 public String getInstallerPackageName(String packageName) { 16635 // reader 16636 synchronized (mPackages) { 16637 return mSettings.getInstallerPackageNameLPr(packageName); 16638 } 16639 } 16640 16641 @Override 16642 public int getApplicationEnabledSetting(String packageName, int userId) { 16643 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16644 int uid = Binder.getCallingUid(); 16645 enforceCrossUserPermission(uid, userId, 16646 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16647 // reader 16648 synchronized (mPackages) { 16649 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16650 } 16651 } 16652 16653 @Override 16654 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16655 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16656 int uid = Binder.getCallingUid(); 16657 enforceCrossUserPermission(uid, userId, 16658 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16659 // reader 16660 synchronized (mPackages) { 16661 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16662 } 16663 } 16664 16665 @Override 16666 public void enterSafeMode() { 16667 enforceSystemOrRoot("Only the system can request entering safe mode"); 16668 16669 if (!mSystemReady) { 16670 mSafeMode = true; 16671 } 16672 } 16673 16674 @Override 16675 public void systemReady() { 16676 mSystemReady = true; 16677 16678 // Read the compatibilty setting when the system is ready. 16679 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16680 mContext.getContentResolver(), 16681 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16682 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16683 if (DEBUG_SETTINGS) { 16684 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16685 } 16686 16687 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16688 16689 synchronized (mPackages) { 16690 // Verify that all of the preferred activity components actually 16691 // exist. It is possible for applications to be updated and at 16692 // that point remove a previously declared activity component that 16693 // had been set as a preferred activity. We try to clean this up 16694 // the next time we encounter that preferred activity, but it is 16695 // possible for the user flow to never be able to return to that 16696 // situation so here we do a sanity check to make sure we haven't 16697 // left any junk around. 16698 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16699 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16700 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16701 removed.clear(); 16702 for (PreferredActivity pa : pir.filterSet()) { 16703 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16704 removed.add(pa); 16705 } 16706 } 16707 if (removed.size() > 0) { 16708 for (int r=0; r<removed.size(); r++) { 16709 PreferredActivity pa = removed.get(r); 16710 Slog.w(TAG, "Removing dangling preferred activity: " 16711 + pa.mPref.mComponent); 16712 pir.removeFilter(pa); 16713 } 16714 mSettings.writePackageRestrictionsLPr( 16715 mSettings.mPreferredActivities.keyAt(i)); 16716 } 16717 } 16718 16719 for (int userId : UserManagerService.getInstance().getUserIds()) { 16720 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16721 grantPermissionsUserIds = ArrayUtils.appendInt( 16722 grantPermissionsUserIds, userId); 16723 } 16724 } 16725 } 16726 sUserManager.systemReady(); 16727 16728 // If we upgraded grant all default permissions before kicking off. 16729 for (int userId : grantPermissionsUserIds) { 16730 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16731 } 16732 16733 // Kick off any messages waiting for system ready 16734 if (mPostSystemReadyMessages != null) { 16735 for (Message msg : mPostSystemReadyMessages) { 16736 msg.sendToTarget(); 16737 } 16738 mPostSystemReadyMessages = null; 16739 } 16740 16741 // Watch for external volumes that come and go over time 16742 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16743 storage.registerListener(mStorageListener); 16744 16745 mInstallerService.systemReady(); 16746 mPackageDexOptimizer.systemReady(); 16747 16748 MountServiceInternal mountServiceInternal = LocalServices.getService( 16749 MountServiceInternal.class); 16750 mountServiceInternal.addExternalStoragePolicy( 16751 new MountServiceInternal.ExternalStorageMountPolicy() { 16752 @Override 16753 public int getMountMode(int uid, String packageName) { 16754 if (Process.isIsolated(uid)) { 16755 return Zygote.MOUNT_EXTERNAL_NONE; 16756 } 16757 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16758 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16759 } 16760 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16761 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16762 } 16763 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16764 return Zygote.MOUNT_EXTERNAL_READ; 16765 } 16766 return Zygote.MOUNT_EXTERNAL_WRITE; 16767 } 16768 16769 @Override 16770 public boolean hasExternalStorage(int uid, String packageName) { 16771 return true; 16772 } 16773 }); 16774 } 16775 16776 @Override 16777 public boolean isSafeMode() { 16778 return mSafeMode; 16779 } 16780 16781 @Override 16782 public boolean hasSystemUidErrors() { 16783 return mHasSystemUidErrors; 16784 } 16785 16786 static String arrayToString(int[] array) { 16787 StringBuffer buf = new StringBuffer(128); 16788 buf.append('['); 16789 if (array != null) { 16790 for (int i=0; i<array.length; i++) { 16791 if (i > 0) buf.append(", "); 16792 buf.append(array[i]); 16793 } 16794 } 16795 buf.append(']'); 16796 return buf.toString(); 16797 } 16798 16799 static class DumpState { 16800 public static final int DUMP_LIBS = 1 << 0; 16801 public static final int DUMP_FEATURES = 1 << 1; 16802 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16803 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16804 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16805 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16806 public static final int DUMP_PERMISSIONS = 1 << 6; 16807 public static final int DUMP_PACKAGES = 1 << 7; 16808 public static final int DUMP_SHARED_USERS = 1 << 8; 16809 public static final int DUMP_MESSAGES = 1 << 9; 16810 public static final int DUMP_PROVIDERS = 1 << 10; 16811 public static final int DUMP_VERIFIERS = 1 << 11; 16812 public static final int DUMP_PREFERRED = 1 << 12; 16813 public static final int DUMP_PREFERRED_XML = 1 << 13; 16814 public static final int DUMP_KEYSETS = 1 << 14; 16815 public static final int DUMP_VERSION = 1 << 15; 16816 public static final int DUMP_INSTALLS = 1 << 16; 16817 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16818 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16819 16820 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16821 16822 private int mTypes; 16823 16824 private int mOptions; 16825 16826 private boolean mTitlePrinted; 16827 16828 private SharedUserSetting mSharedUser; 16829 16830 public boolean isDumping(int type) { 16831 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16832 return true; 16833 } 16834 16835 return (mTypes & type) != 0; 16836 } 16837 16838 public void setDump(int type) { 16839 mTypes |= type; 16840 } 16841 16842 public boolean isOptionEnabled(int option) { 16843 return (mOptions & option) != 0; 16844 } 16845 16846 public void setOptionEnabled(int option) { 16847 mOptions |= option; 16848 } 16849 16850 public boolean onTitlePrinted() { 16851 final boolean printed = mTitlePrinted; 16852 mTitlePrinted = true; 16853 return printed; 16854 } 16855 16856 public boolean getTitlePrinted() { 16857 return mTitlePrinted; 16858 } 16859 16860 public void setTitlePrinted(boolean enabled) { 16861 mTitlePrinted = enabled; 16862 } 16863 16864 public SharedUserSetting getSharedUser() { 16865 return mSharedUser; 16866 } 16867 16868 public void setSharedUser(SharedUserSetting user) { 16869 mSharedUser = user; 16870 } 16871 } 16872 16873 @Override 16874 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16875 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16876 (new PackageManagerShellCommand(this)).exec( 16877 this, in, out, err, args, resultReceiver); 16878 } 16879 16880 @Override 16881 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16882 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16883 != PackageManager.PERMISSION_GRANTED) { 16884 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16885 + Binder.getCallingPid() 16886 + ", uid=" + Binder.getCallingUid() 16887 + " without permission " 16888 + android.Manifest.permission.DUMP); 16889 return; 16890 } 16891 16892 DumpState dumpState = new DumpState(); 16893 boolean fullPreferred = false; 16894 boolean checkin = false; 16895 16896 String packageName = null; 16897 ArraySet<String> permissionNames = null; 16898 16899 int opti = 0; 16900 while (opti < args.length) { 16901 String opt = args[opti]; 16902 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16903 break; 16904 } 16905 opti++; 16906 16907 if ("-a".equals(opt)) { 16908 // Right now we only know how to print all. 16909 } else if ("-h".equals(opt)) { 16910 pw.println("Package manager dump options:"); 16911 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16912 pw.println(" --checkin: dump for a checkin"); 16913 pw.println(" -f: print details of intent filters"); 16914 pw.println(" -h: print this help"); 16915 pw.println(" cmd may be one of:"); 16916 pw.println(" l[ibraries]: list known shared libraries"); 16917 pw.println(" f[eatures]: list device features"); 16918 pw.println(" k[eysets]: print known keysets"); 16919 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16920 pw.println(" perm[issions]: dump permissions"); 16921 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16922 pw.println(" pref[erred]: print preferred package settings"); 16923 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16924 pw.println(" prov[iders]: dump content providers"); 16925 pw.println(" p[ackages]: dump installed packages"); 16926 pw.println(" s[hared-users]: dump shared user IDs"); 16927 pw.println(" m[essages]: print collected runtime messages"); 16928 pw.println(" v[erifiers]: print package verifier info"); 16929 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16930 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16931 pw.println(" version: print database version info"); 16932 pw.println(" write: write current settings now"); 16933 pw.println(" installs: details about install sessions"); 16934 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16935 pw.println(" <package.name>: info about given package"); 16936 return; 16937 } else if ("--checkin".equals(opt)) { 16938 checkin = true; 16939 } else if ("-f".equals(opt)) { 16940 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16941 } else { 16942 pw.println("Unknown argument: " + opt + "; use -h for help"); 16943 } 16944 } 16945 16946 // Is the caller requesting to dump a particular piece of data? 16947 if (opti < args.length) { 16948 String cmd = args[opti]; 16949 opti++; 16950 // Is this a package name? 16951 if ("android".equals(cmd) || cmd.contains(".")) { 16952 packageName = cmd; 16953 // When dumping a single package, we always dump all of its 16954 // filter information since the amount of data will be reasonable. 16955 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16956 } else if ("check-permission".equals(cmd)) { 16957 if (opti >= args.length) { 16958 pw.println("Error: check-permission missing permission argument"); 16959 return; 16960 } 16961 String perm = args[opti]; 16962 opti++; 16963 if (opti >= args.length) { 16964 pw.println("Error: check-permission missing package argument"); 16965 return; 16966 } 16967 String pkg = args[opti]; 16968 opti++; 16969 int user = UserHandle.getUserId(Binder.getCallingUid()); 16970 if (opti < args.length) { 16971 try { 16972 user = Integer.parseInt(args[opti]); 16973 } catch (NumberFormatException e) { 16974 pw.println("Error: check-permission user argument is not a number: " 16975 + args[opti]); 16976 return; 16977 } 16978 } 16979 pw.println(checkPermission(perm, pkg, user)); 16980 return; 16981 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16982 dumpState.setDump(DumpState.DUMP_LIBS); 16983 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16984 dumpState.setDump(DumpState.DUMP_FEATURES); 16985 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16986 if (opti >= args.length) { 16987 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16988 | DumpState.DUMP_SERVICE_RESOLVERS 16989 | DumpState.DUMP_RECEIVER_RESOLVERS 16990 | DumpState.DUMP_CONTENT_RESOLVERS); 16991 } else { 16992 while (opti < args.length) { 16993 String name = args[opti]; 16994 if ("a".equals(name) || "activity".equals(name)) { 16995 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16996 } else if ("s".equals(name) || "service".equals(name)) { 16997 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16998 } else if ("r".equals(name) || "receiver".equals(name)) { 16999 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17000 } else if ("c".equals(name) || "content".equals(name)) { 17001 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17002 } else { 17003 pw.println("Error: unknown resolver table type: " + name); 17004 return; 17005 } 17006 opti++; 17007 } 17008 } 17009 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17010 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17011 } else if ("permission".equals(cmd)) { 17012 if (opti >= args.length) { 17013 pw.println("Error: permission requires permission name"); 17014 return; 17015 } 17016 permissionNames = new ArraySet<>(); 17017 while (opti < args.length) { 17018 permissionNames.add(args[opti]); 17019 opti++; 17020 } 17021 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17022 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17023 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17024 dumpState.setDump(DumpState.DUMP_PREFERRED); 17025 } else if ("preferred-xml".equals(cmd)) { 17026 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17027 if (opti < args.length && "--full".equals(args[opti])) { 17028 fullPreferred = true; 17029 opti++; 17030 } 17031 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17032 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17033 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17034 dumpState.setDump(DumpState.DUMP_PACKAGES); 17035 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17036 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17037 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17038 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17039 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17040 dumpState.setDump(DumpState.DUMP_MESSAGES); 17041 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17042 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17043 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17044 || "intent-filter-verifiers".equals(cmd)) { 17045 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17046 } else if ("version".equals(cmd)) { 17047 dumpState.setDump(DumpState.DUMP_VERSION); 17048 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17049 dumpState.setDump(DumpState.DUMP_KEYSETS); 17050 } else if ("installs".equals(cmd)) { 17051 dumpState.setDump(DumpState.DUMP_INSTALLS); 17052 } else if ("write".equals(cmd)) { 17053 synchronized (mPackages) { 17054 mSettings.writeLPr(); 17055 pw.println("Settings written."); 17056 return; 17057 } 17058 } 17059 } 17060 17061 if (checkin) { 17062 pw.println("vers,1"); 17063 } 17064 17065 // reader 17066 synchronized (mPackages) { 17067 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17068 if (!checkin) { 17069 if (dumpState.onTitlePrinted()) 17070 pw.println(); 17071 pw.println("Database versions:"); 17072 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17073 } 17074 } 17075 17076 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17077 if (!checkin) { 17078 if (dumpState.onTitlePrinted()) 17079 pw.println(); 17080 pw.println("Verifiers:"); 17081 pw.print(" Required: "); 17082 pw.print(mRequiredVerifierPackage); 17083 pw.print(" (uid="); 17084 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17085 UserHandle.USER_SYSTEM)); 17086 pw.println(")"); 17087 } else if (mRequiredVerifierPackage != null) { 17088 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17089 pw.print(","); 17090 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17091 UserHandle.USER_SYSTEM)); 17092 } 17093 } 17094 17095 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17096 packageName == null) { 17097 if (mIntentFilterVerifierComponent != null) { 17098 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17099 if (!checkin) { 17100 if (dumpState.onTitlePrinted()) 17101 pw.println(); 17102 pw.println("Intent Filter Verifier:"); 17103 pw.print(" Using: "); 17104 pw.print(verifierPackageName); 17105 pw.print(" (uid="); 17106 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17107 UserHandle.USER_SYSTEM)); 17108 pw.println(")"); 17109 } else if (verifierPackageName != null) { 17110 pw.print("ifv,"); pw.print(verifierPackageName); 17111 pw.print(","); 17112 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17113 UserHandle.USER_SYSTEM)); 17114 } 17115 } else { 17116 pw.println(); 17117 pw.println("No Intent Filter Verifier available!"); 17118 } 17119 } 17120 17121 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17122 boolean printedHeader = false; 17123 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17124 while (it.hasNext()) { 17125 String name = it.next(); 17126 SharedLibraryEntry ent = mSharedLibraries.get(name); 17127 if (!checkin) { 17128 if (!printedHeader) { 17129 if (dumpState.onTitlePrinted()) 17130 pw.println(); 17131 pw.println("Libraries:"); 17132 printedHeader = true; 17133 } 17134 pw.print(" "); 17135 } else { 17136 pw.print("lib,"); 17137 } 17138 pw.print(name); 17139 if (!checkin) { 17140 pw.print(" -> "); 17141 } 17142 if (ent.path != null) { 17143 if (!checkin) { 17144 pw.print("(jar) "); 17145 pw.print(ent.path); 17146 } else { 17147 pw.print(",jar,"); 17148 pw.print(ent.path); 17149 } 17150 } else { 17151 if (!checkin) { 17152 pw.print("(apk) "); 17153 pw.print(ent.apk); 17154 } else { 17155 pw.print(",apk,"); 17156 pw.print(ent.apk); 17157 } 17158 } 17159 pw.println(); 17160 } 17161 } 17162 17163 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17164 if (dumpState.onTitlePrinted()) 17165 pw.println(); 17166 if (!checkin) { 17167 pw.println("Features:"); 17168 } 17169 17170 for (FeatureInfo feat : mAvailableFeatures.values()) { 17171 if (checkin) { 17172 pw.print("feat,"); 17173 pw.print(feat.name); 17174 pw.print(","); 17175 pw.println(feat.version); 17176 } else { 17177 pw.print(" "); 17178 pw.print(feat.name); 17179 if (feat.version > 0) { 17180 pw.print(" version="); 17181 pw.print(feat.version); 17182 } 17183 pw.println(); 17184 } 17185 } 17186 } 17187 17188 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17189 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17190 : "Activity Resolver Table:", " ", packageName, 17191 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17192 dumpState.setTitlePrinted(true); 17193 } 17194 } 17195 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17196 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17197 : "Receiver Resolver Table:", " ", packageName, 17198 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17199 dumpState.setTitlePrinted(true); 17200 } 17201 } 17202 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17203 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17204 : "Service Resolver Table:", " ", packageName, 17205 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17206 dumpState.setTitlePrinted(true); 17207 } 17208 } 17209 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17210 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17211 : "Provider Resolver Table:", " ", packageName, 17212 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17213 dumpState.setTitlePrinted(true); 17214 } 17215 } 17216 17217 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17218 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17219 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17220 int user = mSettings.mPreferredActivities.keyAt(i); 17221 if (pir.dump(pw, 17222 dumpState.getTitlePrinted() 17223 ? "\nPreferred Activities User " + user + ":" 17224 : "Preferred Activities User " + user + ":", " ", 17225 packageName, true, false)) { 17226 dumpState.setTitlePrinted(true); 17227 } 17228 } 17229 } 17230 17231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17232 pw.flush(); 17233 FileOutputStream fout = new FileOutputStream(fd); 17234 BufferedOutputStream str = new BufferedOutputStream(fout); 17235 XmlSerializer serializer = new FastXmlSerializer(); 17236 try { 17237 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17238 serializer.startDocument(null, true); 17239 serializer.setFeature( 17240 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17241 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17242 serializer.endDocument(); 17243 serializer.flush(); 17244 } catch (IllegalArgumentException e) { 17245 pw.println("Failed writing: " + e); 17246 } catch (IllegalStateException e) { 17247 pw.println("Failed writing: " + e); 17248 } catch (IOException e) { 17249 pw.println("Failed writing: " + e); 17250 } 17251 } 17252 17253 if (!checkin 17254 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17255 && packageName == null) { 17256 pw.println(); 17257 int count = mSettings.mPackages.size(); 17258 if (count == 0) { 17259 pw.println("No applications!"); 17260 pw.println(); 17261 } else { 17262 final String prefix = " "; 17263 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17264 if (allPackageSettings.size() == 0) { 17265 pw.println("No domain preferred apps!"); 17266 pw.println(); 17267 } else { 17268 pw.println("App verification status:"); 17269 pw.println(); 17270 count = 0; 17271 for (PackageSetting ps : allPackageSettings) { 17272 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17273 if (ivi == null || ivi.getPackageName() == null) continue; 17274 pw.println(prefix + "Package: " + ivi.getPackageName()); 17275 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17276 pw.println(prefix + "Status: " + ivi.getStatusString()); 17277 pw.println(); 17278 count++; 17279 } 17280 if (count == 0) { 17281 pw.println(prefix + "No app verification established."); 17282 pw.println(); 17283 } 17284 for (int userId : sUserManager.getUserIds()) { 17285 pw.println("App linkages for user " + userId + ":"); 17286 pw.println(); 17287 count = 0; 17288 for (PackageSetting ps : allPackageSettings) { 17289 final long status = ps.getDomainVerificationStatusForUser(userId); 17290 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17291 continue; 17292 } 17293 pw.println(prefix + "Package: " + ps.name); 17294 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17295 String statusStr = IntentFilterVerificationInfo. 17296 getStatusStringFromValue(status); 17297 pw.println(prefix + "Status: " + statusStr); 17298 pw.println(); 17299 count++; 17300 } 17301 if (count == 0) { 17302 pw.println(prefix + "No configured app linkages."); 17303 pw.println(); 17304 } 17305 } 17306 } 17307 } 17308 } 17309 17310 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17311 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17312 if (packageName == null && permissionNames == null) { 17313 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17314 if (iperm == 0) { 17315 if (dumpState.onTitlePrinted()) 17316 pw.println(); 17317 pw.println("AppOp Permissions:"); 17318 } 17319 pw.print(" AppOp Permission "); 17320 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17321 pw.println(":"); 17322 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17323 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17324 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17325 } 17326 } 17327 } 17328 } 17329 17330 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17331 boolean printedSomething = false; 17332 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17333 if (packageName != null && !packageName.equals(p.info.packageName)) { 17334 continue; 17335 } 17336 if (!printedSomething) { 17337 if (dumpState.onTitlePrinted()) 17338 pw.println(); 17339 pw.println("Registered ContentProviders:"); 17340 printedSomething = true; 17341 } 17342 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17343 pw.print(" "); pw.println(p.toString()); 17344 } 17345 printedSomething = false; 17346 for (Map.Entry<String, PackageParser.Provider> entry : 17347 mProvidersByAuthority.entrySet()) { 17348 PackageParser.Provider p = entry.getValue(); 17349 if (packageName != null && !packageName.equals(p.info.packageName)) { 17350 continue; 17351 } 17352 if (!printedSomething) { 17353 if (dumpState.onTitlePrinted()) 17354 pw.println(); 17355 pw.println("ContentProvider Authorities:"); 17356 printedSomething = true; 17357 } 17358 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17359 pw.print(" "); pw.println(p.toString()); 17360 if (p.info != null && p.info.applicationInfo != null) { 17361 final String appInfo = p.info.applicationInfo.toString(); 17362 pw.print(" applicationInfo="); pw.println(appInfo); 17363 } 17364 } 17365 } 17366 17367 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17368 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17369 } 17370 17371 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17372 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17373 } 17374 17375 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17376 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17377 } 17378 17379 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17380 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17381 } 17382 17383 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17384 // XXX should handle packageName != null by dumping only install data that 17385 // the given package is involved with. 17386 if (dumpState.onTitlePrinted()) pw.println(); 17387 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17388 } 17389 17390 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17391 if (dumpState.onTitlePrinted()) pw.println(); 17392 mSettings.dumpReadMessagesLPr(pw, dumpState); 17393 17394 pw.println(); 17395 pw.println("Package warning messages:"); 17396 BufferedReader in = null; 17397 String line = null; 17398 try { 17399 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17400 while ((line = in.readLine()) != null) { 17401 if (line.contains("ignored: updated version")) continue; 17402 pw.println(line); 17403 } 17404 } catch (IOException ignored) { 17405 } finally { 17406 IoUtils.closeQuietly(in); 17407 } 17408 } 17409 17410 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17411 BufferedReader in = null; 17412 String line = null; 17413 try { 17414 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17415 while ((line = in.readLine()) != null) { 17416 if (line.contains("ignored: updated version")) continue; 17417 pw.print("msg,"); 17418 pw.println(line); 17419 } 17420 } catch (IOException ignored) { 17421 } finally { 17422 IoUtils.closeQuietly(in); 17423 } 17424 } 17425 } 17426 } 17427 17428 private String dumpDomainString(String packageName) { 17429 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17430 .getList(); 17431 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17432 17433 ArraySet<String> result = new ArraySet<>(); 17434 if (iviList.size() > 0) { 17435 for (IntentFilterVerificationInfo ivi : iviList) { 17436 for (String host : ivi.getDomains()) { 17437 result.add(host); 17438 } 17439 } 17440 } 17441 if (filters != null && filters.size() > 0) { 17442 for (IntentFilter filter : filters) { 17443 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17444 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17445 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17446 result.addAll(filter.getHostsList()); 17447 } 17448 } 17449 } 17450 17451 StringBuilder sb = new StringBuilder(result.size() * 16); 17452 for (String domain : result) { 17453 if (sb.length() > 0) sb.append(" "); 17454 sb.append(domain); 17455 } 17456 return sb.toString(); 17457 } 17458 17459 // ------- apps on sdcard specific code ------- 17460 static final boolean DEBUG_SD_INSTALL = false; 17461 17462 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17463 17464 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17465 17466 private boolean mMediaMounted = false; 17467 17468 static String getEncryptKey() { 17469 try { 17470 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17471 SD_ENCRYPTION_KEYSTORE_NAME); 17472 if (sdEncKey == null) { 17473 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17474 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17475 if (sdEncKey == null) { 17476 Slog.e(TAG, "Failed to create encryption keys"); 17477 return null; 17478 } 17479 } 17480 return sdEncKey; 17481 } catch (NoSuchAlgorithmException nsae) { 17482 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17483 return null; 17484 } catch (IOException ioe) { 17485 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17486 return null; 17487 } 17488 } 17489 17490 /* 17491 * Update media status on PackageManager. 17492 */ 17493 @Override 17494 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17495 int callingUid = Binder.getCallingUid(); 17496 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17497 throw new SecurityException("Media status can only be updated by the system"); 17498 } 17499 // reader; this apparently protects mMediaMounted, but should probably 17500 // be a different lock in that case. 17501 synchronized (mPackages) { 17502 Log.i(TAG, "Updating external media status from " 17503 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17504 + (mediaStatus ? "mounted" : "unmounted")); 17505 if (DEBUG_SD_INSTALL) 17506 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17507 + ", mMediaMounted=" + mMediaMounted); 17508 if (mediaStatus == mMediaMounted) { 17509 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17510 : 0, -1); 17511 mHandler.sendMessage(msg); 17512 return; 17513 } 17514 mMediaMounted = mediaStatus; 17515 } 17516 // Queue up an async operation since the package installation may take a 17517 // little while. 17518 mHandler.post(new Runnable() { 17519 public void run() { 17520 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17521 } 17522 }); 17523 } 17524 17525 /** 17526 * Called by MountService when the initial ASECs to scan are available. 17527 * Should block until all the ASEC containers are finished being scanned. 17528 */ 17529 public void scanAvailableAsecs() { 17530 updateExternalMediaStatusInner(true, false, false); 17531 } 17532 17533 /* 17534 * Collect information of applications on external media, map them against 17535 * existing containers and update information based on current mount status. 17536 * Please note that we always have to report status if reportStatus has been 17537 * set to true especially when unloading packages. 17538 */ 17539 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17540 boolean externalStorage) { 17541 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17542 int[] uidArr = EmptyArray.INT; 17543 17544 final String[] list = PackageHelper.getSecureContainerList(); 17545 if (ArrayUtils.isEmpty(list)) { 17546 Log.i(TAG, "No secure containers found"); 17547 } else { 17548 // Process list of secure containers and categorize them 17549 // as active or stale based on their package internal state. 17550 17551 // reader 17552 synchronized (mPackages) { 17553 for (String cid : list) { 17554 // Leave stages untouched for now; installer service owns them 17555 if (PackageInstallerService.isStageName(cid)) continue; 17556 17557 if (DEBUG_SD_INSTALL) 17558 Log.i(TAG, "Processing container " + cid); 17559 String pkgName = getAsecPackageName(cid); 17560 if (pkgName == null) { 17561 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17562 continue; 17563 } 17564 if (DEBUG_SD_INSTALL) 17565 Log.i(TAG, "Looking for pkg : " + pkgName); 17566 17567 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17568 if (ps == null) { 17569 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17570 continue; 17571 } 17572 17573 /* 17574 * Skip packages that are not external if we're unmounting 17575 * external storage. 17576 */ 17577 if (externalStorage && !isMounted && !isExternal(ps)) { 17578 continue; 17579 } 17580 17581 final AsecInstallArgs args = new AsecInstallArgs(cid, 17582 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17583 // The package status is changed only if the code path 17584 // matches between settings and the container id. 17585 if (ps.codePathString != null 17586 && ps.codePathString.startsWith(args.getCodePath())) { 17587 if (DEBUG_SD_INSTALL) { 17588 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17589 + " at code path: " + ps.codePathString); 17590 } 17591 17592 // We do have a valid package installed on sdcard 17593 processCids.put(args, ps.codePathString); 17594 final int uid = ps.appId; 17595 if (uid != -1) { 17596 uidArr = ArrayUtils.appendInt(uidArr, uid); 17597 } 17598 } else { 17599 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17600 + ps.codePathString); 17601 } 17602 } 17603 } 17604 17605 Arrays.sort(uidArr); 17606 } 17607 17608 // Process packages with valid entries. 17609 if (isMounted) { 17610 if (DEBUG_SD_INSTALL) 17611 Log.i(TAG, "Loading packages"); 17612 loadMediaPackages(processCids, uidArr, externalStorage); 17613 startCleaningPackages(); 17614 mInstallerService.onSecureContainersAvailable(); 17615 } else { 17616 if (DEBUG_SD_INSTALL) 17617 Log.i(TAG, "Unloading packages"); 17618 unloadMediaPackages(processCids, uidArr, reportStatus); 17619 } 17620 } 17621 17622 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17623 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17624 final int size = infos.size(); 17625 final String[] packageNames = new String[size]; 17626 final int[] packageUids = new int[size]; 17627 for (int i = 0; i < size; i++) { 17628 final ApplicationInfo info = infos.get(i); 17629 packageNames[i] = info.packageName; 17630 packageUids[i] = info.uid; 17631 } 17632 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17633 finishedReceiver); 17634 } 17635 17636 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17637 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17638 sendResourcesChangedBroadcast(mediaStatus, replacing, 17639 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17640 } 17641 17642 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17643 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17644 int size = pkgList.length; 17645 if (size > 0) { 17646 // Send broadcasts here 17647 Bundle extras = new Bundle(); 17648 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17649 if (uidArr != null) { 17650 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17651 } 17652 if (replacing) { 17653 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17654 } 17655 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17656 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17657 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17658 } 17659 } 17660 17661 /* 17662 * Look at potentially valid container ids from processCids If package 17663 * information doesn't match the one on record or package scanning fails, 17664 * the cid is added to list of removeCids. We currently don't delete stale 17665 * containers. 17666 */ 17667 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17668 boolean externalStorage) { 17669 ArrayList<String> pkgList = new ArrayList<String>(); 17670 Set<AsecInstallArgs> keys = processCids.keySet(); 17671 17672 for (AsecInstallArgs args : keys) { 17673 String codePath = processCids.get(args); 17674 if (DEBUG_SD_INSTALL) 17675 Log.i(TAG, "Loading container : " + args.cid); 17676 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17677 try { 17678 // Make sure there are no container errors first. 17679 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17680 Slog.e(TAG, "Failed to mount cid : " + args.cid 17681 + " when installing from sdcard"); 17682 continue; 17683 } 17684 // Check code path here. 17685 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17686 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17687 + " does not match one in settings " + codePath); 17688 continue; 17689 } 17690 // Parse package 17691 int parseFlags = mDefParseFlags; 17692 if (args.isExternalAsec()) { 17693 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17694 } 17695 if (args.isFwdLocked()) { 17696 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17697 } 17698 17699 synchronized (mInstallLock) { 17700 PackageParser.Package pkg = null; 17701 try { 17702 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17703 } catch (PackageManagerException e) { 17704 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17705 } 17706 // Scan the package 17707 if (pkg != null) { 17708 /* 17709 * TODO why is the lock being held? doPostInstall is 17710 * called in other places without the lock. This needs 17711 * to be straightened out. 17712 */ 17713 // writer 17714 synchronized (mPackages) { 17715 retCode = PackageManager.INSTALL_SUCCEEDED; 17716 pkgList.add(pkg.packageName); 17717 // Post process args 17718 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17719 pkg.applicationInfo.uid); 17720 } 17721 } else { 17722 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17723 } 17724 } 17725 17726 } finally { 17727 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17728 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17729 } 17730 } 17731 } 17732 // writer 17733 synchronized (mPackages) { 17734 // If the platform SDK has changed since the last time we booted, 17735 // we need to re-grant app permission to catch any new ones that 17736 // appear. This is really a hack, and means that apps can in some 17737 // cases get permissions that the user didn't initially explicitly 17738 // allow... it would be nice to have some better way to handle 17739 // this situation. 17740 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17741 : mSettings.getInternalVersion(); 17742 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17743 : StorageManager.UUID_PRIVATE_INTERNAL; 17744 17745 int updateFlags = UPDATE_PERMISSIONS_ALL; 17746 if (ver.sdkVersion != mSdkVersion) { 17747 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17748 + mSdkVersion + "; regranting permissions for external"); 17749 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17750 } 17751 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17752 17753 // Yay, everything is now upgraded 17754 ver.forceCurrent(); 17755 17756 // can downgrade to reader 17757 // Persist settings 17758 mSettings.writeLPr(); 17759 } 17760 // Send a broadcast to let everyone know we are done processing 17761 if (pkgList.size() > 0) { 17762 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17763 } 17764 } 17765 17766 /* 17767 * Utility method to unload a list of specified containers 17768 */ 17769 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17770 // Just unmount all valid containers. 17771 for (AsecInstallArgs arg : cidArgs) { 17772 synchronized (mInstallLock) { 17773 arg.doPostDeleteLI(false); 17774 } 17775 } 17776 } 17777 17778 /* 17779 * Unload packages mounted on external media. This involves deleting package 17780 * data from internal structures, sending broadcasts about disabled packages, 17781 * gc'ing to free up references, unmounting all secure containers 17782 * corresponding to packages on external media, and posting a 17783 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17784 * that we always have to post this message if status has been requested no 17785 * matter what. 17786 */ 17787 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17788 final boolean reportStatus) { 17789 if (DEBUG_SD_INSTALL) 17790 Log.i(TAG, "unloading media packages"); 17791 ArrayList<String> pkgList = new ArrayList<String>(); 17792 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17793 final Set<AsecInstallArgs> keys = processCids.keySet(); 17794 for (AsecInstallArgs args : keys) { 17795 String pkgName = args.getPackageName(); 17796 if (DEBUG_SD_INSTALL) 17797 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17798 // Delete package internally 17799 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17800 synchronized (mInstallLock) { 17801 boolean res = deletePackageLI(pkgName, null, false, null, 17802 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17803 if (res) { 17804 pkgList.add(pkgName); 17805 } else { 17806 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17807 failedList.add(args); 17808 } 17809 } 17810 } 17811 17812 // reader 17813 synchronized (mPackages) { 17814 // We didn't update the settings after removing each package; 17815 // write them now for all packages. 17816 mSettings.writeLPr(); 17817 } 17818 17819 // We have to absolutely send UPDATED_MEDIA_STATUS only 17820 // after confirming that all the receivers processed the ordered 17821 // broadcast when packages get disabled, force a gc to clean things up. 17822 // and unload all the containers. 17823 if (pkgList.size() > 0) { 17824 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17825 new IIntentReceiver.Stub() { 17826 public void performReceive(Intent intent, int resultCode, String data, 17827 Bundle extras, boolean ordered, boolean sticky, 17828 int sendingUser) throws RemoteException { 17829 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17830 reportStatus ? 1 : 0, 1, keys); 17831 mHandler.sendMessage(msg); 17832 } 17833 }); 17834 } else { 17835 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17836 keys); 17837 mHandler.sendMessage(msg); 17838 } 17839 } 17840 17841 private void loadPrivatePackages(final VolumeInfo vol) { 17842 mHandler.post(new Runnable() { 17843 @Override 17844 public void run() { 17845 loadPrivatePackagesInner(vol); 17846 } 17847 }); 17848 } 17849 17850 private void loadPrivatePackagesInner(VolumeInfo vol) { 17851 final String volumeUuid = vol.fsUuid; 17852 if (TextUtils.isEmpty(volumeUuid)) { 17853 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17854 return; 17855 } 17856 17857 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17858 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17859 17860 final VersionInfo ver; 17861 final List<PackageSetting> packages; 17862 synchronized (mPackages) { 17863 ver = mSettings.findOrCreateVersion(volumeUuid); 17864 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17865 } 17866 17867 // TODO: introduce a new concept similar to "frozen" to prevent these 17868 // apps from being launched until after data has been fully reconciled 17869 for (PackageSetting ps : packages) { 17870 synchronized (mInstallLock) { 17871 final PackageParser.Package pkg; 17872 try { 17873 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17874 loaded.add(pkg.applicationInfo); 17875 17876 } catch (PackageManagerException e) { 17877 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17878 } 17879 17880 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17881 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17882 } 17883 } 17884 } 17885 17886 // Reconcile app data for all started/unlocked users 17887 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17888 final UserManager um = mContext.getSystemService(UserManager.class); 17889 for (UserInfo user : um.getUsers()) { 17890 final int flags; 17891 if (um.isUserUnlocked(user.id)) { 17892 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17893 } else if (um.isUserRunning(user.id)) { 17894 flags = StorageManager.FLAG_STORAGE_DE; 17895 } else { 17896 continue; 17897 } 17898 17899 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17900 reconcileAppsData(volumeUuid, user.id, flags); 17901 } 17902 17903 synchronized (mPackages) { 17904 int updateFlags = UPDATE_PERMISSIONS_ALL; 17905 if (ver.sdkVersion != mSdkVersion) { 17906 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17907 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17908 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17909 } 17910 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17911 17912 // Yay, everything is now upgraded 17913 ver.forceCurrent(); 17914 17915 mSettings.writeLPr(); 17916 } 17917 17918 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17919 sendResourcesChangedBroadcast(true, false, loaded, null); 17920 } 17921 17922 private void unloadPrivatePackages(final VolumeInfo vol) { 17923 mHandler.post(new Runnable() { 17924 @Override 17925 public void run() { 17926 unloadPrivatePackagesInner(vol); 17927 } 17928 }); 17929 } 17930 17931 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17932 final String volumeUuid = vol.fsUuid; 17933 if (TextUtils.isEmpty(volumeUuid)) { 17934 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17935 return; 17936 } 17937 17938 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17939 synchronized (mInstallLock) { 17940 synchronized (mPackages) { 17941 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17942 for (PackageSetting ps : packages) { 17943 if (ps.pkg == null) continue; 17944 17945 final ApplicationInfo info = ps.pkg.applicationInfo; 17946 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17947 if (deletePackageLI(ps.name, null, false, null, 17948 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17949 unloaded.add(info); 17950 } else { 17951 Slog.w(TAG, "Failed to unload " + ps.codePath); 17952 } 17953 } 17954 17955 mSettings.writeLPr(); 17956 } 17957 } 17958 17959 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17960 sendResourcesChangedBroadcast(false, false, unloaded, null); 17961 } 17962 17963 /** 17964 * Examine all users present on given mounted volume, and destroy data 17965 * belonging to users that are no longer valid, or whose user ID has been 17966 * recycled. 17967 */ 17968 private void reconcileUsers(String volumeUuid) { 17969 // TODO: also reconcile DE directories 17970 final File[] files = FileUtils 17971 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17972 for (File file : files) { 17973 if (!file.isDirectory()) continue; 17974 17975 final int userId; 17976 final UserInfo info; 17977 try { 17978 userId = Integer.parseInt(file.getName()); 17979 info = sUserManager.getUserInfo(userId); 17980 } catch (NumberFormatException e) { 17981 Slog.w(TAG, "Invalid user directory " + file); 17982 continue; 17983 } 17984 17985 boolean destroyUser = false; 17986 if (info == null) { 17987 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17988 + " because no matching user was found"); 17989 destroyUser = true; 17990 } else { 17991 try { 17992 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17993 } catch (IOException e) { 17994 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17995 + " because we failed to enforce serial number: " + e); 17996 destroyUser = true; 17997 } 17998 } 17999 18000 if (destroyUser) { 18001 synchronized (mInstallLock) { 18002 try { 18003 mInstaller.removeUserDataDirs(volumeUuid, userId); 18004 } catch (InstallerException e) { 18005 Slog.w(TAG, "Failed to clean up user dirs", e); 18006 } 18007 } 18008 } 18009 } 18010 } 18011 18012 private void assertPackageKnown(String volumeUuid, String packageName) 18013 throws PackageManagerException { 18014 synchronized (mPackages) { 18015 final PackageSetting ps = mSettings.mPackages.get(packageName); 18016 if (ps == null) { 18017 throw new PackageManagerException("Package " + packageName + " is unknown"); 18018 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18019 throw new PackageManagerException( 18020 "Package " + packageName + " found on unknown volume " + volumeUuid 18021 + "; expected volume " + ps.volumeUuid); 18022 } 18023 } 18024 } 18025 18026 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18027 throws PackageManagerException { 18028 synchronized (mPackages) { 18029 final PackageSetting ps = mSettings.mPackages.get(packageName); 18030 if (ps == null) { 18031 throw new PackageManagerException("Package " + packageName + " is unknown"); 18032 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18033 throw new PackageManagerException( 18034 "Package " + packageName + " found on unknown volume " + volumeUuid 18035 + "; expected volume " + ps.volumeUuid); 18036 } else if (!ps.getInstalled(userId)) { 18037 throw new PackageManagerException( 18038 "Package " + packageName + " not installed for user " + userId); 18039 } 18040 } 18041 } 18042 18043 /** 18044 * Examine all apps present on given mounted volume, and destroy apps that 18045 * aren't expected, either due to uninstallation or reinstallation on 18046 * another volume. 18047 */ 18048 private void reconcileApps(String volumeUuid) { 18049 final File[] files = FileUtils 18050 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18051 for (File file : files) { 18052 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18053 && !PackageInstallerService.isStageName(file.getName()); 18054 if (!isPackage) { 18055 // Ignore entries which are not packages 18056 continue; 18057 } 18058 18059 try { 18060 final PackageLite pkg = PackageParser.parsePackageLite(file, 18061 PackageParser.PARSE_MUST_BE_APK); 18062 assertPackageKnown(volumeUuid, pkg.packageName); 18063 18064 } catch (PackageParserException | PackageManagerException e) { 18065 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18066 synchronized (mInstallLock) { 18067 removeCodePathLI(file); 18068 } 18069 } 18070 } 18071 } 18072 18073 /** 18074 * Reconcile all app data for the given user. 18075 * <p> 18076 * Verifies that directories exist and that ownership and labeling is 18077 * correct for all installed apps on all mounted volumes. 18078 */ 18079 void reconcileAppsData(int userId, int flags) { 18080 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18081 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18082 final String volumeUuid = vol.getFsUuid(); 18083 reconcileAppsData(volumeUuid, userId, flags); 18084 } 18085 } 18086 18087 /** 18088 * Reconcile all app data on given mounted volume. 18089 * <p> 18090 * Destroys app data that isn't expected, either due to uninstallation or 18091 * reinstallation on another volume. 18092 * <p> 18093 * Verifies that directories exist and that ownership and labeling is 18094 * correct for all installed apps. 18095 */ 18096 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18097 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18098 + Integer.toHexString(flags)); 18099 18100 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18101 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18102 18103 boolean restoreconNeeded = false; 18104 18105 // First look for stale data that doesn't belong, and check if things 18106 // have changed since we did our last restorecon 18107 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18108 if (!isUserKeyUnlocked(userId)) { 18109 throw new RuntimeException( 18110 "Yikes, someone asked us to reconcile CE storage while " + userId 18111 + " was still locked; this would have caused massive data loss!"); 18112 } 18113 18114 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18115 18116 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18117 for (File file : files) { 18118 final String packageName = file.getName(); 18119 try { 18120 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18121 } catch (PackageManagerException e) { 18122 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18123 synchronized (mInstallLock) { 18124 destroyAppDataLI(volumeUuid, packageName, userId, 18125 StorageManager.FLAG_STORAGE_CE); 18126 } 18127 } 18128 } 18129 } 18130 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18131 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18132 18133 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18134 for (File file : files) { 18135 final String packageName = file.getName(); 18136 try { 18137 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18138 } catch (PackageManagerException e) { 18139 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18140 synchronized (mInstallLock) { 18141 destroyAppDataLI(volumeUuid, packageName, userId, 18142 StorageManager.FLAG_STORAGE_DE); 18143 } 18144 } 18145 } 18146 } 18147 18148 // Ensure that data directories are ready to roll for all packages 18149 // installed for this volume and user 18150 final List<PackageSetting> packages; 18151 synchronized (mPackages) { 18152 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18153 } 18154 int preparedCount = 0; 18155 for (PackageSetting ps : packages) { 18156 final String packageName = ps.name; 18157 if (ps.pkg == null) { 18158 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18159 // TODO: might be due to legacy ASEC apps; we should circle back 18160 // and reconcile again once they're scanned 18161 continue; 18162 } 18163 18164 if (ps.getInstalled(userId)) { 18165 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18166 18167 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18168 // We may have just shuffled around app data directories, so 18169 // prepare them one more time 18170 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18171 } 18172 18173 preparedCount++; 18174 } 18175 } 18176 18177 if (restoreconNeeded) { 18178 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18179 SELinuxMMAC.setRestoreconDone(ceDir); 18180 } 18181 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18182 SELinuxMMAC.setRestoreconDone(deDir); 18183 } 18184 } 18185 18186 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18187 + " packages; restoreconNeeded was " + restoreconNeeded); 18188 } 18189 18190 /** 18191 * Prepare app data for the given app just after it was installed or 18192 * upgraded. This method carefully only touches users that it's installed 18193 * for, and it forces a restorecon to handle any seinfo changes. 18194 * <p> 18195 * Verifies that directories exist and that ownership and labeling is 18196 * correct for all installed apps. If there is an ownership mismatch, it 18197 * will try recovering system apps by wiping data; third-party app data is 18198 * left intact. 18199 * <p> 18200 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18201 */ 18202 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18203 prepareAppDataAfterInstallInternal(pkg); 18204 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18205 for (int i = 0; i < childCount; i++) { 18206 PackageParser.Package childPackage = pkg.childPackages.get(i); 18207 prepareAppDataAfterInstallInternal(childPackage); 18208 } 18209 } 18210 18211 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18212 final PackageSetting ps; 18213 synchronized (mPackages) { 18214 ps = mSettings.mPackages.get(pkg.packageName); 18215 mSettings.writeKernelMappingLPr(ps); 18216 } 18217 18218 final UserManager um = mContext.getSystemService(UserManager.class); 18219 for (UserInfo user : um.getUsers()) { 18220 final int flags; 18221 if (um.isUserUnlocked(user.id)) { 18222 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18223 } else if (um.isUserRunning(user.id)) { 18224 flags = StorageManager.FLAG_STORAGE_DE; 18225 } else { 18226 continue; 18227 } 18228 18229 if (ps.getInstalled(user.id)) { 18230 // Whenever an app changes, force a restorecon of its data 18231 // TODO: when user data is locked, mark that we're still dirty 18232 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18233 } 18234 } 18235 } 18236 18237 /** 18238 * Prepare app data for the given app. 18239 * <p> 18240 * Verifies that directories exist and that ownership and labeling is 18241 * correct for all installed apps. If there is an ownership mismatch, this 18242 * will try recovering system apps by wiping data; third-party app data is 18243 * left intact. 18244 */ 18245 private void prepareAppData(String volumeUuid, int userId, int flags, 18246 PackageParser.Package pkg, boolean restoreconNeeded) { 18247 if (DEBUG_APP_DATA) { 18248 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18249 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18250 } 18251 18252 final String packageName = pkg.packageName; 18253 final ApplicationInfo app = pkg.applicationInfo; 18254 final int appId = UserHandle.getAppId(app.uid); 18255 18256 Preconditions.checkNotNull(app.seinfo); 18257 18258 synchronized (mInstallLock) { 18259 try { 18260 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18261 appId, app.seinfo, app.targetSdkVersion); 18262 } catch (InstallerException e) { 18263 if (app.isSystemApp()) { 18264 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18265 + ", but trying to recover: " + e); 18266 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18267 try { 18268 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18269 appId, app.seinfo, app.targetSdkVersion); 18270 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18271 } catch (InstallerException e2) { 18272 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18273 } 18274 } else { 18275 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18276 } 18277 } 18278 18279 if (restoreconNeeded) { 18280 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18281 } 18282 18283 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18284 // Create a native library symlink only if we have native libraries 18285 // and if the native libraries are 32 bit libraries. We do not provide 18286 // this symlink for 64 bit libraries. 18287 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18288 final String nativeLibPath = app.nativeLibraryDir; 18289 try { 18290 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18291 nativeLibPath, userId); 18292 } catch (InstallerException e) { 18293 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18294 } 18295 } 18296 } 18297 } 18298 } 18299 18300 /** 18301 * For system apps on non-FBE devices, this method migrates any existing 18302 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18303 * the app. 18304 */ 18305 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18306 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18307 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18308 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18309 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18310 synchronized (mInstallLock) { 18311 try { 18312 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18313 } catch (InstallerException e) { 18314 logCriticalInfo(Log.WARN, 18315 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18316 } 18317 } 18318 return true; 18319 } else { 18320 return false; 18321 } 18322 } 18323 18324 private void unfreezePackage(String packageName) { 18325 synchronized (mPackages) { 18326 final PackageSetting ps = mSettings.mPackages.get(packageName); 18327 if (ps != null) { 18328 ps.frozen = false; 18329 } 18330 } 18331 } 18332 18333 @Override 18334 public int movePackage(final String packageName, final String volumeUuid) { 18335 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18336 18337 final int moveId = mNextMoveId.getAndIncrement(); 18338 mHandler.post(new Runnable() { 18339 @Override 18340 public void run() { 18341 try { 18342 movePackageInternal(packageName, volumeUuid, moveId); 18343 } catch (PackageManagerException e) { 18344 Slog.w(TAG, "Failed to move " + packageName, e); 18345 mMoveCallbacks.notifyStatusChanged(moveId, 18346 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18347 } 18348 } 18349 }); 18350 return moveId; 18351 } 18352 18353 private void movePackageInternal(final String packageName, final String volumeUuid, 18354 final int moveId) throws PackageManagerException { 18355 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18356 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18357 final PackageManager pm = mContext.getPackageManager(); 18358 18359 final boolean currentAsec; 18360 final String currentVolumeUuid; 18361 final File codeFile; 18362 final String installerPackageName; 18363 final String packageAbiOverride; 18364 final int appId; 18365 final String seinfo; 18366 final String label; 18367 final int targetSdkVersion; 18368 18369 // reader 18370 synchronized (mPackages) { 18371 final PackageParser.Package pkg = mPackages.get(packageName); 18372 final PackageSetting ps = mSettings.mPackages.get(packageName); 18373 if (pkg == null || ps == null) { 18374 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18375 } 18376 18377 if (pkg.applicationInfo.isSystemApp()) { 18378 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18379 "Cannot move system application"); 18380 } 18381 18382 if (pkg.applicationInfo.isExternalAsec()) { 18383 currentAsec = true; 18384 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18385 } else if (pkg.applicationInfo.isForwardLocked()) { 18386 currentAsec = true; 18387 currentVolumeUuid = "forward_locked"; 18388 } else { 18389 currentAsec = false; 18390 currentVolumeUuid = ps.volumeUuid; 18391 18392 final File probe = new File(pkg.codePath); 18393 final File probeOat = new File(probe, "oat"); 18394 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18395 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18396 "Move only supported for modern cluster style installs"); 18397 } 18398 } 18399 18400 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18401 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18402 "Package already moved to " + volumeUuid); 18403 } 18404 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18405 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18406 "Device admin cannot be moved"); 18407 } 18408 18409 if (ps.frozen) { 18410 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18411 "Failed to move already frozen package"); 18412 } 18413 ps.frozen = true; 18414 18415 codeFile = new File(pkg.codePath); 18416 installerPackageName = ps.installerPackageName; 18417 packageAbiOverride = ps.cpuAbiOverrideString; 18418 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18419 seinfo = pkg.applicationInfo.seinfo; 18420 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18421 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18422 } 18423 18424 // Now that we're guarded by frozen state, kill app during move 18425 final long token = Binder.clearCallingIdentity(); 18426 try { 18427 killApplication(packageName, appId, "move pkg"); 18428 } finally { 18429 Binder.restoreCallingIdentity(token); 18430 } 18431 18432 final Bundle extras = new Bundle(); 18433 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18434 extras.putString(Intent.EXTRA_TITLE, label); 18435 mMoveCallbacks.notifyCreated(moveId, extras); 18436 18437 int installFlags; 18438 final boolean moveCompleteApp; 18439 final File measurePath; 18440 18441 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18442 installFlags = INSTALL_INTERNAL; 18443 moveCompleteApp = !currentAsec; 18444 measurePath = Environment.getDataAppDirectory(volumeUuid); 18445 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18446 installFlags = INSTALL_EXTERNAL; 18447 moveCompleteApp = false; 18448 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18449 } else { 18450 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18451 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18452 || !volume.isMountedWritable()) { 18453 unfreezePackage(packageName); 18454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18455 "Move location not mounted private volume"); 18456 } 18457 18458 Preconditions.checkState(!currentAsec); 18459 18460 installFlags = INSTALL_INTERNAL; 18461 moveCompleteApp = true; 18462 measurePath = Environment.getDataAppDirectory(volumeUuid); 18463 } 18464 18465 final PackageStats stats = new PackageStats(null, -1); 18466 synchronized (mInstaller) { 18467 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18468 unfreezePackage(packageName); 18469 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18470 "Failed to measure package size"); 18471 } 18472 } 18473 18474 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18475 + stats.dataSize); 18476 18477 final long startFreeBytes = measurePath.getFreeSpace(); 18478 final long sizeBytes; 18479 if (moveCompleteApp) { 18480 sizeBytes = stats.codeSize + stats.dataSize; 18481 } else { 18482 sizeBytes = stats.codeSize; 18483 } 18484 18485 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18486 unfreezePackage(packageName); 18487 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18488 "Not enough free space to move"); 18489 } 18490 18491 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18492 18493 final CountDownLatch installedLatch = new CountDownLatch(1); 18494 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18495 @Override 18496 public void onUserActionRequired(Intent intent) throws RemoteException { 18497 throw new IllegalStateException(); 18498 } 18499 18500 @Override 18501 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18502 Bundle extras) throws RemoteException { 18503 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18504 + PackageManager.installStatusToString(returnCode, msg)); 18505 18506 installedLatch.countDown(); 18507 18508 // Regardless of success or failure of the move operation, 18509 // always unfreeze the package 18510 unfreezePackage(packageName); 18511 18512 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18513 switch (status) { 18514 case PackageInstaller.STATUS_SUCCESS: 18515 mMoveCallbacks.notifyStatusChanged(moveId, 18516 PackageManager.MOVE_SUCCEEDED); 18517 break; 18518 case PackageInstaller.STATUS_FAILURE_STORAGE: 18519 mMoveCallbacks.notifyStatusChanged(moveId, 18520 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18521 break; 18522 default: 18523 mMoveCallbacks.notifyStatusChanged(moveId, 18524 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18525 break; 18526 } 18527 } 18528 }; 18529 18530 final MoveInfo move; 18531 if (moveCompleteApp) { 18532 // Kick off a thread to report progress estimates 18533 new Thread() { 18534 @Override 18535 public void run() { 18536 while (true) { 18537 try { 18538 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18539 break; 18540 } 18541 } catch (InterruptedException ignored) { 18542 } 18543 18544 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18545 final int progress = 10 + (int) MathUtils.constrain( 18546 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18547 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18548 } 18549 } 18550 }.start(); 18551 18552 final String dataAppName = codeFile.getName(); 18553 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18554 dataAppName, appId, seinfo, targetSdkVersion); 18555 } else { 18556 move = null; 18557 } 18558 18559 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18560 18561 final Message msg = mHandler.obtainMessage(INIT_COPY); 18562 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18563 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18564 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18565 packageAbiOverride, null); 18566 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18567 msg.obj = params; 18568 18569 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18570 System.identityHashCode(msg.obj)); 18571 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18572 System.identityHashCode(msg.obj)); 18573 18574 mHandler.sendMessage(msg); 18575 } 18576 18577 @Override 18578 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18579 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18580 18581 final int realMoveId = mNextMoveId.getAndIncrement(); 18582 final Bundle extras = new Bundle(); 18583 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18584 mMoveCallbacks.notifyCreated(realMoveId, extras); 18585 18586 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18587 @Override 18588 public void onCreated(int moveId, Bundle extras) { 18589 // Ignored 18590 } 18591 18592 @Override 18593 public void onStatusChanged(int moveId, int status, long estMillis) { 18594 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18595 } 18596 }; 18597 18598 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18599 storage.setPrimaryStorageUuid(volumeUuid, callback); 18600 return realMoveId; 18601 } 18602 18603 @Override 18604 public int getMoveStatus(int moveId) { 18605 mContext.enforceCallingOrSelfPermission( 18606 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18607 return mMoveCallbacks.mLastStatus.get(moveId); 18608 } 18609 18610 @Override 18611 public void registerMoveCallback(IPackageMoveObserver callback) { 18612 mContext.enforceCallingOrSelfPermission( 18613 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18614 mMoveCallbacks.register(callback); 18615 } 18616 18617 @Override 18618 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18619 mContext.enforceCallingOrSelfPermission( 18620 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18621 mMoveCallbacks.unregister(callback); 18622 } 18623 18624 @Override 18625 public boolean setInstallLocation(int loc) { 18626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18627 null); 18628 if (getInstallLocation() == loc) { 18629 return true; 18630 } 18631 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18632 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18633 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18634 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18635 return true; 18636 } 18637 return false; 18638 } 18639 18640 @Override 18641 public int getInstallLocation() { 18642 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18643 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18644 PackageHelper.APP_INSTALL_AUTO); 18645 } 18646 18647 /** Called by UserManagerService */ 18648 void cleanUpUser(UserManagerService userManager, int userHandle) { 18649 synchronized (mPackages) { 18650 mDirtyUsers.remove(userHandle); 18651 mUserNeedsBadging.delete(userHandle); 18652 mSettings.removeUserLPw(userHandle); 18653 mPendingBroadcasts.remove(userHandle); 18654 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18655 } 18656 synchronized (mInstallLock) { 18657 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18658 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18659 final String volumeUuid = vol.getFsUuid(); 18660 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18661 try { 18662 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18663 } catch (InstallerException e) { 18664 Slog.w(TAG, "Failed to remove user data", e); 18665 } 18666 } 18667 synchronized (mPackages) { 18668 removeUnusedPackagesLILPw(userManager, userHandle); 18669 } 18670 } 18671 } 18672 18673 /** 18674 * We're removing userHandle and would like to remove any downloaded packages 18675 * that are no longer in use by any other user. 18676 * @param userHandle the user being removed 18677 */ 18678 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18679 final boolean DEBUG_CLEAN_APKS = false; 18680 int [] users = userManager.getUserIds(); 18681 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18682 while (psit.hasNext()) { 18683 PackageSetting ps = psit.next(); 18684 if (ps.pkg == null) { 18685 continue; 18686 } 18687 final String packageName = ps.pkg.packageName; 18688 // Skip over if system app 18689 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18690 continue; 18691 } 18692 if (DEBUG_CLEAN_APKS) { 18693 Slog.i(TAG, "Checking package " + packageName); 18694 } 18695 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18696 if (keep) { 18697 if (DEBUG_CLEAN_APKS) { 18698 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18699 } 18700 } else { 18701 for (int i = 0; i < users.length; i++) { 18702 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18703 keep = true; 18704 if (DEBUG_CLEAN_APKS) { 18705 Slog.i(TAG, " Keeping package " + packageName + " for user " 18706 + users[i]); 18707 } 18708 break; 18709 } 18710 } 18711 } 18712 if (!keep) { 18713 if (DEBUG_CLEAN_APKS) { 18714 Slog.i(TAG, " Removing package " + packageName); 18715 } 18716 mHandler.post(new Runnable() { 18717 public void run() { 18718 deletePackageX(packageName, userHandle, 0); 18719 } //end run 18720 }); 18721 } 18722 } 18723 } 18724 18725 /** Called by UserManagerService */ 18726 void createNewUser(int userHandle) { 18727 synchronized (mInstallLock) { 18728 try { 18729 mInstaller.createUserConfig(userHandle); 18730 } catch (InstallerException e) { 18731 Slog.w(TAG, "Failed to create user config", e); 18732 } 18733 mSettings.createNewUserLI(this, mInstaller, userHandle); 18734 } 18735 synchronized (mPackages) { 18736 applyFactoryDefaultBrowserLPw(userHandle); 18737 primeDomainVerificationsLPw(userHandle); 18738 } 18739 } 18740 18741 void newUserCreated(final int userHandle) { 18742 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18743 // If permission review for legacy apps is required, we represent 18744 // dagerous permissions for such apps as always granted runtime 18745 // permissions to keep per user flag state whether review is needed. 18746 // Hence, if a new user is added we have to propagate dangerous 18747 // permission grants for these legacy apps. 18748 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18749 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18750 | UPDATE_PERMISSIONS_REPLACE_ALL); 18751 } 18752 } 18753 18754 @Override 18755 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18756 mContext.enforceCallingOrSelfPermission( 18757 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18758 "Only package verification agents can read the verifier device identity"); 18759 18760 synchronized (mPackages) { 18761 return mSettings.getVerifierDeviceIdentityLPw(); 18762 } 18763 } 18764 18765 @Override 18766 public void setPermissionEnforced(String permission, boolean enforced) { 18767 // TODO: Now that we no longer change GID for storage, this should to away. 18768 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18769 "setPermissionEnforced"); 18770 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18771 synchronized (mPackages) { 18772 if (mSettings.mReadExternalStorageEnforced == null 18773 || mSettings.mReadExternalStorageEnforced != enforced) { 18774 mSettings.mReadExternalStorageEnforced = enforced; 18775 mSettings.writeLPr(); 18776 } 18777 } 18778 // kill any non-foreground processes so we restart them and 18779 // grant/revoke the GID. 18780 final IActivityManager am = ActivityManagerNative.getDefault(); 18781 if (am != null) { 18782 final long token = Binder.clearCallingIdentity(); 18783 try { 18784 am.killProcessesBelowForeground("setPermissionEnforcement"); 18785 } catch (RemoteException e) { 18786 } finally { 18787 Binder.restoreCallingIdentity(token); 18788 } 18789 } 18790 } else { 18791 throw new IllegalArgumentException("No selective enforcement for " + permission); 18792 } 18793 } 18794 18795 @Override 18796 @Deprecated 18797 public boolean isPermissionEnforced(String permission) { 18798 return true; 18799 } 18800 18801 @Override 18802 public boolean isStorageLow() { 18803 final long token = Binder.clearCallingIdentity(); 18804 try { 18805 final DeviceStorageMonitorInternal 18806 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18807 if (dsm != null) { 18808 return dsm.isMemoryLow(); 18809 } else { 18810 return false; 18811 } 18812 } finally { 18813 Binder.restoreCallingIdentity(token); 18814 } 18815 } 18816 18817 @Override 18818 public IPackageInstaller getPackageInstaller() { 18819 return mInstallerService; 18820 } 18821 18822 private boolean userNeedsBadging(int userId) { 18823 int index = mUserNeedsBadging.indexOfKey(userId); 18824 if (index < 0) { 18825 final UserInfo userInfo; 18826 final long token = Binder.clearCallingIdentity(); 18827 try { 18828 userInfo = sUserManager.getUserInfo(userId); 18829 } finally { 18830 Binder.restoreCallingIdentity(token); 18831 } 18832 final boolean b; 18833 if (userInfo != null && userInfo.isManagedProfile()) { 18834 b = true; 18835 } else { 18836 b = false; 18837 } 18838 mUserNeedsBadging.put(userId, b); 18839 return b; 18840 } 18841 return mUserNeedsBadging.valueAt(index); 18842 } 18843 18844 @Override 18845 public KeySet getKeySetByAlias(String packageName, String alias) { 18846 if (packageName == null || alias == null) { 18847 return null; 18848 } 18849 synchronized(mPackages) { 18850 final PackageParser.Package pkg = mPackages.get(packageName); 18851 if (pkg == null) { 18852 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18853 throw new IllegalArgumentException("Unknown package: " + packageName); 18854 } 18855 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18856 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18857 } 18858 } 18859 18860 @Override 18861 public KeySet getSigningKeySet(String packageName) { 18862 if (packageName == null) { 18863 return null; 18864 } 18865 synchronized(mPackages) { 18866 final PackageParser.Package pkg = mPackages.get(packageName); 18867 if (pkg == null) { 18868 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18869 throw new IllegalArgumentException("Unknown package: " + packageName); 18870 } 18871 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18872 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18873 throw new SecurityException("May not access signing KeySet of other apps."); 18874 } 18875 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18876 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18877 } 18878 } 18879 18880 @Override 18881 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18882 if (packageName == null || ks == null) { 18883 return false; 18884 } 18885 synchronized(mPackages) { 18886 final PackageParser.Package pkg = mPackages.get(packageName); 18887 if (pkg == null) { 18888 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18889 throw new IllegalArgumentException("Unknown package: " + packageName); 18890 } 18891 IBinder ksh = ks.getToken(); 18892 if (ksh instanceof KeySetHandle) { 18893 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18894 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18895 } 18896 return false; 18897 } 18898 } 18899 18900 @Override 18901 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18902 if (packageName == null || ks == null) { 18903 return false; 18904 } 18905 synchronized(mPackages) { 18906 final PackageParser.Package pkg = mPackages.get(packageName); 18907 if (pkg == null) { 18908 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18909 throw new IllegalArgumentException("Unknown package: " + packageName); 18910 } 18911 IBinder ksh = ks.getToken(); 18912 if (ksh instanceof KeySetHandle) { 18913 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18914 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18915 } 18916 return false; 18917 } 18918 } 18919 18920 private void deletePackageIfUnusedLPr(final String packageName) { 18921 PackageSetting ps = mSettings.mPackages.get(packageName); 18922 if (ps == null) { 18923 return; 18924 } 18925 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18926 // TODO Implement atomic delete if package is unused 18927 // It is currently possible that the package will be deleted even if it is installed 18928 // after this method returns. 18929 mHandler.post(new Runnable() { 18930 public void run() { 18931 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18932 } 18933 }); 18934 } 18935 } 18936 18937 /** 18938 * Check and throw if the given before/after packages would be considered a 18939 * downgrade. 18940 */ 18941 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18942 throws PackageManagerException { 18943 if (after.versionCode < before.mVersionCode) { 18944 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18945 "Update version code " + after.versionCode + " is older than current " 18946 + before.mVersionCode); 18947 } else if (after.versionCode == before.mVersionCode) { 18948 if (after.baseRevisionCode < before.baseRevisionCode) { 18949 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18950 "Update base revision code " + after.baseRevisionCode 18951 + " is older than current " + before.baseRevisionCode); 18952 } 18953 18954 if (!ArrayUtils.isEmpty(after.splitNames)) { 18955 for (int i = 0; i < after.splitNames.length; i++) { 18956 final String splitName = after.splitNames[i]; 18957 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18958 if (j != -1) { 18959 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18960 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18961 "Update split " + splitName + " revision code " 18962 + after.splitRevisionCodes[i] + " is older than current " 18963 + before.splitRevisionCodes[j]); 18964 } 18965 } 18966 } 18967 } 18968 } 18969 } 18970 18971 private static class MoveCallbacks extends Handler { 18972 private static final int MSG_CREATED = 1; 18973 private static final int MSG_STATUS_CHANGED = 2; 18974 18975 private final RemoteCallbackList<IPackageMoveObserver> 18976 mCallbacks = new RemoteCallbackList<>(); 18977 18978 private final SparseIntArray mLastStatus = new SparseIntArray(); 18979 18980 public MoveCallbacks(Looper looper) { 18981 super(looper); 18982 } 18983 18984 public void register(IPackageMoveObserver callback) { 18985 mCallbacks.register(callback); 18986 } 18987 18988 public void unregister(IPackageMoveObserver callback) { 18989 mCallbacks.unregister(callback); 18990 } 18991 18992 @Override 18993 public void handleMessage(Message msg) { 18994 final SomeArgs args = (SomeArgs) msg.obj; 18995 final int n = mCallbacks.beginBroadcast(); 18996 for (int i = 0; i < n; i++) { 18997 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18998 try { 18999 invokeCallback(callback, msg.what, args); 19000 } catch (RemoteException ignored) { 19001 } 19002 } 19003 mCallbacks.finishBroadcast(); 19004 args.recycle(); 19005 } 19006 19007 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19008 throws RemoteException { 19009 switch (what) { 19010 case MSG_CREATED: { 19011 callback.onCreated(args.argi1, (Bundle) args.arg2); 19012 break; 19013 } 19014 case MSG_STATUS_CHANGED: { 19015 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19016 break; 19017 } 19018 } 19019 } 19020 19021 private void notifyCreated(int moveId, Bundle extras) { 19022 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19023 19024 final SomeArgs args = SomeArgs.obtain(); 19025 args.argi1 = moveId; 19026 args.arg2 = extras; 19027 obtainMessage(MSG_CREATED, args).sendToTarget(); 19028 } 19029 19030 private void notifyStatusChanged(int moveId, int status) { 19031 notifyStatusChanged(moveId, status, -1); 19032 } 19033 19034 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19035 Slog.v(TAG, "Move " + moveId + " status " + status); 19036 19037 final SomeArgs args = SomeArgs.obtain(); 19038 args.argi1 = moveId; 19039 args.argi2 = status; 19040 args.arg3 = estMillis; 19041 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19042 19043 synchronized (mLastStatus) { 19044 mLastStatus.put(moveId, status); 19045 } 19046 } 19047 } 19048 19049 private final static class OnPermissionChangeListeners extends Handler { 19050 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19051 19052 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19053 new RemoteCallbackList<>(); 19054 19055 public OnPermissionChangeListeners(Looper looper) { 19056 super(looper); 19057 } 19058 19059 @Override 19060 public void handleMessage(Message msg) { 19061 switch (msg.what) { 19062 case MSG_ON_PERMISSIONS_CHANGED: { 19063 final int uid = msg.arg1; 19064 handleOnPermissionsChanged(uid); 19065 } break; 19066 } 19067 } 19068 19069 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19070 mPermissionListeners.register(listener); 19071 19072 } 19073 19074 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19075 mPermissionListeners.unregister(listener); 19076 } 19077 19078 public void onPermissionsChanged(int uid) { 19079 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19080 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19081 } 19082 } 19083 19084 private void handleOnPermissionsChanged(int uid) { 19085 final int count = mPermissionListeners.beginBroadcast(); 19086 try { 19087 for (int i = 0; i < count; i++) { 19088 IOnPermissionsChangeListener callback = mPermissionListeners 19089 .getBroadcastItem(i); 19090 try { 19091 callback.onPermissionsChanged(uid); 19092 } catch (RemoteException e) { 19093 Log.e(TAG, "Permission listener is dead", e); 19094 } 19095 } 19096 } finally { 19097 mPermissionListeners.finishBroadcast(); 19098 } 19099 } 19100 } 19101 19102 private class PackageManagerInternalImpl extends PackageManagerInternal { 19103 @Override 19104 public void setLocationPackagesProvider(PackagesProvider provider) { 19105 synchronized (mPackages) { 19106 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19107 } 19108 } 19109 19110 @Override 19111 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19112 synchronized (mPackages) { 19113 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19114 } 19115 } 19116 19117 @Override 19118 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19119 synchronized (mPackages) { 19120 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19121 } 19122 } 19123 19124 @Override 19125 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19126 synchronized (mPackages) { 19127 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19128 } 19129 } 19130 19131 @Override 19132 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19133 synchronized (mPackages) { 19134 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19135 } 19136 } 19137 19138 @Override 19139 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19140 synchronized (mPackages) { 19141 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19142 } 19143 } 19144 19145 @Override 19146 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19147 synchronized (mPackages) { 19148 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19149 packageName, userId); 19150 } 19151 } 19152 19153 @Override 19154 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19155 synchronized (mPackages) { 19156 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19157 packageName, userId); 19158 } 19159 } 19160 19161 @Override 19162 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19163 synchronized (mPackages) { 19164 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19165 packageName, userId); 19166 } 19167 } 19168 19169 @Override 19170 public void setKeepUninstalledPackages(final List<String> packageList) { 19171 Preconditions.checkNotNull(packageList); 19172 List<String> removedFromList = null; 19173 synchronized (mPackages) { 19174 if (mKeepUninstalledPackages != null) { 19175 final int packagesCount = mKeepUninstalledPackages.size(); 19176 for (int i = 0; i < packagesCount; i++) { 19177 String oldPackage = mKeepUninstalledPackages.get(i); 19178 if (packageList != null && packageList.contains(oldPackage)) { 19179 continue; 19180 } 19181 if (removedFromList == null) { 19182 removedFromList = new ArrayList<>(); 19183 } 19184 removedFromList.add(oldPackage); 19185 } 19186 } 19187 mKeepUninstalledPackages = new ArrayList<>(packageList); 19188 if (removedFromList != null) { 19189 final int removedCount = removedFromList.size(); 19190 for (int i = 0; i < removedCount; i++) { 19191 deletePackageIfUnusedLPr(removedFromList.get(i)); 19192 } 19193 } 19194 } 19195 } 19196 19197 @Override 19198 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19199 synchronized (mPackages) { 19200 // If we do not support permission review, done. 19201 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19202 return false; 19203 } 19204 19205 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19206 if (packageSetting == null) { 19207 return false; 19208 } 19209 19210 // Permission review applies only to apps not supporting the new permission model. 19211 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19212 return false; 19213 } 19214 19215 // Legacy apps have the permission and get user consent on launch. 19216 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19217 return permissionsState.isPermissionReviewRequired(userId); 19218 } 19219 } 19220 19221 @Override 19222 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19223 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19224 } 19225 } 19226 19227 @Override 19228 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19229 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19230 synchronized (mPackages) { 19231 final long identity = Binder.clearCallingIdentity(); 19232 try { 19233 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19234 packageNames, userId); 19235 } finally { 19236 Binder.restoreCallingIdentity(identity); 19237 } 19238 } 19239 } 19240 19241 private static void enforceSystemOrPhoneCaller(String tag) { 19242 int callingUid = Binder.getCallingUid(); 19243 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19244 throw new SecurityException( 19245 "Cannot call " + tag + " from UID " + callingUid); 19246 } 19247 } 19248 19249 boolean isHistoricalPackageUsageAvailable() { 19250 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19251 } 19252 19253 /** 19254 * Return a <b>copy</b> of the collection of packages known to the package manager. 19255 * @return A copy of the values of mPackages. 19256 */ 19257 Collection<PackageParser.Package> getPackages() { 19258 synchronized (mPackages) { 19259 return new ArrayList<>(mPackages.values()); 19260 } 19261 } 19262} 19263