PackageManagerService.java revision 7efb7eff63ba7c57de918afba9140d74a816ecc6
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_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Process.PACKAGE_INFO_GID; 79import static android.os.Process.SYSTEM_UID; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.app.ActivityManager; 105import android.app.ActivityManagerNative; 106import android.app.IActivityManager; 107import android.app.admin.DevicePolicyManagerInternal; 108import android.app.admin.IDevicePolicyManager; 109import android.app.admin.SecurityLog; 110import android.app.backup.IBackupManager; 111import android.content.BroadcastReceiver; 112import android.content.ComponentName; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.Process; 181import android.os.RemoteCallbackList; 182import android.os.RemoteException; 183import android.os.ResultReceiver; 184import android.os.SELinux; 185import android.os.ServiceManager; 186import android.os.SystemClock; 187import android.os.SystemProperties; 188import android.os.Trace; 189import android.os.UserHandle; 190import android.os.UserManager; 191import android.os.storage.IMountService; 192import android.os.storage.MountServiceInternal; 193import android.os.storage.StorageEventListener; 194import android.os.storage.StorageManager; 195import android.os.storage.VolumeInfo; 196import android.os.storage.VolumeRecord; 197import android.security.KeyStore; 198import android.security.SystemKeyStore; 199import android.system.ErrnoException; 200import android.system.Os; 201import android.text.TextUtils; 202import android.text.format.DateUtils; 203import android.util.ArrayMap; 204import android.util.ArraySet; 205import android.util.AtomicFile; 206import android.util.DisplayMetrics; 207import android.util.EventLog; 208import android.util.ExceptionUtils; 209import android.util.Log; 210import android.util.LogPrinter; 211import android.util.MathUtils; 212import android.util.PrintStreamPrinter; 213import android.util.Slog; 214import android.util.SparseArray; 215import android.util.SparseBooleanArray; 216import android.util.SparseIntArray; 217import android.util.Xml; 218import android.view.Display; 219 220import com.android.internal.R; 221import com.android.internal.annotations.GuardedBy; 222import com.android.internal.app.IMediaContainerService; 223import com.android.internal.app.ResolverActivity; 224import com.android.internal.content.NativeLibraryHelper; 225import com.android.internal.content.PackageHelper; 226import com.android.internal.os.IParcelFileDescriptorFactory; 227import com.android.internal.os.InstallerConnection.InstallerException; 228import com.android.internal.os.SomeArgs; 229import com.android.internal.os.Zygote; 230import com.android.internal.util.ArrayUtils; 231import com.android.internal.util.FastPrintWriter; 232import com.android.internal.util.FastXmlSerializer; 233import com.android.internal.util.IndentingPrintWriter; 234import com.android.internal.util.Preconditions; 235import com.android.internal.util.XmlUtils; 236import com.android.server.EventLogTags; 237import com.android.server.FgThread; 238import com.android.server.IntentResolver; 239import com.android.server.LocalServices; 240import com.android.server.ServiceThread; 241import com.android.server.SystemConfig; 242import com.android.server.Watchdog; 243import com.android.server.pm.PermissionsState.PermissionState; 244import com.android.server.pm.Settings.DatabaseVersion; 245import com.android.server.pm.Settings.VersionInfo; 246import com.android.server.storage.DeviceStorageMonitorInternal; 247 248import dalvik.system.DexFile; 249import dalvik.system.VMRuntime; 250 251import libcore.io.IoUtils; 252import libcore.util.EmptyArray; 253 254import org.xmlpull.v1.XmlPullParser; 255import org.xmlpull.v1.XmlPullParserException; 256import org.xmlpull.v1.XmlSerializer; 257 258import java.io.BufferedInputStream; 259import java.io.BufferedOutputStream; 260import java.io.BufferedReader; 261import java.io.ByteArrayInputStream; 262import java.io.ByteArrayOutputStream; 263import java.io.File; 264import java.io.FileDescriptor; 265import java.io.FileNotFoundException; 266import java.io.FileOutputStream; 267import java.io.FileReader; 268import java.io.FilenameFilter; 269import java.io.IOException; 270import java.io.InputStream; 271import java.io.PrintWriter; 272import java.nio.charset.StandardCharsets; 273import java.security.MessageDigest; 274import java.security.NoSuchAlgorithmException; 275import java.security.PublicKey; 276import java.security.cert.CertificateEncodingException; 277import java.security.cert.CertificateException; 278import java.text.SimpleDateFormat; 279import java.util.ArrayList; 280import java.util.Arrays; 281import java.util.Collection; 282import java.util.Collections; 283import java.util.Comparator; 284import java.util.Date; 285import java.util.HashSet; 286import java.util.Iterator; 287import java.util.List; 288import java.util.Map; 289import java.util.Objects; 290import java.util.Set; 291import java.util.concurrent.CountDownLatch; 292import java.util.concurrent.TimeUnit; 293import java.util.concurrent.atomic.AtomicBoolean; 294import java.util.concurrent.atomic.AtomicInteger; 295import java.util.concurrent.atomic.AtomicLong; 296 297/** 298 * Keep track of all those .apks everywhere. 299 * 300 * This is very central to the platform's security; please run the unit 301 * tests whenever making modifications here: 302 * 303runtest -c android.content.pm.PackageManagerTests frameworks-core 304 * 305 * {@hide} 306 */ 307public class PackageManagerService extends IPackageManager.Stub { 308 static final String TAG = "PackageManager"; 309 static final boolean DEBUG_SETTINGS = false; 310 static final boolean DEBUG_PREFERRED = false; 311 static final boolean DEBUG_UPGRADE = false; 312 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 313 private static final boolean DEBUG_BACKUP = false; 314 private static final boolean DEBUG_INSTALL = false; 315 private static final boolean DEBUG_REMOVE = false; 316 private static final boolean DEBUG_BROADCASTS = false; 317 private static final boolean DEBUG_SHOW_INFO = false; 318 private static final boolean DEBUG_PACKAGE_INFO = false; 319 private static final boolean DEBUG_INTENT_MATCHING = false; 320 private static final boolean DEBUG_PACKAGE_SCANNING = false; 321 private static final boolean DEBUG_VERIFY = false; 322 323 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 324 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 325 // user, but by default initialize to this. 326 static final boolean DEBUG_DEXOPT = false; 327 328 private static final boolean DEBUG_ABI_SELECTION = false; 329 private static final boolean DEBUG_EPHEMERAL = false; 330 private static final boolean DEBUG_TRIAGED_MISSING = false; 331 private static final boolean DEBUG_APP_DATA = false; 332 333 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 334 335 private static final boolean DISABLE_EPHEMERAL_APPS = true; 336 337 private static final int RADIO_UID = Process.PHONE_UID; 338 private static final int LOG_UID = Process.LOG_UID; 339 private static final int NFC_UID = Process.NFC_UID; 340 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 341 private static final int SHELL_UID = Process.SHELL_UID; 342 343 // Cap the size of permission trees that 3rd party apps can define 344 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 345 346 // Suffix used during package installation when copying/moving 347 // package apks to install directory. 348 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 349 350 static final int SCAN_NO_DEX = 1<<1; 351 static final int SCAN_FORCE_DEX = 1<<2; 352 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 353 static final int SCAN_NEW_INSTALL = 1<<4; 354 static final int SCAN_NO_PATHS = 1<<5; 355 static final int SCAN_UPDATE_TIME = 1<<6; 356 static final int SCAN_DEFER_DEX = 1<<7; 357 static final int SCAN_BOOTING = 1<<8; 358 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 359 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 360 static final int SCAN_REPLACING = 1<<11; 361 static final int SCAN_REQUIRE_KNOWN = 1<<12; 362 static final int SCAN_MOVE = 1<<13; 363 static final int SCAN_INITIAL = 1<<14; 364 static final int SCAN_CHECK_ONLY = 1<<15; 365 static final int SCAN_DONT_KILL_APP = 1<<17; 366 367 static final int REMOVE_CHATTY = 1<<16; 368 369 private static final int[] EMPTY_INT_ARRAY = new int[0]; 370 371 /** 372 * Timeout (in milliseconds) after which the watchdog should declare that 373 * our handler thread is wedged. The usual default for such things is one 374 * minute but we sometimes do very lengthy I/O operations on this thread, 375 * such as installing multi-gigabyte applications, so ours needs to be longer. 376 */ 377 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 378 379 /** 380 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 381 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 382 * settings entry if available, otherwise we use the hardcoded default. If it's been 383 * more than this long since the last fstrim, we force one during the boot sequence. 384 * 385 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 386 * one gets run at the next available charging+idle time. This final mandatory 387 * no-fstrim check kicks in only of the other scheduling criteria is never met. 388 */ 389 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 390 391 /** 392 * Whether verification is enabled by default. 393 */ 394 private static final boolean DEFAULT_VERIFY_ENABLE = true; 395 396 /** 397 * The default maximum time to wait for the verification agent to return in 398 * milliseconds. 399 */ 400 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 401 402 /** 403 * The default response for package verification timeout. 404 * 405 * This can be either PackageManager.VERIFICATION_ALLOW or 406 * PackageManager.VERIFICATION_REJECT. 407 */ 408 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 409 410 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 411 412 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 413 DEFAULT_CONTAINER_PACKAGE, 414 "com.android.defcontainer.DefaultContainerService"); 415 416 private static final String KILL_APP_REASON_GIDS_CHANGED = 417 "permission grant or revoke changed gids"; 418 419 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 420 "permissions revoked"; 421 422 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 423 424 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 425 426 /** Permission grant: not grant the permission. */ 427 private static final int GRANT_DENIED = 1; 428 429 /** Permission grant: grant the permission as an install permission. */ 430 private static final int GRANT_INSTALL = 2; 431 432 /** Permission grant: grant the permission as a runtime one. */ 433 private static final int GRANT_RUNTIME = 3; 434 435 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 436 private static final int GRANT_UPGRADE = 4; 437 438 /** Canonical intent used to identify what counts as a "web browser" app */ 439 private static final Intent sBrowserIntent; 440 static { 441 sBrowserIntent = new Intent(); 442 sBrowserIntent.setAction(Intent.ACTION_VIEW); 443 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 444 sBrowserIntent.setData(Uri.parse("http:")); 445 } 446 447 // Compilation reasons. 448 public static final int REASON_FIRST_BOOT = 0; 449 public static final int REASON_BOOT = 1; 450 public static final int REASON_INSTALL = 2; 451 public static final int REASON_BACKGROUND_DEXOPT = 3; 452 public static final int REASON_AB_OTA = 4; 453 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 454 public static final int REASON_SHARED_APK = 6; 455 public static final int REASON_FORCED_DEXOPT = 7; 456 457 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 458 459 final ServiceThread mHandlerThread; 460 461 final PackageHandler mHandler; 462 463 private final ProcessLoggingHandler mProcessLoggingHandler; 464 465 /** 466 * Messages for {@link #mHandler} that need to wait for system ready before 467 * being dispatched. 468 */ 469 private ArrayList<Message> mPostSystemReadyMessages; 470 471 final int mSdkVersion = Build.VERSION.SDK_INT; 472 473 final Context mContext; 474 final boolean mFactoryTest; 475 final boolean mOnlyCore; 476 final DisplayMetrics mMetrics; 477 final int mDefParseFlags; 478 final String[] mSeparateProcesses; 479 final boolean mIsUpgrade; 480 final boolean mIsPreNUpgrade; 481 482 /** The location for ASEC container files on internal storage. */ 483 final String mAsecInternalPath; 484 485 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 486 // LOCK HELD. Can be called with mInstallLock held. 487 @GuardedBy("mInstallLock") 488 final Installer mInstaller; 489 490 /** Directory where installed third-party apps stored */ 491 final File mAppInstallDir; 492 final File mEphemeralInstallDir; 493 494 /** 495 * Directory to which applications installed internally have their 496 * 32 bit native libraries copied. 497 */ 498 private File mAppLib32InstallDir; 499 500 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 501 // apps. 502 final File mDrmAppPrivateInstallDir; 503 504 // ---------------------------------------------------------------- 505 506 // Lock for state used when installing and doing other long running 507 // operations. Methods that must be called with this lock held have 508 // the suffix "LI". 509 final Object mInstallLock = new Object(); 510 511 // ---------------------------------------------------------------- 512 513 // Keys are String (package name), values are Package. This also serves 514 // as the lock for the global state. Methods that must be called with 515 // this lock held have the prefix "LP". 516 @GuardedBy("mPackages") 517 final ArrayMap<String, PackageParser.Package> mPackages = 518 new ArrayMap<String, PackageParser.Package>(); 519 520 final ArrayMap<String, Set<String>> mKnownCodebase = 521 new ArrayMap<String, Set<String>>(); 522 523 // Tracks available target package names -> overlay package paths. 524 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 525 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 526 527 /** 528 * Tracks new system packages [received in an OTA] that we expect to 529 * find updated user-installed versions. Keys are package name, values 530 * are package location. 531 */ 532 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 533 534 /** 535 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 536 */ 537 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 538 /** 539 * Whether or not system app permissions should be promoted from install to runtime. 540 */ 541 boolean mPromoteSystemApps; 542 543 final Settings mSettings; 544 boolean mRestoredSettings; 545 546 // System configuration read by SystemConfig. 547 final int[] mGlobalGids; 548 final SparseArray<ArraySet<String>> mSystemPermissions; 549 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 550 551 // If mac_permissions.xml was found for seinfo labeling. 552 boolean mFoundPolicyFile; 553 554 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 555 556 public static final class SharedLibraryEntry { 557 public final String path; 558 public final String apk; 559 560 SharedLibraryEntry(String _path, String _apk) { 561 path = _path; 562 apk = _apk; 563 } 564 } 565 566 // Currently known shared libraries. 567 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 568 new ArrayMap<String, SharedLibraryEntry>(); 569 570 // All available activities, for your resolving pleasure. 571 final ActivityIntentResolver mActivities = 572 new ActivityIntentResolver(); 573 574 // All available receivers, for your resolving pleasure. 575 final ActivityIntentResolver mReceivers = 576 new ActivityIntentResolver(); 577 578 // All available services, for your resolving pleasure. 579 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 580 581 // All available providers, for your resolving pleasure. 582 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 583 584 // Mapping from provider base names (first directory in content URI codePath) 585 // to the provider information. 586 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 587 new ArrayMap<String, PackageParser.Provider>(); 588 589 // Mapping from instrumentation class names to info about them. 590 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 591 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 592 593 // Mapping from permission names to info about them. 594 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 595 new ArrayMap<String, PackageParser.PermissionGroup>(); 596 597 // Packages whose data we have transfered into another package, thus 598 // should no longer exist. 599 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 600 601 // Broadcast actions that are only available to the system. 602 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 603 604 /** List of packages waiting for verification. */ 605 final SparseArray<PackageVerificationState> mPendingVerification 606 = new SparseArray<PackageVerificationState>(); 607 608 /** Set of packages associated with each app op permission. */ 609 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 610 611 final PackageInstallerService mInstallerService; 612 613 private final PackageDexOptimizer mPackageDexOptimizer; 614 615 private AtomicInteger mNextMoveId = new AtomicInteger(); 616 private final MoveCallbacks mMoveCallbacks; 617 618 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 619 620 // Cache of users who need badging. 621 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 622 623 /** Token for keys in mPendingVerification. */ 624 private int mPendingVerificationToken = 0; 625 626 volatile boolean mSystemReady; 627 volatile boolean mSafeMode; 628 volatile boolean mHasSystemUidErrors; 629 630 ApplicationInfo mAndroidApplication; 631 final ActivityInfo mResolveActivity = new ActivityInfo(); 632 final ResolveInfo mResolveInfo = new ResolveInfo(); 633 ComponentName mResolveComponentName; 634 PackageParser.Package mPlatformPackage; 635 ComponentName mCustomResolverComponentName; 636 637 boolean mResolverReplaced = false; 638 639 private final @Nullable ComponentName mIntentFilterVerifierComponent; 640 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 641 642 private int mIntentFilterVerificationToken = 0; 643 644 /** Component that knows whether or not an ephemeral application exists */ 645 final ComponentName mEphemeralResolverComponent; 646 /** The service connection to the ephemeral resolver */ 647 final EphemeralResolverConnection mEphemeralResolverConnection; 648 649 /** Component used to install ephemeral applications */ 650 final ComponentName mEphemeralInstallerComponent; 651 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 652 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 653 654 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 655 = new SparseArray<IntentFilterVerificationState>(); 656 657 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 658 new DefaultPermissionGrantPolicy(this); 659 660 // List of packages names to keep cached, even if they are uninstalled for all users 661 private List<String> mKeepUninstalledPackages; 662 663 private static class IFVerificationParams { 664 PackageParser.Package pkg; 665 boolean replacing; 666 int userId; 667 int verifierUid; 668 669 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 670 int _userId, int _verifierUid) { 671 pkg = _pkg; 672 replacing = _replacing; 673 userId = _userId; 674 replacing = _replacing; 675 verifierUid = _verifierUid; 676 } 677 } 678 679 private interface IntentFilterVerifier<T extends IntentFilter> { 680 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 681 T filter, String packageName); 682 void startVerifications(int userId); 683 void receiveVerificationResponse(int verificationId); 684 } 685 686 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 687 private Context mContext; 688 private ComponentName mIntentFilterVerifierComponent; 689 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 690 691 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 692 mContext = context; 693 mIntentFilterVerifierComponent = verifierComponent; 694 } 695 696 private String getDefaultScheme() { 697 return IntentFilter.SCHEME_HTTPS; 698 } 699 700 @Override 701 public void startVerifications(int userId) { 702 // Launch verifications requests 703 int count = mCurrentIntentFilterVerifications.size(); 704 for (int n=0; n<count; n++) { 705 int verificationId = mCurrentIntentFilterVerifications.get(n); 706 final IntentFilterVerificationState ivs = 707 mIntentFilterVerificationStates.get(verificationId); 708 709 String packageName = ivs.getPackageName(); 710 711 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 712 final int filterCount = filters.size(); 713 ArraySet<String> domainsSet = new ArraySet<>(); 714 for (int m=0; m<filterCount; m++) { 715 PackageParser.ActivityIntentInfo filter = filters.get(m); 716 domainsSet.addAll(filter.getHostsList()); 717 } 718 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 719 synchronized (mPackages) { 720 if (mSettings.createIntentFilterVerificationIfNeededLPw( 721 packageName, domainsList) != null) { 722 scheduleWriteSettingsLocked(); 723 } 724 } 725 sendVerificationRequest(userId, verificationId, ivs); 726 } 727 mCurrentIntentFilterVerifications.clear(); 728 } 729 730 private void sendVerificationRequest(int userId, int verificationId, 731 IntentFilterVerificationState ivs) { 732 733 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 734 verificationIntent.putExtra( 735 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 736 verificationId); 737 verificationIntent.putExtra( 738 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 739 getDefaultScheme()); 740 verificationIntent.putExtra( 741 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 742 ivs.getHostsString()); 743 verificationIntent.putExtra( 744 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 745 ivs.getPackageName()); 746 verificationIntent.setComponent(mIntentFilterVerifierComponent); 747 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 748 749 UserHandle user = new UserHandle(userId); 750 mContext.sendBroadcastAsUser(verificationIntent, user); 751 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 752 "Sending IntentFilter verification broadcast"); 753 } 754 755 public void receiveVerificationResponse(int verificationId) { 756 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 757 758 final boolean verified = ivs.isVerified(); 759 760 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 761 final int count = filters.size(); 762 if (DEBUG_DOMAIN_VERIFICATION) { 763 Slog.i(TAG, "Received verification response " + verificationId 764 + " for " + count + " filters, verified=" + verified); 765 } 766 for (int n=0; n<count; n++) { 767 PackageParser.ActivityIntentInfo filter = filters.get(n); 768 filter.setVerified(verified); 769 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 771 + " verified with result:" + verified + " and hosts:" 772 + ivs.getHostsString()); 773 } 774 775 mIntentFilterVerificationStates.remove(verificationId); 776 777 final String packageName = ivs.getPackageName(); 778 IntentFilterVerificationInfo ivi = null; 779 780 synchronized (mPackages) { 781 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 782 } 783 if (ivi == null) { 784 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 785 + verificationId + " packageName:" + packageName); 786 return; 787 } 788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 789 "Updating IntentFilterVerificationInfo for package " + packageName 790 +" verificationId:" + verificationId); 791 792 synchronized (mPackages) { 793 if (verified) { 794 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 795 } else { 796 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 797 } 798 scheduleWriteSettingsLocked(); 799 800 final int userId = ivs.getUserId(); 801 if (userId != UserHandle.USER_ALL) { 802 final int userStatus = 803 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 804 805 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 806 boolean needUpdate = false; 807 808 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 809 // already been set by the User thru the Disambiguation dialog 810 switch (userStatus) { 811 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 812 if (verified) { 813 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 814 } else { 815 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 816 } 817 needUpdate = true; 818 break; 819 820 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 821 if (verified) { 822 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 823 needUpdate = true; 824 } 825 break; 826 827 default: 828 // Nothing to do 829 } 830 831 if (needUpdate) { 832 mSettings.updateIntentFilterVerificationStatusLPw( 833 packageName, updatedStatus, userId); 834 scheduleWritePackageRestrictionsLocked(userId); 835 } 836 } 837 } 838 } 839 840 @Override 841 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 842 ActivityIntentInfo filter, String packageName) { 843 if (!hasValidDomains(filter)) { 844 return false; 845 } 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 if (ivs == null) { 848 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 849 packageName); 850 } 851 if (DEBUG_DOMAIN_VERIFICATION) { 852 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 853 } 854 ivs.addFilter(filter); 855 return true; 856 } 857 858 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 859 int userId, int verificationId, String packageName) { 860 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 861 verifierUid, userId, packageName); 862 ivs.setPendingState(); 863 synchronized (mPackages) { 864 mIntentFilterVerificationStates.append(verificationId, ivs); 865 mCurrentIntentFilterVerifications.add(verificationId); 866 } 867 return ivs; 868 } 869 } 870 871 private static boolean hasValidDomains(ActivityIntentInfo filter) { 872 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 873 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 874 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 875 } 876 877 // Set of pending broadcasts for aggregating enable/disable of components. 878 static class PendingPackageBroadcasts { 879 // for each user id, a map of <package name -> components within that package> 880 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 881 882 public PendingPackageBroadcasts() { 883 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 884 } 885 886 public ArrayList<String> get(int userId, String packageName) { 887 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 888 return packages.get(packageName); 889 } 890 891 public void put(int userId, String packageName, ArrayList<String> components) { 892 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 893 packages.put(packageName, components); 894 } 895 896 public void remove(int userId, String packageName) { 897 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 898 if (packages != null) { 899 packages.remove(packageName); 900 } 901 } 902 903 public void remove(int userId) { 904 mUidMap.remove(userId); 905 } 906 907 public int userIdCount() { 908 return mUidMap.size(); 909 } 910 911 public int userIdAt(int n) { 912 return mUidMap.keyAt(n); 913 } 914 915 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 916 return mUidMap.get(userId); 917 } 918 919 public int size() { 920 // total number of pending broadcast entries across all userIds 921 int num = 0; 922 for (int i = 0; i< mUidMap.size(); i++) { 923 num += mUidMap.valueAt(i).size(); 924 } 925 return num; 926 } 927 928 public void clear() { 929 mUidMap.clear(); 930 } 931 932 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 933 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 934 if (map == null) { 935 map = new ArrayMap<String, ArrayList<String>>(); 936 mUidMap.put(userId, map); 937 } 938 return map; 939 } 940 } 941 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 942 943 // Service Connection to remote media container service to copy 944 // package uri's from external media onto secure containers 945 // or internal storage. 946 private IMediaContainerService mContainerService = null; 947 948 static final int SEND_PENDING_BROADCAST = 1; 949 static final int MCS_BOUND = 3; 950 static final int END_COPY = 4; 951 static final int INIT_COPY = 5; 952 static final int MCS_UNBIND = 6; 953 static final int START_CLEANING_PACKAGE = 7; 954 static final int FIND_INSTALL_LOC = 8; 955 static final int POST_INSTALL = 9; 956 static final int MCS_RECONNECT = 10; 957 static final int MCS_GIVE_UP = 11; 958 static final int UPDATED_MEDIA_STATUS = 12; 959 static final int WRITE_SETTINGS = 13; 960 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 961 static final int PACKAGE_VERIFIED = 15; 962 static final int CHECK_PENDING_VERIFICATION = 16; 963 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 964 static final int INTENT_FILTER_VERIFIED = 18; 965 966 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 967 968 // Delay time in millisecs 969 static final int BROADCAST_DELAY = 10 * 1000; 970 971 static UserManagerService sUserManager; 972 973 // Stores a list of users whose package restrictions file needs to be updated 974 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 975 976 final private DefaultContainerConnection mDefContainerConn = 977 new DefaultContainerConnection(); 978 class DefaultContainerConnection implements ServiceConnection { 979 public void onServiceConnected(ComponentName name, IBinder service) { 980 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 981 IMediaContainerService imcs = 982 IMediaContainerService.Stub.asInterface(service); 983 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 984 } 985 986 public void onServiceDisconnected(ComponentName name) { 987 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 988 } 989 } 990 991 // Recordkeeping of restore-after-install operations that are currently in flight 992 // between the Package Manager and the Backup Manager 993 static class PostInstallData { 994 public InstallArgs args; 995 public PackageInstalledInfo res; 996 997 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 998 args = _a; 999 res = _r; 1000 } 1001 } 1002 1003 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1004 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1005 1006 // XML tags for backup/restore of various bits of state 1007 private static final String TAG_PREFERRED_BACKUP = "pa"; 1008 private static final String TAG_DEFAULT_APPS = "da"; 1009 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1010 1011 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1012 private static final String TAG_ALL_GRANTS = "rt-grants"; 1013 private static final String TAG_GRANT = "grant"; 1014 private static final String ATTR_PACKAGE_NAME = "pkg"; 1015 1016 private static final String TAG_PERMISSION = "perm"; 1017 private static final String ATTR_PERMISSION_NAME = "name"; 1018 private static final String ATTR_IS_GRANTED = "g"; 1019 private static final String ATTR_USER_SET = "set"; 1020 private static final String ATTR_USER_FIXED = "fixed"; 1021 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1022 1023 // System/policy permission grants are not backed up 1024 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1025 FLAG_PERMISSION_POLICY_FIXED 1026 | FLAG_PERMISSION_SYSTEM_FIXED 1027 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1028 1029 // And we back up these user-adjusted states 1030 private static final int USER_RUNTIME_GRANT_MASK = 1031 FLAG_PERMISSION_USER_SET 1032 | FLAG_PERMISSION_USER_FIXED 1033 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1034 1035 final @Nullable String mRequiredVerifierPackage; 1036 final @Nullable String mRequiredInstallerPackage; 1037 1038 private final PackageUsage mPackageUsage = new PackageUsage(); 1039 1040 private class PackageUsage { 1041 private static final int WRITE_INTERVAL 1042 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1043 1044 private final Object mFileLock = new Object(); 1045 private final AtomicLong mLastWritten = new AtomicLong(0); 1046 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1047 1048 private boolean mIsHistoricalPackageUsageAvailable = true; 1049 1050 boolean isHistoricalPackageUsageAvailable() { 1051 return mIsHistoricalPackageUsageAvailable; 1052 } 1053 1054 void write(boolean force) { 1055 if (force) { 1056 writeInternal(); 1057 return; 1058 } 1059 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1060 && !DEBUG_DEXOPT) { 1061 return; 1062 } 1063 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1064 new Thread("PackageUsage_DiskWriter") { 1065 @Override 1066 public void run() { 1067 try { 1068 writeInternal(); 1069 } finally { 1070 mBackgroundWriteRunning.set(false); 1071 } 1072 } 1073 }.start(); 1074 } 1075 } 1076 1077 private void writeInternal() { 1078 synchronized (mPackages) { 1079 synchronized (mFileLock) { 1080 AtomicFile file = getFile(); 1081 FileOutputStream f = null; 1082 try { 1083 f = file.startWrite(); 1084 BufferedOutputStream out = new BufferedOutputStream(f); 1085 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1086 StringBuilder sb = new StringBuilder(); 1087 for (PackageParser.Package pkg : mPackages.values()) { 1088 if (pkg.mLastPackageUsageTimeInMills == 0) { 1089 continue; 1090 } 1091 sb.setLength(0); 1092 sb.append(pkg.packageName); 1093 sb.append(' '); 1094 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1095 sb.append('\n'); 1096 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1097 } 1098 out.flush(); 1099 file.finishWrite(f); 1100 } catch (IOException e) { 1101 if (f != null) { 1102 file.failWrite(f); 1103 } 1104 Log.e(TAG, "Failed to write package usage times", e); 1105 } 1106 } 1107 } 1108 mLastWritten.set(SystemClock.elapsedRealtime()); 1109 } 1110 1111 void readLP() { 1112 synchronized (mFileLock) { 1113 AtomicFile file = getFile(); 1114 BufferedInputStream in = null; 1115 try { 1116 in = new BufferedInputStream(file.openRead()); 1117 StringBuffer sb = new StringBuffer(); 1118 while (true) { 1119 String packageName = readToken(in, sb, ' '); 1120 if (packageName == null) { 1121 break; 1122 } 1123 String timeInMillisString = readToken(in, sb, '\n'); 1124 if (timeInMillisString == null) { 1125 throw new IOException("Failed to find last usage time for package " 1126 + packageName); 1127 } 1128 PackageParser.Package pkg = mPackages.get(packageName); 1129 if (pkg == null) { 1130 continue; 1131 } 1132 long timeInMillis; 1133 try { 1134 timeInMillis = Long.parseLong(timeInMillisString); 1135 } catch (NumberFormatException e) { 1136 throw new IOException("Failed to parse " + timeInMillisString 1137 + " as a long.", e); 1138 } 1139 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1140 } 1141 } catch (FileNotFoundException expected) { 1142 mIsHistoricalPackageUsageAvailable = false; 1143 } catch (IOException e) { 1144 Log.w(TAG, "Failed to read package usage times", e); 1145 } finally { 1146 IoUtils.closeQuietly(in); 1147 } 1148 } 1149 mLastWritten.set(SystemClock.elapsedRealtime()); 1150 } 1151 1152 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1153 throws IOException { 1154 sb.setLength(0); 1155 while (true) { 1156 int ch = in.read(); 1157 if (ch == -1) { 1158 if (sb.length() == 0) { 1159 return null; 1160 } 1161 throw new IOException("Unexpected EOF"); 1162 } 1163 if (ch == endOfToken) { 1164 return sb.toString(); 1165 } 1166 sb.append((char)ch); 1167 } 1168 } 1169 1170 private AtomicFile getFile() { 1171 File dataDir = Environment.getDataDirectory(); 1172 File systemDir = new File(dataDir, "system"); 1173 File fname = new File(systemDir, "package-usage.list"); 1174 return new AtomicFile(fname); 1175 } 1176 } 1177 1178 class PackageHandler extends Handler { 1179 private boolean mBound = false; 1180 final ArrayList<HandlerParams> mPendingInstalls = 1181 new ArrayList<HandlerParams>(); 1182 1183 private boolean connectToService() { 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1185 " DefaultContainerService"); 1186 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1187 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1188 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1189 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1190 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1191 mBound = true; 1192 return true; 1193 } 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1195 return false; 1196 } 1197 1198 private void disconnectService() { 1199 mContainerService = null; 1200 mBound = false; 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1202 mContext.unbindService(mDefContainerConn); 1203 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1204 } 1205 1206 PackageHandler(Looper looper) { 1207 super(looper); 1208 } 1209 1210 public void handleMessage(Message msg) { 1211 try { 1212 doHandleMessage(msg); 1213 } finally { 1214 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1215 } 1216 } 1217 1218 void doHandleMessage(Message msg) { 1219 switch (msg.what) { 1220 case INIT_COPY: { 1221 HandlerParams params = (HandlerParams) msg.obj; 1222 int idx = mPendingInstalls.size(); 1223 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1224 // If a bind was already initiated we dont really 1225 // need to do anything. The pending install 1226 // will be processed later on. 1227 if (!mBound) { 1228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1229 System.identityHashCode(mHandler)); 1230 // If this is the only one pending we might 1231 // have to bind to the service again. 1232 if (!connectToService()) { 1233 Slog.e(TAG, "Failed to bind to media container service"); 1234 params.serviceError(); 1235 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1236 System.identityHashCode(mHandler)); 1237 if (params.traceMethod != null) { 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1239 params.traceCookie); 1240 } 1241 return; 1242 } else { 1243 // Once we bind to the service, the first 1244 // pending request will be processed. 1245 mPendingInstalls.add(idx, params); 1246 } 1247 } else { 1248 mPendingInstalls.add(idx, params); 1249 // Already bound to the service. Just make 1250 // sure we trigger off processing the first request. 1251 if (idx == 0) { 1252 mHandler.sendEmptyMessage(MCS_BOUND); 1253 } 1254 } 1255 break; 1256 } 1257 case MCS_BOUND: { 1258 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1259 if (msg.obj != null) { 1260 mContainerService = (IMediaContainerService) msg.obj; 1261 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1262 System.identityHashCode(mHandler)); 1263 } 1264 if (mContainerService == null) { 1265 if (!mBound) { 1266 // Something seriously wrong since we are not bound and we are not 1267 // waiting for connection. Bail out. 1268 Slog.e(TAG, "Cannot bind to media container service"); 1269 for (HandlerParams params : mPendingInstalls) { 1270 // Indicate service bind error 1271 params.serviceError(); 1272 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1273 System.identityHashCode(params)); 1274 if (params.traceMethod != null) { 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1276 params.traceMethod, params.traceCookie); 1277 } 1278 return; 1279 } 1280 mPendingInstalls.clear(); 1281 } else { 1282 Slog.w(TAG, "Waiting to connect to media container service"); 1283 } 1284 } else if (mPendingInstalls.size() > 0) { 1285 HandlerParams params = mPendingInstalls.get(0); 1286 if (params != null) { 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1288 System.identityHashCode(params)); 1289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1290 if (params.startCopy()) { 1291 // We are done... look for more work or to 1292 // go idle. 1293 if (DEBUG_SD_INSTALL) Log.i(TAG, 1294 "Checking for more work or unbind..."); 1295 // Delete pending install 1296 if (mPendingInstalls.size() > 0) { 1297 mPendingInstalls.remove(0); 1298 } 1299 if (mPendingInstalls.size() == 0) { 1300 if (mBound) { 1301 if (DEBUG_SD_INSTALL) Log.i(TAG, 1302 "Posting delayed MCS_UNBIND"); 1303 removeMessages(MCS_UNBIND); 1304 Message ubmsg = obtainMessage(MCS_UNBIND); 1305 // Unbind after a little delay, to avoid 1306 // continual thrashing. 1307 sendMessageDelayed(ubmsg, 10000); 1308 } 1309 } else { 1310 // There are more pending requests in queue. 1311 // Just post MCS_BOUND message to trigger processing 1312 // of next pending install. 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, 1314 "Posting MCS_BOUND for next work"); 1315 mHandler.sendEmptyMessage(MCS_BOUND); 1316 } 1317 } 1318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1319 } 1320 } else { 1321 // Should never happen ideally. 1322 Slog.w(TAG, "Empty queue"); 1323 } 1324 break; 1325 } 1326 case MCS_RECONNECT: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1328 if (mPendingInstalls.size() > 0) { 1329 if (mBound) { 1330 disconnectService(); 1331 } 1332 if (!connectToService()) { 1333 Slog.e(TAG, "Failed to bind to media container service"); 1334 for (HandlerParams params : mPendingInstalls) { 1335 // Indicate service bind error 1336 params.serviceError(); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 } 1340 mPendingInstalls.clear(); 1341 } 1342 } 1343 break; 1344 } 1345 case MCS_UNBIND: { 1346 // If there is no actual work left, then time to unbind. 1347 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1348 1349 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1350 if (mBound) { 1351 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1352 1353 disconnectService(); 1354 } 1355 } else if (mPendingInstalls.size() > 0) { 1356 // There are more pending requests in queue. 1357 // Just post MCS_BOUND message to trigger processing 1358 // of next pending install. 1359 mHandler.sendEmptyMessage(MCS_BOUND); 1360 } 1361 1362 break; 1363 } 1364 case MCS_GIVE_UP: { 1365 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1366 HandlerParams params = mPendingInstalls.remove(0); 1367 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1368 System.identityHashCode(params)); 1369 break; 1370 } 1371 case SEND_PENDING_BROADCAST: { 1372 String packages[]; 1373 ArrayList<String> components[]; 1374 int size = 0; 1375 int uids[]; 1376 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1377 synchronized (mPackages) { 1378 if (mPendingBroadcasts == null) { 1379 return; 1380 } 1381 size = mPendingBroadcasts.size(); 1382 if (size <= 0) { 1383 // Nothing to be done. Just return 1384 return; 1385 } 1386 packages = new String[size]; 1387 components = new ArrayList[size]; 1388 uids = new int[size]; 1389 int i = 0; // filling out the above arrays 1390 1391 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1392 int packageUserId = mPendingBroadcasts.userIdAt(n); 1393 Iterator<Map.Entry<String, ArrayList<String>>> it 1394 = mPendingBroadcasts.packagesForUserId(packageUserId) 1395 .entrySet().iterator(); 1396 while (it.hasNext() && i < size) { 1397 Map.Entry<String, ArrayList<String>> ent = it.next(); 1398 packages[i] = ent.getKey(); 1399 components[i] = ent.getValue(); 1400 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1401 uids[i] = (ps != null) 1402 ? UserHandle.getUid(packageUserId, ps.appId) 1403 : -1; 1404 i++; 1405 } 1406 } 1407 size = i; 1408 mPendingBroadcasts.clear(); 1409 } 1410 // Send broadcasts 1411 for (int i = 0; i < size; i++) { 1412 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 break; 1416 } 1417 case START_CLEANING_PACKAGE: { 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1419 final String packageName = (String)msg.obj; 1420 final int userId = msg.arg1; 1421 final boolean andCode = msg.arg2 != 0; 1422 synchronized (mPackages) { 1423 if (userId == UserHandle.USER_ALL) { 1424 int[] users = sUserManager.getUserIds(); 1425 for (int user : users) { 1426 mSettings.addPackageToCleanLPw( 1427 new PackageCleanItem(user, packageName, andCode)); 1428 } 1429 } else { 1430 mSettings.addPackageToCleanLPw( 1431 new PackageCleanItem(userId, packageName, andCode)); 1432 } 1433 } 1434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1435 startCleaningPackages(); 1436 } break; 1437 case POST_INSTALL: { 1438 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1439 1440 PostInstallData data = mRunningInstalls.get(msg.arg1); 1441 mRunningInstalls.delete(msg.arg1); 1442 1443 if (data != null) { 1444 InstallArgs args = data.args; 1445 PackageInstalledInfo parentRes = data.res; 1446 1447 final boolean grantPermissions = (args.installFlags 1448 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1449 final boolean killApp = (args.installFlags 1450 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1451 final String[] grantedPermissions = args.installGrantPermissions; 1452 1453 // Handle the parent package 1454 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1455 grantedPermissions, args.observer); 1456 1457 // Handle the child packages 1458 final int childCount = (parentRes.addedChildPackages != null) 1459 ? parentRes.addedChildPackages.size() : 0; 1460 for (int i = 0; i < childCount; i++) { 1461 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1462 handlePackagePostInstall(childRes, grantPermissions, killApp, 1463 grantedPermissions, args.observer); 1464 } 1465 1466 // Log tracing if needed 1467 if (args.traceMethod != null) { 1468 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1469 args.traceCookie); 1470 } 1471 } else { 1472 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1473 } 1474 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1476 } break; 1477 case UPDATED_MEDIA_STATUS: { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1479 boolean reportStatus = msg.arg1 == 1; 1480 boolean doGc = msg.arg2 == 1; 1481 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1482 if (doGc) { 1483 // Force a gc to clear up stale containers. 1484 Runtime.getRuntime().gc(); 1485 } 1486 if (msg.obj != null) { 1487 @SuppressWarnings("unchecked") 1488 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1490 // Unload containers 1491 unloadAllContainers(args); 1492 } 1493 if (reportStatus) { 1494 try { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1496 PackageHelper.getMountService().finishMediaUpdate(); 1497 } catch (RemoteException e) { 1498 Log.e(TAG, "MountService not running?"); 1499 } 1500 } 1501 } break; 1502 case WRITE_SETTINGS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_SETTINGS); 1506 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1507 mSettings.writeLPr(); 1508 mDirtyUsers.clear(); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case WRITE_PACKAGE_RESTRICTIONS: { 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1514 synchronized (mPackages) { 1515 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1516 for (int userId : mDirtyUsers) { 1517 mSettings.writePackageRestrictionsLPr(userId); 1518 } 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case CHECK_PENDING_VERIFICATION: { 1524 final int verificationId = msg.arg1; 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 1527 if ((state != null) && !state.timeoutExtended()) { 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 Slog.i(TAG, "Verification timed out for " + originUri); 1532 mPendingVerification.remove(verificationId); 1533 1534 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1535 1536 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1537 Slog.i(TAG, "Continuing with installation of " + originUri); 1538 state.setVerifierResponse(Binder.getCallingUid(), 1539 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1540 broadcastPackageVerified(verificationId, originUri, 1541 PackageManager.VERIFICATION_ALLOW, 1542 state.getInstallArgs().getUser()); 1543 try { 1544 ret = args.copyApk(mContainerService, true); 1545 } catch (RemoteException e) { 1546 Slog.e(TAG, "Could not contact the ContainerService"); 1547 } 1548 } else { 1549 broadcastPackageVerified(verificationId, originUri, 1550 PackageManager.VERIFICATION_REJECT, 1551 state.getInstallArgs().getUser()); 1552 } 1553 1554 Trace.asyncTraceEnd( 1555 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1556 1557 processPendingInstall(args, ret); 1558 mHandler.sendEmptyMessage(MCS_UNBIND); 1559 } 1560 break; 1561 } 1562 case PACKAGE_VERIFIED: { 1563 final int verificationId = msg.arg1; 1564 1565 final PackageVerificationState state = mPendingVerification.get(verificationId); 1566 if (state == null) { 1567 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1568 break; 1569 } 1570 1571 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1572 1573 state.setVerifierResponse(response.callerUid, response.code); 1574 1575 if (state.isVerificationComplete()) { 1576 mPendingVerification.remove(verificationId); 1577 1578 final InstallArgs args = state.getInstallArgs(); 1579 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1580 1581 int ret; 1582 if (state.isInstallAllowed()) { 1583 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1584 broadcastPackageVerified(verificationId, originUri, 1585 response.code, state.getInstallArgs().getUser()); 1586 try { 1587 ret = args.copyApk(mContainerService, true); 1588 } catch (RemoteException e) { 1589 Slog.e(TAG, "Could not contact the ContainerService"); 1590 } 1591 } else { 1592 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1593 } 1594 1595 Trace.asyncTraceEnd( 1596 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1597 1598 processPendingInstall(args, ret); 1599 mHandler.sendEmptyMessage(MCS_UNBIND); 1600 } 1601 1602 break; 1603 } 1604 case START_INTENT_FILTER_VERIFICATIONS: { 1605 IFVerificationParams params = (IFVerificationParams) msg.obj; 1606 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1607 params.replacing, params.pkg); 1608 break; 1609 } 1610 case INTENT_FILTER_VERIFIED: { 1611 final int verificationId = msg.arg1; 1612 1613 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1614 verificationId); 1615 if (state == null) { 1616 Slog.w(TAG, "Invalid IntentFilter verification token " 1617 + verificationId + " received"); 1618 break; 1619 } 1620 1621 final int userId = state.getUserId(); 1622 1623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1624 "Processing IntentFilter verification with token:" 1625 + verificationId + " and userId:" + userId); 1626 1627 final IntentFilterVerificationResponse response = 1628 (IntentFilterVerificationResponse) msg.obj; 1629 1630 state.setVerifierResponse(response.callerUid, response.code); 1631 1632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1633 "IntentFilter verification with token:" + verificationId 1634 + " and userId:" + userId 1635 + " is settings verifier response with response code:" 1636 + response.code); 1637 1638 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1640 + response.getFailedDomainsString()); 1641 } 1642 1643 if (state.isVerificationComplete()) { 1644 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1645 } else { 1646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1647 "IntentFilter verification with token:" + verificationId 1648 + " was not said to be complete"); 1649 } 1650 1651 break; 1652 } 1653 } 1654 } 1655 } 1656 1657 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1658 boolean killApp, String[] grantedPermissions, 1659 IPackageInstallObserver2 installObserver) { 1660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1661 // Send the removed broadcasts 1662 if (res.removedInfo != null) { 1663 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1664 } 1665 1666 // Now that we successfully installed the package, grant runtime 1667 // permissions if requested before broadcasting the install. 1668 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1669 >= Build.VERSION_CODES.M) { 1670 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1671 } 1672 1673 final boolean update = res.removedInfo != null 1674 && res.removedInfo.removedPackage != null; 1675 1676 // If this is the first time we have child packages for a disabled privileged 1677 // app that had no children, we grant requested runtime permissions to the new 1678 // children if the parent on the system image had them already granted. 1679 if (res.pkg.parentPackage != null) { 1680 synchronized (mPackages) { 1681 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1682 } 1683 } 1684 1685 synchronized (mPackages) { 1686 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1687 } 1688 1689 final String packageName = res.pkg.applicationInfo.packageName; 1690 Bundle extras = new Bundle(1); 1691 extras.putInt(Intent.EXTRA_UID, res.uid); 1692 1693 // Determine the set of users who are adding this package for 1694 // the first time vs. those who are seeing an update. 1695 int[] firstUsers = EMPTY_INT_ARRAY; 1696 int[] updateUsers = EMPTY_INT_ARRAY; 1697 if (res.origUsers == null || res.origUsers.length == 0) { 1698 firstUsers = res.newUsers; 1699 } else { 1700 for (int newUser : res.newUsers) { 1701 boolean isNew = true; 1702 for (int origUser : res.origUsers) { 1703 if (origUser == newUser) { 1704 isNew = false; 1705 break; 1706 } 1707 } 1708 if (isNew) { 1709 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1710 } else { 1711 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1712 } 1713 } 1714 } 1715 1716 // Send installed broadcasts if the install/update is not ephemeral 1717 if (!isEphemeral(res.pkg)) { 1718 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1719 1720 // Send added for users that see the package for the first time 1721 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1722 extras, 0 /*flags*/, null /*targetPackage*/, 1723 null /*finishedReceiver*/, firstUsers); 1724 1725 // Send added for users that don't see the package for the first time 1726 if (update) { 1727 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1728 } 1729 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1730 extras, 0 /*flags*/, null /*targetPackage*/, 1731 null /*finishedReceiver*/, updateUsers); 1732 1733 // Send replaced for users that don't see the package for the first time 1734 if (update) { 1735 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1736 packageName, extras, 0 /*flags*/, 1737 null /*targetPackage*/, null /*finishedReceiver*/, 1738 updateUsers); 1739 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1740 null /*package*/, null /*extras*/, 0 /*flags*/, 1741 packageName /*targetPackage*/, 1742 null /*finishedReceiver*/, updateUsers); 1743 } 1744 1745 // Send broadcast package appeared if forward locked/external for all users 1746 // treat asec-hosted packages like removable media on upgrade 1747 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1748 if (DEBUG_INSTALL) { 1749 Slog.i(TAG, "upgrading pkg " + res.pkg 1750 + " is ASEC-hosted -> AVAILABLE"); 1751 } 1752 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1753 ArrayList<String> pkgList = new ArrayList<>(1); 1754 pkgList.add(packageName); 1755 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1756 } 1757 } 1758 1759 // Work that needs to happen on first install within each user 1760 if (firstUsers != null && firstUsers.length > 0) { 1761 synchronized (mPackages) { 1762 for (int userId : firstUsers) { 1763 // If this app is a browser and it's newly-installed for some 1764 // users, clear any default-browser state in those users. The 1765 // app's nature doesn't depend on the user, so we can just check 1766 // its browser nature in any user and generalize. 1767 if (packageIsBrowser(packageName, userId)) { 1768 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1769 } 1770 1771 // We may also need to apply pending (restored) runtime 1772 // permission grants within these users. 1773 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1774 } 1775 } 1776 } 1777 1778 // Log current value of "unknown sources" setting 1779 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1780 getUnknownSourcesSettings()); 1781 1782 // Force a gc to clear up things 1783 Runtime.getRuntime().gc(); 1784 1785 // Remove the replaced package's older resources safely now 1786 // We delete after a gc for applications on sdcard. 1787 if (res.removedInfo != null && res.removedInfo.args != null) { 1788 synchronized (mInstallLock) { 1789 res.removedInfo.args.doPostDeleteLI(true); 1790 } 1791 } 1792 } 1793 1794 // If someone is watching installs - notify them 1795 if (installObserver != null) { 1796 try { 1797 Bundle extras = extrasForInstallResult(res); 1798 installObserver.onPackageInstalled(res.name, res.returnCode, 1799 res.returnMsg, extras); 1800 } catch (RemoteException e) { 1801 Slog.i(TAG, "Observer no longer exists."); 1802 } 1803 } 1804 } 1805 1806 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1807 PackageParser.Package pkg) { 1808 if (pkg.parentPackage == null) { 1809 return; 1810 } 1811 if (pkg.requestedPermissions == null) { 1812 return; 1813 } 1814 final PackageSetting disabledSysParentPs = mSettings 1815 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1816 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1817 || !disabledSysParentPs.isPrivileged() 1818 || (disabledSysParentPs.childPackageNames != null 1819 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1820 return; 1821 } 1822 final int[] allUserIds = sUserManager.getUserIds(); 1823 final int permCount = pkg.requestedPermissions.size(); 1824 for (int i = 0; i < permCount; i++) { 1825 String permission = pkg.requestedPermissions.get(i); 1826 BasePermission bp = mSettings.mPermissions.get(permission); 1827 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1828 continue; 1829 } 1830 for (int userId : allUserIds) { 1831 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1832 permission, userId)) { 1833 grantRuntimePermission(pkg.packageName, permission, userId); 1834 } 1835 } 1836 } 1837 } 1838 1839 private StorageEventListener mStorageListener = new StorageEventListener() { 1840 @Override 1841 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1842 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1843 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1844 final String volumeUuid = vol.getFsUuid(); 1845 1846 // Clean up any users or apps that were removed or recreated 1847 // while this volume was missing 1848 reconcileUsers(volumeUuid); 1849 reconcileApps(volumeUuid); 1850 1851 // Clean up any install sessions that expired or were 1852 // cancelled while this volume was missing 1853 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1854 1855 loadPrivatePackages(vol); 1856 1857 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1858 unloadPrivatePackages(vol); 1859 } 1860 } 1861 1862 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1863 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1864 updateExternalMediaStatus(true, false); 1865 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1866 updateExternalMediaStatus(false, false); 1867 } 1868 } 1869 } 1870 1871 @Override 1872 public void onVolumeForgotten(String fsUuid) { 1873 if (TextUtils.isEmpty(fsUuid)) { 1874 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1875 return; 1876 } 1877 1878 // Remove any apps installed on the forgotten volume 1879 synchronized (mPackages) { 1880 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1881 for (PackageSetting ps : packages) { 1882 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1883 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1884 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1885 } 1886 1887 mSettings.onVolumeForgotten(fsUuid); 1888 mSettings.writeLPr(); 1889 } 1890 } 1891 }; 1892 1893 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1894 String[] grantedPermissions) { 1895 for (int userId : userIds) { 1896 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1897 } 1898 1899 // We could have touched GID membership, so flush out packages.list 1900 synchronized (mPackages) { 1901 mSettings.writePackageListLPr(); 1902 } 1903 } 1904 1905 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1906 String[] grantedPermissions) { 1907 SettingBase sb = (SettingBase) pkg.mExtras; 1908 if (sb == null) { 1909 return; 1910 } 1911 1912 PermissionsState permissionsState = sb.getPermissionsState(); 1913 1914 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1915 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1916 1917 synchronized (mPackages) { 1918 for (String permission : pkg.requestedPermissions) { 1919 BasePermission bp = mSettings.mPermissions.get(permission); 1920 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1921 && (grantedPermissions == null 1922 || ArrayUtils.contains(grantedPermissions, permission))) { 1923 final int flags = permissionsState.getPermissionFlags(permission, userId); 1924 // Installer cannot change immutable permissions. 1925 if ((flags & immutableFlags) == 0) { 1926 grantRuntimePermission(pkg.packageName, permission, userId); 1927 } 1928 } 1929 } 1930 } 1931 } 1932 1933 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1934 Bundle extras = null; 1935 switch (res.returnCode) { 1936 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1937 extras = new Bundle(); 1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1939 res.origPermission); 1940 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1941 res.origPackage); 1942 break; 1943 } 1944 case PackageManager.INSTALL_SUCCEEDED: { 1945 extras = new Bundle(); 1946 extras.putBoolean(Intent.EXTRA_REPLACING, 1947 res.removedInfo != null && res.removedInfo.removedPackage != null); 1948 break; 1949 } 1950 } 1951 return extras; 1952 } 1953 1954 void scheduleWriteSettingsLocked() { 1955 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1956 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1957 } 1958 } 1959 1960 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1961 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1962 scheduleWritePackageRestrictionsLocked(userId); 1963 } 1964 1965 void scheduleWritePackageRestrictionsLocked(int userId) { 1966 final int[] userIds = (userId == UserHandle.USER_ALL) 1967 ? sUserManager.getUserIds() : new int[]{userId}; 1968 for (int nextUserId : userIds) { 1969 if (!sUserManager.exists(nextUserId)) return; 1970 mDirtyUsers.add(nextUserId); 1971 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1972 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1973 } 1974 } 1975 } 1976 1977 public static PackageManagerService main(Context context, Installer installer, 1978 boolean factoryTest, boolean onlyCore) { 1979 // Self-check for initial settings. 1980 PackageManagerServiceCompilerMapping.checkProperties(); 1981 1982 PackageManagerService m = new PackageManagerService(context, installer, 1983 factoryTest, onlyCore); 1984 m.enableSystemUserPackages(); 1985 ServiceManager.addService("package", m); 1986 return m; 1987 } 1988 1989 private void enableSystemUserPackages() { 1990 if (!UserManager.isSplitSystemUser()) { 1991 return; 1992 } 1993 // For system user, enable apps based on the following conditions: 1994 // - app is whitelisted or belong to one of these groups: 1995 // -- system app which has no launcher icons 1996 // -- system app which has INTERACT_ACROSS_USERS permission 1997 // -- system IME app 1998 // - app is not in the blacklist 1999 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2000 Set<String> enableApps = new ArraySet<>(); 2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2002 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2003 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2004 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2005 enableApps.addAll(wlApps); 2006 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2007 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2008 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2009 enableApps.removeAll(blApps); 2010 Log.i(TAG, "Applications installed for system user: " + enableApps); 2011 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2012 UserHandle.SYSTEM); 2013 final int allAppsSize = allAps.size(); 2014 synchronized (mPackages) { 2015 for (int i = 0; i < allAppsSize; i++) { 2016 String pName = allAps.get(i); 2017 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2018 // Should not happen, but we shouldn't be failing if it does 2019 if (pkgSetting == null) { 2020 continue; 2021 } 2022 boolean install = enableApps.contains(pName); 2023 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2024 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2025 + " for system user"); 2026 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2027 } 2028 } 2029 } 2030 } 2031 2032 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2033 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2034 Context.DISPLAY_SERVICE); 2035 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2036 } 2037 2038 public PackageManagerService(Context context, Installer installer, 2039 boolean factoryTest, boolean onlyCore) { 2040 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2041 SystemClock.uptimeMillis()); 2042 2043 if (mSdkVersion <= 0) { 2044 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2045 } 2046 2047 mContext = context; 2048 mFactoryTest = factoryTest; 2049 mOnlyCore = onlyCore; 2050 mMetrics = new DisplayMetrics(); 2051 mSettings = new Settings(mPackages); 2052 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2053 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2054 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2055 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2056 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2057 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2058 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2059 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2060 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2061 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2062 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2063 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2064 2065 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2066 if (separateProcesses != null && separateProcesses.length() > 0) { 2067 if ("*".equals(separateProcesses)) { 2068 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2069 mSeparateProcesses = null; 2070 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2071 } else { 2072 mDefParseFlags = 0; 2073 mSeparateProcesses = separateProcesses.split(","); 2074 Slog.w(TAG, "Running with debug.separate_processes: " 2075 + separateProcesses); 2076 } 2077 } else { 2078 mDefParseFlags = 0; 2079 mSeparateProcesses = null; 2080 } 2081 2082 mInstaller = installer; 2083 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2084 "*dexopt*"); 2085 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2086 2087 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2088 FgThread.get().getLooper()); 2089 2090 getDefaultDisplayMetrics(context, mMetrics); 2091 2092 SystemConfig systemConfig = SystemConfig.getInstance(); 2093 mGlobalGids = systemConfig.getGlobalGids(); 2094 mSystemPermissions = systemConfig.getSystemPermissions(); 2095 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2096 2097 synchronized (mInstallLock) { 2098 // writer 2099 synchronized (mPackages) { 2100 mHandlerThread = new ServiceThread(TAG, 2101 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2102 mHandlerThread.start(); 2103 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2104 mProcessLoggingHandler = new ProcessLoggingHandler(); 2105 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2106 2107 File dataDir = Environment.getDataDirectory(); 2108 mAppInstallDir = new File(dataDir, "app"); 2109 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2110 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2111 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2112 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2113 2114 sUserManager = new UserManagerService(context, this, mPackages); 2115 2116 // Propagate permission configuration in to package manager. 2117 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2118 = systemConfig.getPermissions(); 2119 for (int i=0; i<permConfig.size(); i++) { 2120 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2121 BasePermission bp = mSettings.mPermissions.get(perm.name); 2122 if (bp == null) { 2123 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2124 mSettings.mPermissions.put(perm.name, bp); 2125 } 2126 if (perm.gids != null) { 2127 bp.setGids(perm.gids, perm.perUser); 2128 } 2129 } 2130 2131 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2132 for (int i=0; i<libConfig.size(); i++) { 2133 mSharedLibraries.put(libConfig.keyAt(i), 2134 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2135 } 2136 2137 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2138 2139 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2140 2141 String customResolverActivity = Resources.getSystem().getString( 2142 R.string.config_customResolverActivity); 2143 if (TextUtils.isEmpty(customResolverActivity)) { 2144 customResolverActivity = null; 2145 } else { 2146 mCustomResolverComponentName = ComponentName.unflattenFromString( 2147 customResolverActivity); 2148 } 2149 2150 long startTime = SystemClock.uptimeMillis(); 2151 2152 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2153 startTime); 2154 2155 // Set flag to monitor and not change apk file paths when 2156 // scanning install directories. 2157 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2158 2159 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2160 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2161 2162 if (bootClassPath == null) { 2163 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2164 } 2165 2166 if (systemServerClassPath == null) { 2167 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2168 } 2169 2170 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2171 final String[] dexCodeInstructionSets = 2172 getDexCodeInstructionSets( 2173 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2174 2175 /** 2176 * Ensure all external libraries have had dexopt run on them. 2177 */ 2178 if (mSharedLibraries.size() > 0) { 2179 // NOTE: For now, we're compiling these system "shared libraries" 2180 // (and framework jars) into all available architectures. It's possible 2181 // to compile them only when we come across an app that uses them (there's 2182 // already logic for that in scanPackageLI) but that adds some complexity. 2183 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2184 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2185 final String lib = libEntry.path; 2186 if (lib == null) { 2187 continue; 2188 } 2189 2190 try { 2191 // Shared libraries do not have profiles so we perform a full 2192 // AOT compilation (if needed). 2193 int dexoptNeeded = DexFile.getDexOptNeeded( 2194 lib, dexCodeInstructionSet, 2195 getCompilerFilterForReason(REASON_SHARED_APK), 2196 false /* newProfile */); 2197 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2198 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2199 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2200 getCompilerFilterForReason(REASON_SHARED_APK), 2201 StorageManager.UUID_PRIVATE_INTERNAL); 2202 } 2203 } catch (FileNotFoundException e) { 2204 Slog.w(TAG, "Library not found: " + lib); 2205 } catch (IOException | InstallerException e) { 2206 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2207 + e.getMessage()); 2208 } 2209 } 2210 } 2211 } 2212 2213 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2214 2215 final VersionInfo ver = mSettings.getInternalVersion(); 2216 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2217 2218 // when upgrading from pre-M, promote system app permissions from install to runtime 2219 mPromoteSystemApps = 2220 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2221 2222 // save off the names of pre-existing system packages prior to scanning; we don't 2223 // want to automatically grant runtime permissions for new system apps 2224 if (mPromoteSystemApps) { 2225 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2226 while (pkgSettingIter.hasNext()) { 2227 PackageSetting ps = pkgSettingIter.next(); 2228 if (isSystemApp(ps)) { 2229 mExistingSystemPackages.add(ps.name); 2230 } 2231 } 2232 } 2233 2234 // When upgrading from pre-N, we need to handle package extraction like first boot, 2235 // as there is no profiling data available. 2236 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2237 mSettings.setNWorkDone(); 2238 2239 // Collect vendor overlay packages. 2240 // (Do this before scanning any apps.) 2241 // For security and version matching reason, only consider 2242 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2243 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2244 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2245 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2246 2247 // Find base frameworks (resource packages without code). 2248 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR 2250 | PackageParser.PARSE_IS_PRIVILEGED, 2251 scanFlags | SCAN_NO_DEX, 0); 2252 2253 // Collected privileged system packages. 2254 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2255 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2256 | PackageParser.PARSE_IS_SYSTEM_DIR 2257 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2258 2259 // Collect ordinary system packages. 2260 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2261 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2262 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2263 2264 // Collect all vendor packages. 2265 File vendorAppDir = new File("/vendor/app"); 2266 try { 2267 vendorAppDir = vendorAppDir.getCanonicalFile(); 2268 } catch (IOException e) { 2269 // failed to look up canonical path, continue with original one 2270 } 2271 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2272 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2273 2274 // Collect all OEM packages. 2275 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2276 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2278 2279 // Prune any system packages that no longer exist. 2280 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2281 if (!mOnlyCore) { 2282 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2283 while (psit.hasNext()) { 2284 PackageSetting ps = psit.next(); 2285 2286 /* 2287 * If this is not a system app, it can't be a 2288 * disable system app. 2289 */ 2290 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2291 continue; 2292 } 2293 2294 /* 2295 * If the package is scanned, it's not erased. 2296 */ 2297 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2298 if (scannedPkg != null) { 2299 /* 2300 * If the system app is both scanned and in the 2301 * disabled packages list, then it must have been 2302 * added via OTA. Remove it from the currently 2303 * scanned package so the previously user-installed 2304 * application can be scanned. 2305 */ 2306 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2307 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2308 + ps.name + "; removing system app. Last known codePath=" 2309 + ps.codePathString + ", installStatus=" + ps.installStatus 2310 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2311 + scannedPkg.mVersionCode); 2312 removePackageLI(scannedPkg, true); 2313 mExpectingBetter.put(ps.name, ps.codePath); 2314 } 2315 2316 continue; 2317 } 2318 2319 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2320 psit.remove(); 2321 logCriticalInfo(Log.WARN, "System package " + ps.name 2322 + " no longer exists; wiping its data"); 2323 removeDataDirsLI(null, ps.name); 2324 } else { 2325 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2326 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2327 possiblyDeletedUpdatedSystemApps.add(ps.name); 2328 } 2329 } 2330 } 2331 } 2332 2333 //look for any incomplete package installations 2334 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2335 //clean up list 2336 for(int i = 0; i < deletePkgsList.size(); i++) { 2337 //clean up here 2338 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2339 } 2340 //delete tmp files 2341 deleteTempPackageFiles(); 2342 2343 // Remove any shared userIDs that have no associated packages 2344 mSettings.pruneSharedUsersLPw(); 2345 2346 if (!mOnlyCore) { 2347 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2348 SystemClock.uptimeMillis()); 2349 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2350 2351 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2352 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2353 2354 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2355 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2356 2357 /** 2358 * Remove disable package settings for any updated system 2359 * apps that were removed via an OTA. If they're not a 2360 * previously-updated app, remove them completely. 2361 * Otherwise, just revoke their system-level permissions. 2362 */ 2363 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2364 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2365 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2366 2367 String msg; 2368 if (deletedPkg == null) { 2369 msg = "Updated system package " + deletedAppName 2370 + " no longer exists; wiping its data"; 2371 removeDataDirsLI(null, deletedAppName); 2372 } else { 2373 msg = "Updated system app + " + deletedAppName 2374 + " no longer present; removing system privileges for " 2375 + deletedAppName; 2376 2377 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2378 2379 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2380 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2381 } 2382 logCriticalInfo(Log.WARN, msg); 2383 } 2384 2385 /** 2386 * Make sure all system apps that we expected to appear on 2387 * the userdata partition actually showed up. If they never 2388 * appeared, crawl back and revive the system version. 2389 */ 2390 for (int i = 0; i < mExpectingBetter.size(); i++) { 2391 final String packageName = mExpectingBetter.keyAt(i); 2392 if (!mPackages.containsKey(packageName)) { 2393 final File scanFile = mExpectingBetter.valueAt(i); 2394 2395 logCriticalInfo(Log.WARN, "Expected better " + packageName 2396 + " but never showed up; reverting to system"); 2397 2398 final int reparseFlags; 2399 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2400 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR 2402 | PackageParser.PARSE_IS_PRIVILEGED; 2403 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2404 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2405 | PackageParser.PARSE_IS_SYSTEM_DIR; 2406 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2407 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR; 2409 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2410 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2411 | PackageParser.PARSE_IS_SYSTEM_DIR; 2412 } else { 2413 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2414 continue; 2415 } 2416 2417 mSettings.enableSystemPackageLPw(packageName); 2418 2419 try { 2420 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2421 } catch (PackageManagerException e) { 2422 Slog.e(TAG, "Failed to parse original system package: " 2423 + e.getMessage()); 2424 } 2425 } 2426 } 2427 } 2428 mExpectingBetter.clear(); 2429 2430 // Now that we know all of the shared libraries, update all clients to have 2431 // the correct library paths. 2432 updateAllSharedLibrariesLPw(); 2433 2434 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2435 // NOTE: We ignore potential failures here during a system scan (like 2436 // the rest of the commands above) because there's precious little we 2437 // can do about it. A settings error is reported, though. 2438 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2439 false /* boot complete */); 2440 } 2441 2442 // Now that we know all the packages we are keeping, 2443 // read and update their last usage times. 2444 mPackageUsage.readLP(); 2445 2446 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2447 SystemClock.uptimeMillis()); 2448 Slog.i(TAG, "Time to scan packages: " 2449 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2450 + " seconds"); 2451 2452 // If the platform SDK has changed since the last time we booted, 2453 // we need to re-grant app permission to catch any new ones that 2454 // appear. This is really a hack, and means that apps can in some 2455 // cases get permissions that the user didn't initially explicitly 2456 // allow... it would be nice to have some better way to handle 2457 // this situation. 2458 int updateFlags = UPDATE_PERMISSIONS_ALL; 2459 if (ver.sdkVersion != mSdkVersion) { 2460 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2461 + mSdkVersion + "; regranting permissions for internal storage"); 2462 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2463 } 2464 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2465 ver.sdkVersion = mSdkVersion; 2466 2467 // If this is the first boot or an update from pre-M, and it is a normal 2468 // boot, then we need to initialize the default preferred apps across 2469 // all defined users. 2470 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2471 for (UserInfo user : sUserManager.getUsers(true)) { 2472 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2473 applyFactoryDefaultBrowserLPw(user.id); 2474 primeDomainVerificationsLPw(user.id); 2475 } 2476 } 2477 2478 // Prepare storage for system user really early during boot, 2479 // since core system apps like SettingsProvider and SystemUI 2480 // can't wait for user to start 2481 final int storageFlags; 2482 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2483 storageFlags = StorageManager.FLAG_STORAGE_DE; 2484 } else { 2485 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2486 } 2487 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2488 storageFlags); 2489 2490 // If this is first boot after an OTA, and a normal boot, then 2491 // we need to clear code cache directories. 2492 if (mIsUpgrade && !onlyCore) { 2493 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2494 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2495 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2496 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2497 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2498 } 2499 } 2500 ver.fingerprint = Build.FINGERPRINT; 2501 } 2502 2503 checkDefaultBrowser(); 2504 2505 // clear only after permissions and other defaults have been updated 2506 mExistingSystemPackages.clear(); 2507 mPromoteSystemApps = false; 2508 2509 // All the changes are done during package scanning. 2510 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2511 2512 // can downgrade to reader 2513 mSettings.writeLPr(); 2514 2515 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2516 SystemClock.uptimeMillis()); 2517 2518 if (!mOnlyCore) { 2519 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2520 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2521 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2522 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2523 mIntentFilterVerifierComponent); 2524 } else { 2525 mRequiredVerifierPackage = null; 2526 mRequiredInstallerPackage = null; 2527 mIntentFilterVerifierComponent = null; 2528 mIntentFilterVerifier = null; 2529 } 2530 2531 mInstallerService = new PackageInstallerService(context, this); 2532 2533 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2534 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2535 // both the installer and resolver must be present to enable ephemeral 2536 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2537 if (DEBUG_EPHEMERAL) { 2538 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2539 + " installer:" + ephemeralInstallerComponent); 2540 } 2541 mEphemeralResolverComponent = ephemeralResolverComponent; 2542 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2543 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2544 mEphemeralResolverConnection = 2545 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2546 } else { 2547 if (DEBUG_EPHEMERAL) { 2548 final String missingComponent = 2549 (ephemeralResolverComponent == null) 2550 ? (ephemeralInstallerComponent == null) 2551 ? "resolver and installer" 2552 : "resolver" 2553 : "installer"; 2554 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2555 } 2556 mEphemeralResolverComponent = null; 2557 mEphemeralInstallerComponent = null; 2558 mEphemeralResolverConnection = null; 2559 } 2560 2561 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2562 } // synchronized (mPackages) 2563 } // synchronized (mInstallLock) 2564 2565 // Now after opening every single application zip, make sure they 2566 // are all flushed. Not really needed, but keeps things nice and 2567 // tidy. 2568 Runtime.getRuntime().gc(); 2569 2570 // The initial scanning above does many calls into installd while 2571 // holding the mPackages lock, but we're mostly interested in yelling 2572 // once we have a booted system. 2573 mInstaller.setWarnIfHeld(mPackages); 2574 2575 // Expose private service for system components to use. 2576 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2577 } 2578 2579 @Override 2580 public boolean isFirstBoot() { 2581 return !mRestoredSettings; 2582 } 2583 2584 @Override 2585 public boolean isOnlyCoreApps() { 2586 return mOnlyCore; 2587 } 2588 2589 @Override 2590 public boolean isUpgrade() { 2591 return mIsUpgrade; 2592 } 2593 2594 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2595 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2596 2597 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2598 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2599 UserHandle.USER_SYSTEM); 2600 if (matches.size() == 1) { 2601 return matches.get(0).getComponentInfo().packageName; 2602 } else { 2603 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2604 return null; 2605 } 2606 } 2607 2608 private @NonNull String getRequiredInstallerLPr() { 2609 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2610 intent.addCategory(Intent.CATEGORY_DEFAULT); 2611 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2612 2613 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2614 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2615 UserHandle.USER_SYSTEM); 2616 if (matches.size() == 1) { 2617 return matches.get(0).getComponentInfo().packageName; 2618 } else { 2619 throw new RuntimeException("There must be exactly one installer; found " + matches); 2620 } 2621 } 2622 2623 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2624 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2625 2626 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2627 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2628 UserHandle.USER_SYSTEM); 2629 ResolveInfo best = null; 2630 final int N = matches.size(); 2631 for (int i = 0; i < N; i++) { 2632 final ResolveInfo cur = matches.get(i); 2633 final String packageName = cur.getComponentInfo().packageName; 2634 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2635 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2636 continue; 2637 } 2638 2639 if (best == null || cur.priority > best.priority) { 2640 best = cur; 2641 } 2642 } 2643 2644 if (best != null) { 2645 return best.getComponentInfo().getComponentName(); 2646 } else { 2647 throw new RuntimeException("There must be at least one intent filter verifier"); 2648 } 2649 } 2650 2651 private @Nullable ComponentName getEphemeralResolverLPr() { 2652 final String[] packageArray = 2653 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2654 if (packageArray.length == 0) { 2655 if (DEBUG_EPHEMERAL) { 2656 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2657 } 2658 return null; 2659 } 2660 2661 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2662 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2663 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2664 UserHandle.USER_SYSTEM); 2665 2666 final int N = resolvers.size(); 2667 if (N == 0) { 2668 if (DEBUG_EPHEMERAL) { 2669 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2670 } 2671 return null; 2672 } 2673 2674 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2675 for (int i = 0; i < N; i++) { 2676 final ResolveInfo info = resolvers.get(i); 2677 2678 if (info.serviceInfo == null) { 2679 continue; 2680 } 2681 2682 final String packageName = info.serviceInfo.packageName; 2683 if (!possiblePackages.contains(packageName)) { 2684 if (DEBUG_EPHEMERAL) { 2685 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2686 + " pkg: " + packageName + ", info:" + info); 2687 } 2688 continue; 2689 } 2690 2691 if (DEBUG_EPHEMERAL) { 2692 Slog.v(TAG, "Ephemeral resolver found;" 2693 + " pkg: " + packageName + ", info:" + info); 2694 } 2695 return new ComponentName(packageName, info.serviceInfo.name); 2696 } 2697 if (DEBUG_EPHEMERAL) { 2698 Slog.v(TAG, "Ephemeral resolver NOT found"); 2699 } 2700 return null; 2701 } 2702 2703 private @Nullable ComponentName getEphemeralInstallerLPr() { 2704 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2705 intent.addCategory(Intent.CATEGORY_DEFAULT); 2706 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2707 2708 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2709 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2710 UserHandle.USER_SYSTEM); 2711 if (matches.size() == 0) { 2712 return null; 2713 } else if (matches.size() == 1) { 2714 return matches.get(0).getComponentInfo().getComponentName(); 2715 } else { 2716 throw new RuntimeException( 2717 "There must be at most one ephemeral installer; found " + matches); 2718 } 2719 } 2720 2721 private void primeDomainVerificationsLPw(int userId) { 2722 if (DEBUG_DOMAIN_VERIFICATION) { 2723 Slog.d(TAG, "Priming domain verifications in user " + userId); 2724 } 2725 2726 SystemConfig systemConfig = SystemConfig.getInstance(); 2727 ArraySet<String> packages = systemConfig.getLinkedApps(); 2728 ArraySet<String> domains = new ArraySet<String>(); 2729 2730 for (String packageName : packages) { 2731 PackageParser.Package pkg = mPackages.get(packageName); 2732 if (pkg != null) { 2733 if (!pkg.isSystemApp()) { 2734 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2735 continue; 2736 } 2737 2738 domains.clear(); 2739 for (PackageParser.Activity a : pkg.activities) { 2740 for (ActivityIntentInfo filter : a.intents) { 2741 if (hasValidDomains(filter)) { 2742 domains.addAll(filter.getHostsList()); 2743 } 2744 } 2745 } 2746 2747 if (domains.size() > 0) { 2748 if (DEBUG_DOMAIN_VERIFICATION) { 2749 Slog.v(TAG, " + " + packageName); 2750 } 2751 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2752 // state w.r.t. the formal app-linkage "no verification attempted" state; 2753 // and then 'always' in the per-user state actually used for intent resolution. 2754 final IntentFilterVerificationInfo ivi; 2755 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2756 new ArrayList<String>(domains)); 2757 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2758 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2759 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2760 } else { 2761 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2762 + "' does not handle web links"); 2763 } 2764 } else { 2765 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2766 } 2767 } 2768 2769 scheduleWritePackageRestrictionsLocked(userId); 2770 scheduleWriteSettingsLocked(); 2771 } 2772 2773 private void applyFactoryDefaultBrowserLPw(int userId) { 2774 // The default browser app's package name is stored in a string resource, 2775 // with a product-specific overlay used for vendor customization. 2776 String browserPkg = mContext.getResources().getString( 2777 com.android.internal.R.string.default_browser); 2778 if (!TextUtils.isEmpty(browserPkg)) { 2779 // non-empty string => required to be a known package 2780 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2781 if (ps == null) { 2782 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2783 browserPkg = null; 2784 } else { 2785 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2786 } 2787 } 2788 2789 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2790 // default. If there's more than one, just leave everything alone. 2791 if (browserPkg == null) { 2792 calculateDefaultBrowserLPw(userId); 2793 } 2794 } 2795 2796 private void calculateDefaultBrowserLPw(int userId) { 2797 List<String> allBrowsers = resolveAllBrowserApps(userId); 2798 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2799 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2800 } 2801 2802 private List<String> resolveAllBrowserApps(int userId) { 2803 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2804 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2805 PackageManager.MATCH_ALL, userId); 2806 2807 final int count = list.size(); 2808 List<String> result = new ArrayList<String>(count); 2809 for (int i=0; i<count; i++) { 2810 ResolveInfo info = list.get(i); 2811 if (info.activityInfo == null 2812 || !info.handleAllWebDataURI 2813 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2814 || result.contains(info.activityInfo.packageName)) { 2815 continue; 2816 } 2817 result.add(info.activityInfo.packageName); 2818 } 2819 2820 return result; 2821 } 2822 2823 private boolean packageIsBrowser(String packageName, int userId) { 2824 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2825 PackageManager.MATCH_ALL, userId); 2826 final int N = list.size(); 2827 for (int i = 0; i < N; i++) { 2828 ResolveInfo info = list.get(i); 2829 if (packageName.equals(info.activityInfo.packageName)) { 2830 return true; 2831 } 2832 } 2833 return false; 2834 } 2835 2836 private void checkDefaultBrowser() { 2837 final int myUserId = UserHandle.myUserId(); 2838 final String packageName = getDefaultBrowserPackageName(myUserId); 2839 if (packageName != null) { 2840 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2841 if (info == null) { 2842 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2843 synchronized (mPackages) { 2844 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2845 } 2846 } 2847 } 2848 } 2849 2850 @Override 2851 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2852 throws RemoteException { 2853 try { 2854 return super.onTransact(code, data, reply, flags); 2855 } catch (RuntimeException e) { 2856 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2857 Slog.wtf(TAG, "Package Manager Crash", e); 2858 } 2859 throw e; 2860 } 2861 } 2862 2863 void cleanupInstallFailedPackage(PackageSetting ps) { 2864 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2865 2866 removeDataDirsLI(ps.volumeUuid, ps.name); 2867 if (ps.codePath != null) { 2868 removeCodePathLI(ps.codePath); 2869 } 2870 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2871 if (ps.resourcePath.isDirectory()) { 2872 FileUtils.deleteContents(ps.resourcePath); 2873 } 2874 ps.resourcePath.delete(); 2875 } 2876 mSettings.removePackageLPw(ps.name); 2877 } 2878 2879 static int[] appendInts(int[] cur, int[] add) { 2880 if (add == null) return cur; 2881 if (cur == null) return add; 2882 final int N = add.length; 2883 for (int i=0; i<N; i++) { 2884 cur = appendInt(cur, add[i]); 2885 } 2886 return cur; 2887 } 2888 2889 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 final PackageSetting ps = (PackageSetting) p.mExtras; 2892 if (ps == null) { 2893 return null; 2894 } 2895 2896 final PermissionsState permissionsState = ps.getPermissionsState(); 2897 2898 final int[] gids = permissionsState.computeGids(userId); 2899 final Set<String> permissions = permissionsState.getPermissions(userId); 2900 final PackageUserState state = ps.readUserState(userId); 2901 2902 return PackageParser.generatePackageInfo(p, gids, flags, 2903 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2904 } 2905 2906 @Override 2907 public void checkPackageStartable(String packageName, int userId) { 2908 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2909 2910 synchronized (mPackages) { 2911 final PackageSetting ps = mSettings.mPackages.get(packageName); 2912 if (ps == null) { 2913 throw new SecurityException("Package " + packageName + " was not found!"); 2914 } 2915 2916 if (!ps.getInstalled(userId)) { 2917 throw new SecurityException( 2918 "Package " + packageName + " was not installed for user " + userId + "!"); 2919 } 2920 2921 if (mSafeMode && !ps.isSystem()) { 2922 throw new SecurityException("Package " + packageName + " not a system app!"); 2923 } 2924 2925 if (ps.frozen) { 2926 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2927 } 2928 2929 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2930 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2931 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2932 } 2933 } 2934 } 2935 2936 @Override 2937 public boolean isPackageAvailable(String packageName, int userId) { 2938 if (!sUserManager.exists(userId)) return false; 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2940 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2941 synchronized (mPackages) { 2942 PackageParser.Package p = mPackages.get(packageName); 2943 if (p != null) { 2944 final PackageSetting ps = (PackageSetting) p.mExtras; 2945 if (ps != null) { 2946 final PackageUserState state = ps.readUserState(userId); 2947 if (state != null) { 2948 return PackageParser.isAvailable(state); 2949 } 2950 } 2951 } 2952 } 2953 return false; 2954 } 2955 2956 @Override 2957 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2958 if (!sUserManager.exists(userId)) return null; 2959 flags = updateFlagsForPackage(flags, userId, packageName); 2960 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2961 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2962 // reader 2963 synchronized (mPackages) { 2964 PackageParser.Package p = mPackages.get(packageName); 2965 if (DEBUG_PACKAGE_INFO) 2966 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2967 if (p != null) { 2968 return generatePackageInfo(p, flags, userId); 2969 } 2970 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2971 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2972 } 2973 } 2974 return null; 2975 } 2976 2977 @Override 2978 public String[] currentToCanonicalPackageNames(String[] names) { 2979 String[] out = new String[names.length]; 2980 // reader 2981 synchronized (mPackages) { 2982 for (int i=names.length-1; i>=0; i--) { 2983 PackageSetting ps = mSettings.mPackages.get(names[i]); 2984 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2985 } 2986 } 2987 return out; 2988 } 2989 2990 @Override 2991 public String[] canonicalToCurrentPackageNames(String[] names) { 2992 String[] out = new String[names.length]; 2993 // reader 2994 synchronized (mPackages) { 2995 for (int i=names.length-1; i>=0; i--) { 2996 String cur = mSettings.mRenamedPackages.get(names[i]); 2997 out[i] = cur != null ? cur : names[i]; 2998 } 2999 } 3000 return out; 3001 } 3002 3003 @Override 3004 public int getPackageUid(String packageName, int flags, int userId) { 3005 if (!sUserManager.exists(userId)) return -1; 3006 flags = updateFlagsForPackage(flags, userId, packageName); 3007 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3008 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3009 3010 // reader 3011 synchronized (mPackages) { 3012 final PackageParser.Package p = mPackages.get(packageName); 3013 if (p != null && p.isMatch(flags)) { 3014 return UserHandle.getUid(userId, p.applicationInfo.uid); 3015 } 3016 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3017 final PackageSetting ps = mSettings.mPackages.get(packageName); 3018 if (ps != null && ps.isMatch(flags)) { 3019 return UserHandle.getUid(userId, ps.appId); 3020 } 3021 } 3022 } 3023 3024 return -1; 3025 } 3026 3027 @Override 3028 public int[] getPackageGids(String packageName, int flags, int userId) { 3029 if (!sUserManager.exists(userId)) return null; 3030 flags = updateFlagsForPackage(flags, userId, packageName); 3031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3032 false /* requireFullPermission */, false /* checkShell */, 3033 "getPackageGids"); 3034 3035 // reader 3036 synchronized (mPackages) { 3037 final PackageParser.Package p = mPackages.get(packageName); 3038 if (p != null && p.isMatch(flags)) { 3039 PackageSetting ps = (PackageSetting) p.mExtras; 3040 return ps.getPermissionsState().computeGids(userId); 3041 } 3042 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3043 final PackageSetting ps = mSettings.mPackages.get(packageName); 3044 if (ps != null && ps.isMatch(flags)) { 3045 return ps.getPermissionsState().computeGids(userId); 3046 } 3047 } 3048 } 3049 3050 return null; 3051 } 3052 3053 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3054 if (bp.perm != null) { 3055 return PackageParser.generatePermissionInfo(bp.perm, flags); 3056 } 3057 PermissionInfo pi = new PermissionInfo(); 3058 pi.name = bp.name; 3059 pi.packageName = bp.sourcePackage; 3060 pi.nonLocalizedLabel = bp.name; 3061 pi.protectionLevel = bp.protectionLevel; 3062 return pi; 3063 } 3064 3065 @Override 3066 public PermissionInfo getPermissionInfo(String name, int flags) { 3067 // reader 3068 synchronized (mPackages) { 3069 final BasePermission p = mSettings.mPermissions.get(name); 3070 if (p != null) { 3071 return generatePermissionInfo(p, flags); 3072 } 3073 return null; 3074 } 3075 } 3076 3077 @Override 3078 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3079 int flags) { 3080 // reader 3081 synchronized (mPackages) { 3082 if (group != null && !mPermissionGroups.containsKey(group)) { 3083 // This is thrown as NameNotFoundException 3084 return null; 3085 } 3086 3087 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3088 for (BasePermission p : mSettings.mPermissions.values()) { 3089 if (group == null) { 3090 if (p.perm == null || p.perm.info.group == null) { 3091 out.add(generatePermissionInfo(p, flags)); 3092 } 3093 } else { 3094 if (p.perm != null && group.equals(p.perm.info.group)) { 3095 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3096 } 3097 } 3098 } 3099 return new ParceledListSlice<>(out); 3100 } 3101 } 3102 3103 @Override 3104 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3105 // reader 3106 synchronized (mPackages) { 3107 return PackageParser.generatePermissionGroupInfo( 3108 mPermissionGroups.get(name), flags); 3109 } 3110 } 3111 3112 @Override 3113 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3114 // reader 3115 synchronized (mPackages) { 3116 final int N = mPermissionGroups.size(); 3117 ArrayList<PermissionGroupInfo> out 3118 = new ArrayList<PermissionGroupInfo>(N); 3119 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3120 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3121 } 3122 return new ParceledListSlice<>(out); 3123 } 3124 } 3125 3126 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3127 int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 PackageSetting ps = mSettings.mPackages.get(packageName); 3130 if (ps != null) { 3131 if (ps.pkg == null) { 3132 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3133 flags, userId); 3134 if (pInfo != null) { 3135 return pInfo.applicationInfo; 3136 } 3137 return null; 3138 } 3139 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3140 ps.readUserState(userId), userId); 3141 } 3142 return null; 3143 } 3144 3145 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3146 int userId) { 3147 if (!sUserManager.exists(userId)) return null; 3148 PackageSetting ps = mSettings.mPackages.get(packageName); 3149 if (ps != null) { 3150 PackageParser.Package pkg = ps.pkg; 3151 if (pkg == null) { 3152 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3153 return null; 3154 } 3155 // Only data remains, so we aren't worried about code paths 3156 pkg = new PackageParser.Package(packageName); 3157 pkg.applicationInfo.packageName = packageName; 3158 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3159 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3160 pkg.applicationInfo.uid = ps.appId; 3161 pkg.applicationInfo.initForUser(userId); 3162 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3163 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3164 } 3165 return generatePackageInfo(pkg, flags, userId); 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 flags = updateFlagsForApplication(flags, userId, packageName); 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3176 // writer 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (DEBUG_PACKAGE_INFO) Log.v( 3180 TAG, "getApplicationInfo " + packageName 3181 + ": " + p); 3182 if (p != null) { 3183 PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps == null) return null; 3185 // Note: isEnabledLP() does not apply here - always return info 3186 return PackageParser.generateApplicationInfo( 3187 p, flags, ps.readUserState(userId), userId); 3188 } 3189 if ("android".equals(packageName)||"system".equals(packageName)) { 3190 return mAndroidApplication; 3191 } 3192 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3193 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3194 } 3195 } 3196 return null; 3197 } 3198 3199 @Override 3200 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3201 final IPackageDataObserver observer) { 3202 mContext.enforceCallingOrSelfPermission( 3203 android.Manifest.permission.CLEAR_APP_CACHE, null); 3204 // Queue up an async operation since clearing cache may take a little while. 3205 mHandler.post(new Runnable() { 3206 public void run() { 3207 mHandler.removeCallbacks(this); 3208 boolean success = true; 3209 synchronized (mInstallLock) { 3210 try { 3211 mInstaller.freeCache(volumeUuid, freeStorageSize); 3212 } catch (InstallerException e) { 3213 Slog.w(TAG, "Couldn't clear application caches: " + e); 3214 success = false; 3215 } 3216 } 3217 if (observer != null) { 3218 try { 3219 observer.onRemoveCompleted(null, success); 3220 } catch (RemoteException e) { 3221 Slog.w(TAG, "RemoveException when invoking call back"); 3222 } 3223 } 3224 } 3225 }); 3226 } 3227 3228 @Override 3229 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3230 final IntentSender pi) { 3231 mContext.enforceCallingOrSelfPermission( 3232 android.Manifest.permission.CLEAR_APP_CACHE, null); 3233 // Queue up an async operation since clearing cache may take a little while. 3234 mHandler.post(new Runnable() { 3235 public void run() { 3236 mHandler.removeCallbacks(this); 3237 boolean success = true; 3238 synchronized (mInstallLock) { 3239 try { 3240 mInstaller.freeCache(volumeUuid, freeStorageSize); 3241 } catch (InstallerException e) { 3242 Slog.w(TAG, "Couldn't clear application caches: " + e); 3243 success = false; 3244 } 3245 } 3246 if(pi != null) { 3247 try { 3248 // Callback via pending intent 3249 int code = success ? 1 : 0; 3250 pi.sendIntent(null, code, null, 3251 null, null); 3252 } catch (SendIntentException e1) { 3253 Slog.i(TAG, "Failed to send pending intent"); 3254 } 3255 } 3256 } 3257 }); 3258 } 3259 3260 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3261 synchronized (mInstallLock) { 3262 try { 3263 mInstaller.freeCache(volumeUuid, freeStorageSize); 3264 } catch (InstallerException e) { 3265 throw new IOException("Failed to free enough space", e); 3266 } 3267 } 3268 } 3269 3270 /** 3271 * Return if the user key is currently unlocked. 3272 */ 3273 private boolean isUserKeyUnlocked(int userId) { 3274 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3275 final IMountService mount = IMountService.Stub 3276 .asInterface(ServiceManager.getService("mount")); 3277 if (mount == null) { 3278 Slog.w(TAG, "Early during boot, assuming locked"); 3279 return false; 3280 } 3281 final long token = Binder.clearCallingIdentity(); 3282 try { 3283 return mount.isUserKeyUnlocked(userId); 3284 } catch (RemoteException e) { 3285 throw e.rethrowAsRuntimeException(); 3286 } finally { 3287 Binder.restoreCallingIdentity(token); 3288 } 3289 } else { 3290 return true; 3291 } 3292 } 3293 3294 /** 3295 * Update given flags based on encryption status of current user. 3296 */ 3297 private int updateFlags(int flags, int userId) { 3298 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3299 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3300 // Caller expressed an explicit opinion about what encryption 3301 // aware/unaware components they want to see, so fall through and 3302 // give them what they want 3303 } else { 3304 // Caller expressed no opinion, so match based on user state 3305 if (isUserKeyUnlocked(userId)) { 3306 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3307 } else { 3308 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3309 } 3310 } 3311 return flags; 3312 } 3313 3314 /** 3315 * Update given flags when being used to request {@link PackageInfo}. 3316 */ 3317 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3318 boolean triaged = true; 3319 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3320 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3321 // Caller is asking for component details, so they'd better be 3322 // asking for specific encryption matching behavior, or be triaged 3323 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3324 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3325 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3326 triaged = false; 3327 } 3328 } 3329 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3330 | PackageManager.MATCH_SYSTEM_ONLY 3331 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3332 triaged = false; 3333 } 3334 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3335 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3336 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3337 } 3338 return updateFlags(flags, userId); 3339 } 3340 3341 /** 3342 * Update given flags when being used to request {@link ApplicationInfo}. 3343 */ 3344 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3345 return updateFlagsForPackage(flags, userId, cookie); 3346 } 3347 3348 /** 3349 * Update given flags when being used to request {@link ComponentInfo}. 3350 */ 3351 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3352 if (cookie instanceof Intent) { 3353 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3354 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3355 } 3356 } 3357 3358 boolean triaged = true; 3359 // Caller is asking for component details, so they'd better be 3360 // asking for specific encryption matching behavior, or be triaged 3361 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3362 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3363 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3364 triaged = false; 3365 } 3366 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3367 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3368 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3369 } 3370 3371 return updateFlags(flags, userId); 3372 } 3373 3374 /** 3375 * Update given flags when being used to request {@link ResolveInfo}. 3376 */ 3377 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3378 // Safe mode means we shouldn't match any third-party components 3379 if (mSafeMode) { 3380 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3381 } 3382 3383 return updateFlagsForComponent(flags, userId, cookie); 3384 } 3385 3386 @Override 3387 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3388 if (!sUserManager.exists(userId)) return null; 3389 flags = updateFlagsForComponent(flags, userId, component); 3390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3391 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3392 synchronized (mPackages) { 3393 PackageParser.Activity a = mActivities.mActivities.get(component); 3394 3395 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3396 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3397 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3398 if (ps == null) return null; 3399 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3400 userId); 3401 } 3402 if (mResolveComponentName.equals(component)) { 3403 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3404 new PackageUserState(), userId); 3405 } 3406 } 3407 return null; 3408 } 3409 3410 @Override 3411 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3412 String resolvedType) { 3413 synchronized (mPackages) { 3414 if (component.equals(mResolveComponentName)) { 3415 // The resolver supports EVERYTHING! 3416 return true; 3417 } 3418 PackageParser.Activity a = mActivities.mActivities.get(component); 3419 if (a == null) { 3420 return false; 3421 } 3422 for (int i=0; i<a.intents.size(); i++) { 3423 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3424 intent.getData(), intent.getCategories(), TAG) >= 0) { 3425 return true; 3426 } 3427 } 3428 return false; 3429 } 3430 } 3431 3432 @Override 3433 public ActivityInfo getReceiverInfo(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 receiver info"); 3438 synchronized (mPackages) { 3439 PackageParser.Activity a = mReceivers.mActivities.get(component); 3440 if (DEBUG_PACKAGE_INFO) Log.v( 3441 TAG, "getReceiverInfo " + component + ": " + a); 3442 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3443 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3444 if (ps == null) return null; 3445 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3446 userId); 3447 } 3448 } 3449 return null; 3450 } 3451 3452 @Override 3453 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3454 if (!sUserManager.exists(userId)) return null; 3455 flags = updateFlagsForComponent(flags, userId, component); 3456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3457 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3458 synchronized (mPackages) { 3459 PackageParser.Service s = mServices.mServices.get(component); 3460 if (DEBUG_PACKAGE_INFO) Log.v( 3461 TAG, "getServiceInfo " + component + ": " + s); 3462 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3463 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3464 if (ps == null) return null; 3465 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3466 userId); 3467 } 3468 } 3469 return null; 3470 } 3471 3472 @Override 3473 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3474 if (!sUserManager.exists(userId)) return null; 3475 flags = updateFlagsForComponent(flags, userId, component); 3476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3477 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3478 synchronized (mPackages) { 3479 PackageParser.Provider p = mProviders.mProviders.get(component); 3480 if (DEBUG_PACKAGE_INFO) Log.v( 3481 TAG, "getProviderInfo " + component + ": " + p); 3482 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3483 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3484 if (ps == null) return null; 3485 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3486 userId); 3487 } 3488 } 3489 return null; 3490 } 3491 3492 @Override 3493 public String[] getSystemSharedLibraryNames() { 3494 Set<String> libSet; 3495 synchronized (mPackages) { 3496 libSet = mSharedLibraries.keySet(); 3497 int size = libSet.size(); 3498 if (size > 0) { 3499 String[] libs = new String[size]; 3500 libSet.toArray(libs); 3501 return libs; 3502 } 3503 } 3504 return null; 3505 } 3506 3507 @Override 3508 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3509 synchronized (mPackages) { 3510 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3511 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3512 if (libraryEntry != null) { 3513 return libraryEntry.apk; 3514 } 3515 } 3516 return null; 3517 } 3518 3519 @Override 3520 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3521 synchronized (mPackages) { 3522 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3523 3524 final FeatureInfo fi = new FeatureInfo(); 3525 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3526 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3527 res.add(fi); 3528 3529 return new ParceledListSlice<>(res); 3530 } 3531 } 3532 3533 @Override 3534 public boolean hasSystemFeature(String name, int version) { 3535 synchronized (mPackages) { 3536 final FeatureInfo feat = mAvailableFeatures.get(name); 3537 if (feat == null) { 3538 return false; 3539 } else { 3540 return feat.version >= version; 3541 } 3542 } 3543 } 3544 3545 @Override 3546 public int checkPermission(String permName, String pkgName, int userId) { 3547 if (!sUserManager.exists(userId)) { 3548 return PackageManager.PERMISSION_DENIED; 3549 } 3550 3551 synchronized (mPackages) { 3552 final PackageParser.Package p = mPackages.get(pkgName); 3553 if (p != null && p.mExtras != null) { 3554 final PackageSetting ps = (PackageSetting) p.mExtras; 3555 final PermissionsState permissionsState = ps.getPermissionsState(); 3556 if (permissionsState.hasPermission(permName, userId)) { 3557 return PackageManager.PERMISSION_GRANTED; 3558 } 3559 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3560 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3561 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3562 return PackageManager.PERMISSION_GRANTED; 3563 } 3564 } 3565 } 3566 3567 return PackageManager.PERMISSION_DENIED; 3568 } 3569 3570 @Override 3571 public int checkUidPermission(String permName, int uid) { 3572 final int userId = UserHandle.getUserId(uid); 3573 3574 if (!sUserManager.exists(userId)) { 3575 return PackageManager.PERMISSION_DENIED; 3576 } 3577 3578 synchronized (mPackages) { 3579 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3580 if (obj != null) { 3581 final SettingBase ps = (SettingBase) obj; 3582 final PermissionsState permissionsState = ps.getPermissionsState(); 3583 if (permissionsState.hasPermission(permName, userId)) { 3584 return PackageManager.PERMISSION_GRANTED; 3585 } 3586 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3587 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3588 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3589 return PackageManager.PERMISSION_GRANTED; 3590 } 3591 } else { 3592 ArraySet<String> perms = mSystemPermissions.get(uid); 3593 if (perms != null) { 3594 if (perms.contains(permName)) { 3595 return PackageManager.PERMISSION_GRANTED; 3596 } 3597 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3598 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3599 return PackageManager.PERMISSION_GRANTED; 3600 } 3601 } 3602 } 3603 } 3604 3605 return PackageManager.PERMISSION_DENIED; 3606 } 3607 3608 @Override 3609 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3610 if (UserHandle.getCallingUserId() != userId) { 3611 mContext.enforceCallingPermission( 3612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3613 "isPermissionRevokedByPolicy for user " + userId); 3614 } 3615 3616 if (checkPermission(permission, packageName, userId) 3617 == PackageManager.PERMISSION_GRANTED) { 3618 return false; 3619 } 3620 3621 final long identity = Binder.clearCallingIdentity(); 3622 try { 3623 final int flags = getPermissionFlags(permission, packageName, userId); 3624 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3625 } finally { 3626 Binder.restoreCallingIdentity(identity); 3627 } 3628 } 3629 3630 @Override 3631 public String getPermissionControllerPackageName() { 3632 synchronized (mPackages) { 3633 return mRequiredInstallerPackage; 3634 } 3635 } 3636 3637 /** 3638 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3639 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3640 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3641 * @param message the message to log on security exception 3642 */ 3643 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3644 boolean checkShell, String message) { 3645 if (userId < 0) { 3646 throw new IllegalArgumentException("Invalid userId " + userId); 3647 } 3648 if (checkShell) { 3649 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3650 } 3651 if (userId == UserHandle.getUserId(callingUid)) return; 3652 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3653 if (requireFullPermission) { 3654 mContext.enforceCallingOrSelfPermission( 3655 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3656 } else { 3657 try { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3660 } catch (SecurityException se) { 3661 mContext.enforceCallingOrSelfPermission( 3662 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3663 } 3664 } 3665 } 3666 } 3667 3668 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3669 if (callingUid == Process.SHELL_UID) { 3670 if (userHandle >= 0 3671 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3672 throw new SecurityException("Shell does not have permission to access user " 3673 + userHandle); 3674 } else if (userHandle < 0) { 3675 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3676 + Debug.getCallers(3)); 3677 } 3678 } 3679 } 3680 3681 private BasePermission findPermissionTreeLP(String permName) { 3682 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3683 if (permName.startsWith(bp.name) && 3684 permName.length() > bp.name.length() && 3685 permName.charAt(bp.name.length()) == '.') { 3686 return bp; 3687 } 3688 } 3689 return null; 3690 } 3691 3692 private BasePermission checkPermissionTreeLP(String permName) { 3693 if (permName != null) { 3694 BasePermission bp = findPermissionTreeLP(permName); 3695 if (bp != null) { 3696 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3697 return bp; 3698 } 3699 throw new SecurityException("Calling uid " 3700 + Binder.getCallingUid() 3701 + " is not allowed to add to permission tree " 3702 + bp.name + " owned by uid " + bp.uid); 3703 } 3704 } 3705 throw new SecurityException("No permission tree found for " + permName); 3706 } 3707 3708 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3709 if (s1 == null) { 3710 return s2 == null; 3711 } 3712 if (s2 == null) { 3713 return false; 3714 } 3715 if (s1.getClass() != s2.getClass()) { 3716 return false; 3717 } 3718 return s1.equals(s2); 3719 } 3720 3721 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3722 if (pi1.icon != pi2.icon) return false; 3723 if (pi1.logo != pi2.logo) return false; 3724 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3725 if (!compareStrings(pi1.name, pi2.name)) return false; 3726 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3727 // We'll take care of setting this one. 3728 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3729 // These are not currently stored in settings. 3730 //if (!compareStrings(pi1.group, pi2.group)) return false; 3731 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3732 //if (pi1.labelRes != pi2.labelRes) return false; 3733 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3734 return true; 3735 } 3736 3737 int permissionInfoFootprint(PermissionInfo info) { 3738 int size = info.name.length(); 3739 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3740 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3741 return size; 3742 } 3743 3744 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3745 int size = 0; 3746 for (BasePermission perm : mSettings.mPermissions.values()) { 3747 if (perm.uid == tree.uid) { 3748 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3749 } 3750 } 3751 return size; 3752 } 3753 3754 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3755 // We calculate the max size of permissions defined by this uid and throw 3756 // if that plus the size of 'info' would exceed our stated maximum. 3757 if (tree.uid != Process.SYSTEM_UID) { 3758 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3759 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3760 throw new SecurityException("Permission tree size cap exceeded"); 3761 } 3762 } 3763 } 3764 3765 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3766 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3767 throw new SecurityException("Label must be specified in permission"); 3768 } 3769 BasePermission tree = checkPermissionTreeLP(info.name); 3770 BasePermission bp = mSettings.mPermissions.get(info.name); 3771 boolean added = bp == null; 3772 boolean changed = true; 3773 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3774 if (added) { 3775 enforcePermissionCapLocked(info, tree); 3776 bp = new BasePermission(info.name, tree.sourcePackage, 3777 BasePermission.TYPE_DYNAMIC); 3778 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3779 throw new SecurityException( 3780 "Not allowed to modify non-dynamic permission " 3781 + info.name); 3782 } else { 3783 if (bp.protectionLevel == fixedLevel 3784 && bp.perm.owner.equals(tree.perm.owner) 3785 && bp.uid == tree.uid 3786 && comparePermissionInfos(bp.perm.info, info)) { 3787 changed = false; 3788 } 3789 } 3790 bp.protectionLevel = fixedLevel; 3791 info = new PermissionInfo(info); 3792 info.protectionLevel = fixedLevel; 3793 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3794 bp.perm.info.packageName = tree.perm.info.packageName; 3795 bp.uid = tree.uid; 3796 if (added) { 3797 mSettings.mPermissions.put(info.name, bp); 3798 } 3799 if (changed) { 3800 if (!async) { 3801 mSettings.writeLPr(); 3802 } else { 3803 scheduleWriteSettingsLocked(); 3804 } 3805 } 3806 return added; 3807 } 3808 3809 @Override 3810 public boolean addPermission(PermissionInfo info) { 3811 synchronized (mPackages) { 3812 return addPermissionLocked(info, false); 3813 } 3814 } 3815 3816 @Override 3817 public boolean addPermissionAsync(PermissionInfo info) { 3818 synchronized (mPackages) { 3819 return addPermissionLocked(info, true); 3820 } 3821 } 3822 3823 @Override 3824 public void removePermission(String name) { 3825 synchronized (mPackages) { 3826 checkPermissionTreeLP(name); 3827 BasePermission bp = mSettings.mPermissions.get(name); 3828 if (bp != null) { 3829 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3830 throw new SecurityException( 3831 "Not allowed to modify non-dynamic permission " 3832 + name); 3833 } 3834 mSettings.mPermissions.remove(name); 3835 mSettings.writeLPr(); 3836 } 3837 } 3838 } 3839 3840 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3841 BasePermission bp) { 3842 int index = pkg.requestedPermissions.indexOf(bp.name); 3843 if (index == -1) { 3844 throw new SecurityException("Package " + pkg.packageName 3845 + " has not requested permission " + bp.name); 3846 } 3847 if (!bp.isRuntime() && !bp.isDevelopment()) { 3848 throw new SecurityException("Permission " + bp.name 3849 + " is not a changeable permission type"); 3850 } 3851 } 3852 3853 @Override 3854 public void grantRuntimePermission(String packageName, String name, final int userId) { 3855 if (!sUserManager.exists(userId)) { 3856 Log.e(TAG, "No such user:" + userId); 3857 return; 3858 } 3859 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3862 "grantRuntimePermission"); 3863 3864 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3865 true /* requireFullPermission */, true /* checkShell */, 3866 "grantRuntimePermission"); 3867 3868 final int uid; 3869 final SettingBase sb; 3870 3871 synchronized (mPackages) { 3872 final PackageParser.Package pkg = mPackages.get(packageName); 3873 if (pkg == null) { 3874 throw new IllegalArgumentException("Unknown package: " + packageName); 3875 } 3876 3877 final BasePermission bp = mSettings.mPermissions.get(name); 3878 if (bp == null) { 3879 throw new IllegalArgumentException("Unknown permission: " + name); 3880 } 3881 3882 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3883 3884 // If a permission review is required for legacy apps we represent 3885 // their permissions as always granted runtime ones since we need 3886 // to keep the review required permission flag per user while an 3887 // install permission's state is shared across all users. 3888 if (Build.PERMISSIONS_REVIEW_REQUIRED 3889 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3890 && bp.isRuntime()) { 3891 return; 3892 } 3893 3894 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3895 sb = (SettingBase) pkg.mExtras; 3896 if (sb == null) { 3897 throw new IllegalArgumentException("Unknown package: " + packageName); 3898 } 3899 3900 final PermissionsState permissionsState = sb.getPermissionsState(); 3901 3902 final int flags = permissionsState.getPermissionFlags(name, userId); 3903 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3904 throw new SecurityException("Cannot grant system fixed permission " 3905 + name + " for package " + packageName); 3906 } 3907 3908 if (bp.isDevelopment()) { 3909 // Development permissions must be handled specially, since they are not 3910 // normal runtime permissions. For now they apply to all users. 3911 if (permissionsState.grantInstallPermission(bp) != 3912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3913 scheduleWriteSettingsLocked(); 3914 } 3915 return; 3916 } 3917 3918 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3919 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3920 return; 3921 } 3922 3923 final int result = permissionsState.grantRuntimePermission(bp, userId); 3924 switch (result) { 3925 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3926 return; 3927 } 3928 3929 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3930 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3931 mHandler.post(new Runnable() { 3932 @Override 3933 public void run() { 3934 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3935 } 3936 }); 3937 } 3938 break; 3939 } 3940 3941 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3942 3943 // Not critical if that is lost - app has to request again. 3944 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3945 } 3946 3947 // Only need to do this if user is initialized. Otherwise it's a new user 3948 // and there are no processes running as the user yet and there's no need 3949 // to make an expensive call to remount processes for the changed permissions. 3950 if (READ_EXTERNAL_STORAGE.equals(name) 3951 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3952 final long token = Binder.clearCallingIdentity(); 3953 try { 3954 if (sUserManager.isInitialized(userId)) { 3955 MountServiceInternal mountServiceInternal = LocalServices.getService( 3956 MountServiceInternal.class); 3957 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3958 } 3959 } finally { 3960 Binder.restoreCallingIdentity(token); 3961 } 3962 } 3963 } 3964 3965 @Override 3966 public void revokeRuntimePermission(String packageName, String name, int userId) { 3967 if (!sUserManager.exists(userId)) { 3968 Log.e(TAG, "No such user:" + userId); 3969 return; 3970 } 3971 3972 mContext.enforceCallingOrSelfPermission( 3973 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3974 "revokeRuntimePermission"); 3975 3976 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3977 true /* requireFullPermission */, true /* checkShell */, 3978 "revokeRuntimePermission"); 3979 3980 final int appId; 3981 3982 synchronized (mPackages) { 3983 final PackageParser.Package pkg = mPackages.get(packageName); 3984 if (pkg == null) { 3985 throw new IllegalArgumentException("Unknown package: " + packageName); 3986 } 3987 3988 final BasePermission bp = mSettings.mPermissions.get(name); 3989 if (bp == null) { 3990 throw new IllegalArgumentException("Unknown permission: " + name); 3991 } 3992 3993 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3994 3995 // If a permission review is required for legacy apps we represent 3996 // their permissions as always granted runtime ones since we need 3997 // to keep the review required permission flag per user while an 3998 // install permission's state is shared across all users. 3999 if (Build.PERMISSIONS_REVIEW_REQUIRED 4000 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4001 && bp.isRuntime()) { 4002 return; 4003 } 4004 4005 SettingBase sb = (SettingBase) pkg.mExtras; 4006 if (sb == null) { 4007 throw new IllegalArgumentException("Unknown package: " + packageName); 4008 } 4009 4010 final PermissionsState permissionsState = sb.getPermissionsState(); 4011 4012 final int flags = permissionsState.getPermissionFlags(name, userId); 4013 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4014 throw new SecurityException("Cannot revoke system fixed permission " 4015 + name + " for package " + packageName); 4016 } 4017 4018 if (bp.isDevelopment()) { 4019 // Development permissions must be handled specially, since they are not 4020 // normal runtime permissions. For now they apply to all users. 4021 if (permissionsState.revokeInstallPermission(bp) != 4022 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4023 scheduleWriteSettingsLocked(); 4024 } 4025 return; 4026 } 4027 4028 if (permissionsState.revokeRuntimePermission(bp, userId) == 4029 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4030 return; 4031 } 4032 4033 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4034 4035 // Critical, after this call app should never have the permission. 4036 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4037 4038 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4039 } 4040 4041 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4042 } 4043 4044 @Override 4045 public void resetRuntimePermissions() { 4046 mContext.enforceCallingOrSelfPermission( 4047 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4048 "revokeRuntimePermission"); 4049 4050 int callingUid = Binder.getCallingUid(); 4051 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4052 mContext.enforceCallingOrSelfPermission( 4053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4054 "resetRuntimePermissions"); 4055 } 4056 4057 synchronized (mPackages) { 4058 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4059 for (int userId : UserManagerService.getInstance().getUserIds()) { 4060 final int packageCount = mPackages.size(); 4061 for (int i = 0; i < packageCount; i++) { 4062 PackageParser.Package pkg = mPackages.valueAt(i); 4063 if (!(pkg.mExtras instanceof PackageSetting)) { 4064 continue; 4065 } 4066 PackageSetting ps = (PackageSetting) pkg.mExtras; 4067 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4068 } 4069 } 4070 } 4071 } 4072 4073 @Override 4074 public int getPermissionFlags(String name, String packageName, int userId) { 4075 if (!sUserManager.exists(userId)) { 4076 return 0; 4077 } 4078 4079 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4080 4081 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4082 true /* requireFullPermission */, false /* checkShell */, 4083 "getPermissionFlags"); 4084 4085 synchronized (mPackages) { 4086 final PackageParser.Package pkg = mPackages.get(packageName); 4087 if (pkg == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final BasePermission bp = mSettings.mPermissions.get(name); 4092 if (bp == null) { 4093 throw new IllegalArgumentException("Unknown permission: " + name); 4094 } 4095 4096 SettingBase sb = (SettingBase) pkg.mExtras; 4097 if (sb == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 PermissionsState permissionsState = sb.getPermissionsState(); 4102 return permissionsState.getPermissionFlags(name, userId); 4103 } 4104 } 4105 4106 @Override 4107 public void updatePermissionFlags(String name, String packageName, int flagMask, 4108 int flagValues, int userId) { 4109 if (!sUserManager.exists(userId)) { 4110 return; 4111 } 4112 4113 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4114 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4116 true /* requireFullPermission */, true /* checkShell */, 4117 "updatePermissionFlags"); 4118 4119 // Only the system can change these flags and nothing else. 4120 if (getCallingUid() != Process.SYSTEM_UID) { 4121 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4122 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4123 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4124 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4125 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4126 } 4127 4128 synchronized (mPackages) { 4129 final PackageParser.Package pkg = mPackages.get(packageName); 4130 if (pkg == null) { 4131 throw new IllegalArgumentException("Unknown package: " + packageName); 4132 } 4133 4134 final BasePermission bp = mSettings.mPermissions.get(name); 4135 if (bp == null) { 4136 throw new IllegalArgumentException("Unknown permission: " + name); 4137 } 4138 4139 SettingBase sb = (SettingBase) pkg.mExtras; 4140 if (sb == null) { 4141 throw new IllegalArgumentException("Unknown package: " + packageName); 4142 } 4143 4144 PermissionsState permissionsState = sb.getPermissionsState(); 4145 4146 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4147 4148 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4149 // Install and runtime permissions are stored in different places, 4150 // so figure out what permission changed and persist the change. 4151 if (permissionsState.getInstallPermissionState(name) != null) { 4152 scheduleWriteSettingsLocked(); 4153 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4154 || hadState) { 4155 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4156 } 4157 } 4158 } 4159 } 4160 4161 /** 4162 * Update the permission flags for all packages and runtime permissions of a user in order 4163 * to allow device or profile owner to remove POLICY_FIXED. 4164 */ 4165 @Override 4166 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4167 if (!sUserManager.exists(userId)) { 4168 return; 4169 } 4170 4171 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4172 4173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4174 true /* requireFullPermission */, true /* checkShell */, 4175 "updatePermissionFlagsForAllApps"); 4176 4177 // Only the system can change system fixed flags. 4178 if (getCallingUid() != Process.SYSTEM_UID) { 4179 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4180 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4181 } 4182 4183 synchronized (mPackages) { 4184 boolean changed = false; 4185 final int packageCount = mPackages.size(); 4186 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4187 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4188 SettingBase sb = (SettingBase) pkg.mExtras; 4189 if (sb == null) { 4190 continue; 4191 } 4192 PermissionsState permissionsState = sb.getPermissionsState(); 4193 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4194 userId, flagMask, flagValues); 4195 } 4196 if (changed) { 4197 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4198 } 4199 } 4200 } 4201 4202 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4203 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4204 != PackageManager.PERMISSION_GRANTED 4205 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4206 != PackageManager.PERMISSION_GRANTED) { 4207 throw new SecurityException(message + " requires " 4208 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4209 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4210 } 4211 } 4212 4213 @Override 4214 public boolean shouldShowRequestPermissionRationale(String permissionName, 4215 String packageName, int userId) { 4216 if (UserHandle.getCallingUserId() != userId) { 4217 mContext.enforceCallingPermission( 4218 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4219 "canShowRequestPermissionRationale for user " + userId); 4220 } 4221 4222 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4223 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4224 return false; 4225 } 4226 4227 if (checkPermission(permissionName, packageName, userId) 4228 == PackageManager.PERMISSION_GRANTED) { 4229 return false; 4230 } 4231 4232 final int flags; 4233 4234 final long identity = Binder.clearCallingIdentity(); 4235 try { 4236 flags = getPermissionFlags(permissionName, 4237 packageName, userId); 4238 } finally { 4239 Binder.restoreCallingIdentity(identity); 4240 } 4241 4242 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4243 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4244 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4245 4246 if ((flags & fixedFlags) != 0) { 4247 return false; 4248 } 4249 4250 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4251 } 4252 4253 @Override 4254 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4255 mContext.enforceCallingOrSelfPermission( 4256 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4257 "addOnPermissionsChangeListener"); 4258 4259 synchronized (mPackages) { 4260 mOnPermissionChangeListeners.addListenerLocked(listener); 4261 } 4262 } 4263 4264 @Override 4265 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4266 synchronized (mPackages) { 4267 mOnPermissionChangeListeners.removeListenerLocked(listener); 4268 } 4269 } 4270 4271 @Override 4272 public boolean isProtectedBroadcast(String actionName) { 4273 synchronized (mPackages) { 4274 if (mProtectedBroadcasts.contains(actionName)) { 4275 return true; 4276 } else if (actionName != null) { 4277 // TODO: remove these terrible hacks 4278 if (actionName.startsWith("android.net.netmon.lingerExpired") 4279 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4280 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4281 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4282 return true; 4283 } 4284 } 4285 } 4286 return false; 4287 } 4288 4289 @Override 4290 public int checkSignatures(String pkg1, String pkg2) { 4291 synchronized (mPackages) { 4292 final PackageParser.Package p1 = mPackages.get(pkg1); 4293 final PackageParser.Package p2 = mPackages.get(pkg2); 4294 if (p1 == null || p1.mExtras == null 4295 || p2 == null || p2.mExtras == null) { 4296 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4297 } 4298 return compareSignatures(p1.mSignatures, p2.mSignatures); 4299 } 4300 } 4301 4302 @Override 4303 public int checkUidSignatures(int uid1, int uid2) { 4304 // Map to base uids. 4305 uid1 = UserHandle.getAppId(uid1); 4306 uid2 = UserHandle.getAppId(uid2); 4307 // reader 4308 synchronized (mPackages) { 4309 Signature[] s1; 4310 Signature[] s2; 4311 Object obj = mSettings.getUserIdLPr(uid1); 4312 if (obj != null) { 4313 if (obj instanceof SharedUserSetting) { 4314 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4315 } else if (obj instanceof PackageSetting) { 4316 s1 = ((PackageSetting)obj).signatures.mSignatures; 4317 } else { 4318 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4319 } 4320 } else { 4321 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4322 } 4323 obj = mSettings.getUserIdLPr(uid2); 4324 if (obj != null) { 4325 if (obj instanceof SharedUserSetting) { 4326 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4327 } else if (obj instanceof PackageSetting) { 4328 s2 = ((PackageSetting)obj).signatures.mSignatures; 4329 } else { 4330 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4331 } 4332 } else { 4333 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4334 } 4335 return compareSignatures(s1, s2); 4336 } 4337 } 4338 4339 private void killUid(int appId, int userId, String reason) { 4340 final long identity = Binder.clearCallingIdentity(); 4341 try { 4342 IActivityManager am = ActivityManagerNative.getDefault(); 4343 if (am != null) { 4344 try { 4345 am.killUid(appId, userId, reason); 4346 } catch (RemoteException e) { 4347 /* ignore - same process */ 4348 } 4349 } 4350 } finally { 4351 Binder.restoreCallingIdentity(identity); 4352 } 4353 } 4354 4355 /** 4356 * Compares two sets of signatures. Returns: 4357 * <br /> 4358 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4359 * <br /> 4360 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4361 * <br /> 4362 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4363 * <br /> 4364 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4365 * <br /> 4366 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4367 */ 4368 static int compareSignatures(Signature[] s1, Signature[] s2) { 4369 if (s1 == null) { 4370 return s2 == null 4371 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4372 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4373 } 4374 4375 if (s2 == null) { 4376 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4377 } 4378 4379 if (s1.length != s2.length) { 4380 return PackageManager.SIGNATURE_NO_MATCH; 4381 } 4382 4383 // Since both signature sets are of size 1, we can compare without HashSets. 4384 if (s1.length == 1) { 4385 return s1[0].equals(s2[0]) ? 4386 PackageManager.SIGNATURE_MATCH : 4387 PackageManager.SIGNATURE_NO_MATCH; 4388 } 4389 4390 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4391 for (Signature sig : s1) { 4392 set1.add(sig); 4393 } 4394 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4395 for (Signature sig : s2) { 4396 set2.add(sig); 4397 } 4398 // Make sure s2 contains all signatures in s1. 4399 if (set1.equals(set2)) { 4400 return PackageManager.SIGNATURE_MATCH; 4401 } 4402 return PackageManager.SIGNATURE_NO_MATCH; 4403 } 4404 4405 /** 4406 * If the database version for this type of package (internal storage or 4407 * external storage) is less than the version where package signatures 4408 * were updated, return true. 4409 */ 4410 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4411 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4412 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4413 } 4414 4415 /** 4416 * Used for backward compatibility to make sure any packages with 4417 * certificate chains get upgraded to the new style. {@code existingSigs} 4418 * will be in the old format (since they were stored on disk from before the 4419 * system upgrade) and {@code scannedSigs} will be in the newer format. 4420 */ 4421 private int compareSignaturesCompat(PackageSignatures existingSigs, 4422 PackageParser.Package scannedPkg) { 4423 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4424 return PackageManager.SIGNATURE_NO_MATCH; 4425 } 4426 4427 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4428 for (Signature sig : existingSigs.mSignatures) { 4429 existingSet.add(sig); 4430 } 4431 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4432 for (Signature sig : scannedPkg.mSignatures) { 4433 try { 4434 Signature[] chainSignatures = sig.getChainSignatures(); 4435 for (Signature chainSig : chainSignatures) { 4436 scannedCompatSet.add(chainSig); 4437 } 4438 } catch (CertificateEncodingException e) { 4439 scannedCompatSet.add(sig); 4440 } 4441 } 4442 /* 4443 * Make sure the expanded scanned set contains all signatures in the 4444 * existing one. 4445 */ 4446 if (scannedCompatSet.equals(existingSet)) { 4447 // Migrate the old signatures to the new scheme. 4448 existingSigs.assignSignatures(scannedPkg.mSignatures); 4449 // The new KeySets will be re-added later in the scanning process. 4450 synchronized (mPackages) { 4451 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4452 } 4453 return PackageManager.SIGNATURE_MATCH; 4454 } 4455 return PackageManager.SIGNATURE_NO_MATCH; 4456 } 4457 4458 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4459 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4460 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4461 } 4462 4463 private int compareSignaturesRecover(PackageSignatures existingSigs, 4464 PackageParser.Package scannedPkg) { 4465 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4466 return PackageManager.SIGNATURE_NO_MATCH; 4467 } 4468 4469 String msg = null; 4470 try { 4471 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4472 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4473 + scannedPkg.packageName); 4474 return PackageManager.SIGNATURE_MATCH; 4475 } 4476 } catch (CertificateException e) { 4477 msg = e.getMessage(); 4478 } 4479 4480 logCriticalInfo(Log.INFO, 4481 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4482 return PackageManager.SIGNATURE_NO_MATCH; 4483 } 4484 4485 @Override 4486 public List<String> getAllPackages() { 4487 synchronized (mPackages) { 4488 return new ArrayList<String>(mPackages.keySet()); 4489 } 4490 } 4491 4492 @Override 4493 public String[] getPackagesForUid(int uid) { 4494 uid = UserHandle.getAppId(uid); 4495 // reader 4496 synchronized (mPackages) { 4497 Object obj = mSettings.getUserIdLPr(uid); 4498 if (obj instanceof SharedUserSetting) { 4499 final SharedUserSetting sus = (SharedUserSetting) obj; 4500 final int N = sus.packages.size(); 4501 final String[] res = new String[N]; 4502 final Iterator<PackageSetting> it = sus.packages.iterator(); 4503 int i = 0; 4504 while (it.hasNext()) { 4505 res[i++] = it.next().name; 4506 } 4507 return res; 4508 } else if (obj instanceof PackageSetting) { 4509 final PackageSetting ps = (PackageSetting) obj; 4510 return new String[] { ps.name }; 4511 } 4512 } 4513 return null; 4514 } 4515 4516 @Override 4517 public String getNameForUid(int uid) { 4518 // reader 4519 synchronized (mPackages) { 4520 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4521 if (obj instanceof SharedUserSetting) { 4522 final SharedUserSetting sus = (SharedUserSetting) obj; 4523 return sus.name + ":" + sus.userId; 4524 } else if (obj instanceof PackageSetting) { 4525 final PackageSetting ps = (PackageSetting) obj; 4526 return ps.name; 4527 } 4528 } 4529 return null; 4530 } 4531 4532 @Override 4533 public int getUidForSharedUser(String sharedUserName) { 4534 if(sharedUserName == null) { 4535 return -1; 4536 } 4537 // reader 4538 synchronized (mPackages) { 4539 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4540 if (suid == null) { 4541 return -1; 4542 } 4543 return suid.userId; 4544 } 4545 } 4546 4547 @Override 4548 public int getFlagsForUid(int uid) { 4549 synchronized (mPackages) { 4550 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4551 if (obj instanceof SharedUserSetting) { 4552 final SharedUserSetting sus = (SharedUserSetting) obj; 4553 return sus.pkgFlags; 4554 } else if (obj instanceof PackageSetting) { 4555 final PackageSetting ps = (PackageSetting) obj; 4556 return ps.pkgFlags; 4557 } 4558 } 4559 return 0; 4560 } 4561 4562 @Override 4563 public int getPrivateFlagsForUid(int uid) { 4564 synchronized (mPackages) { 4565 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4566 if (obj instanceof SharedUserSetting) { 4567 final SharedUserSetting sus = (SharedUserSetting) obj; 4568 return sus.pkgPrivateFlags; 4569 } else if (obj instanceof PackageSetting) { 4570 final PackageSetting ps = (PackageSetting) obj; 4571 return ps.pkgPrivateFlags; 4572 } 4573 } 4574 return 0; 4575 } 4576 4577 @Override 4578 public boolean isUidPrivileged(int uid) { 4579 uid = UserHandle.getAppId(uid); 4580 // reader 4581 synchronized (mPackages) { 4582 Object obj = mSettings.getUserIdLPr(uid); 4583 if (obj instanceof SharedUserSetting) { 4584 final SharedUserSetting sus = (SharedUserSetting) obj; 4585 final Iterator<PackageSetting> it = sus.packages.iterator(); 4586 while (it.hasNext()) { 4587 if (it.next().isPrivileged()) { 4588 return true; 4589 } 4590 } 4591 } else if (obj instanceof PackageSetting) { 4592 final PackageSetting ps = (PackageSetting) obj; 4593 return ps.isPrivileged(); 4594 } 4595 } 4596 return false; 4597 } 4598 4599 @Override 4600 public String[] getAppOpPermissionPackages(String permissionName) { 4601 synchronized (mPackages) { 4602 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4603 if (pkgs == null) { 4604 return null; 4605 } 4606 return pkgs.toArray(new String[pkgs.size()]); 4607 } 4608 } 4609 4610 @Override 4611 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4612 int flags, int userId) { 4613 try { 4614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4615 4616 if (!sUserManager.exists(userId)) return null; 4617 flags = updateFlagsForResolve(flags, userId, intent); 4618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4619 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4620 4621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4622 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4623 flags, userId); 4624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4625 4626 final ResolveInfo bestChoice = 4627 chooseBestActivity(intent, resolvedType, flags, query, userId); 4628 4629 if (isEphemeralAllowed(intent, query, userId)) { 4630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4631 final EphemeralResolveInfo ai = 4632 getEphemeralResolveInfo(intent, resolvedType, userId); 4633 if (ai != null) { 4634 if (DEBUG_EPHEMERAL) { 4635 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4636 } 4637 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4638 bestChoice.ephemeralResolveInfo = ai; 4639 } 4640 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4641 } 4642 return bestChoice; 4643 } finally { 4644 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4645 } 4646 } 4647 4648 @Override 4649 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4650 IntentFilter filter, int match, ComponentName activity) { 4651 final int userId = UserHandle.getCallingUserId(); 4652 if (DEBUG_PREFERRED) { 4653 Log.v(TAG, "setLastChosenActivity intent=" + intent 4654 + " resolvedType=" + resolvedType 4655 + " flags=" + flags 4656 + " filter=" + filter 4657 + " match=" + match 4658 + " activity=" + activity); 4659 filter.dump(new PrintStreamPrinter(System.out), " "); 4660 } 4661 intent.setComponent(null); 4662 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4663 userId); 4664 // Find any earlier preferred or last chosen entries and nuke them 4665 findPreferredActivity(intent, resolvedType, 4666 flags, query, 0, false, true, false, userId); 4667 // Add the new activity as the last chosen for this filter 4668 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4669 "Setting last chosen"); 4670 } 4671 4672 @Override 4673 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4674 final int userId = UserHandle.getCallingUserId(); 4675 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4676 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4677 userId); 4678 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4679 false, false, false, userId); 4680 } 4681 4682 4683 private boolean isEphemeralAllowed( 4684 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4685 // Short circuit and return early if possible. 4686 if (DISABLE_EPHEMERAL_APPS) { 4687 return false; 4688 } 4689 final int callingUser = UserHandle.getCallingUserId(); 4690 if (callingUser != UserHandle.USER_SYSTEM) { 4691 return false; 4692 } 4693 if (mEphemeralResolverConnection == null) { 4694 return false; 4695 } 4696 if (intent.getComponent() != null) { 4697 return false; 4698 } 4699 if (intent.getPackage() != null) { 4700 return false; 4701 } 4702 final boolean isWebUri = hasWebURI(intent); 4703 if (!isWebUri) { 4704 return false; 4705 } 4706 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4707 synchronized (mPackages) { 4708 final int count = resolvedActivites.size(); 4709 for (int n = 0; n < count; n++) { 4710 ResolveInfo info = resolvedActivites.get(n); 4711 String packageName = info.activityInfo.packageName; 4712 PackageSetting ps = mSettings.mPackages.get(packageName); 4713 if (ps != null) { 4714 // Try to get the status from User settings first 4715 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4716 int status = (int) (packedStatus >> 32); 4717 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4718 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4719 if (DEBUG_EPHEMERAL) { 4720 Slog.v(TAG, "DENY ephemeral apps;" 4721 + " pkg: " + packageName + ", status: " + status); 4722 } 4723 return false; 4724 } 4725 } 4726 } 4727 } 4728 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4729 return true; 4730 } 4731 4732 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4733 int userId) { 4734 MessageDigest digest = null; 4735 try { 4736 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4737 } catch (NoSuchAlgorithmException e) { 4738 // If we can't create a digest, ignore ephemeral apps. 4739 return null; 4740 } 4741 4742 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4743 final byte[] digestBytes = digest.digest(hostBytes); 4744 int shaPrefix = 4745 digestBytes[0] << 24 4746 | digestBytes[1] << 16 4747 | digestBytes[2] << 8 4748 | digestBytes[3] << 0; 4749 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4750 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4751 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4752 // No hash prefix match; there are no ephemeral apps for this domain. 4753 return null; 4754 } 4755 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4756 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4757 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4758 continue; 4759 } 4760 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4761 // No filters; this should never happen. 4762 if (filters.isEmpty()) { 4763 continue; 4764 } 4765 // We have a domain match; resolve the filters to see if anything matches. 4766 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4767 for (int j = filters.size() - 1; j >= 0; --j) { 4768 final EphemeralResolveIntentInfo intentInfo = 4769 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4770 ephemeralResolver.addFilter(intentInfo); 4771 } 4772 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4773 intent, resolvedType, false /*defaultOnly*/, userId); 4774 if (!matchedResolveInfoList.isEmpty()) { 4775 return matchedResolveInfoList.get(0); 4776 } 4777 } 4778 // Hash or filter mis-match; no ephemeral apps for this domain. 4779 return null; 4780 } 4781 4782 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4783 int flags, List<ResolveInfo> query, int userId) { 4784 if (query != null) { 4785 final int N = query.size(); 4786 if (N == 1) { 4787 return query.get(0); 4788 } else if (N > 1) { 4789 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4790 // If there is more than one activity with the same priority, 4791 // then let the user decide between them. 4792 ResolveInfo r0 = query.get(0); 4793 ResolveInfo r1 = query.get(1); 4794 if (DEBUG_INTENT_MATCHING || debug) { 4795 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4796 + r1.activityInfo.name + "=" + r1.priority); 4797 } 4798 // If the first activity has a higher priority, or a different 4799 // default, then it is always desirable to pick it. 4800 if (r0.priority != r1.priority 4801 || r0.preferredOrder != r1.preferredOrder 4802 || r0.isDefault != r1.isDefault) { 4803 return query.get(0); 4804 } 4805 // If we have saved a preference for a preferred activity for 4806 // this Intent, use that. 4807 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4808 flags, query, r0.priority, true, false, debug, userId); 4809 if (ri != null) { 4810 return ri; 4811 } 4812 ri = new ResolveInfo(mResolveInfo); 4813 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4814 ri.activityInfo.applicationInfo = new ApplicationInfo( 4815 ri.activityInfo.applicationInfo); 4816 if (userId != 0) { 4817 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4818 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4819 } 4820 // Make sure that the resolver is displayable in car mode 4821 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4822 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4823 return ri; 4824 } 4825 } 4826 return null; 4827 } 4828 4829 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4830 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4831 final int N = query.size(); 4832 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4833 .get(userId); 4834 // Get the list of persistent preferred activities that handle the intent 4835 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4836 List<PersistentPreferredActivity> pprefs = ppir != null 4837 ? ppir.queryIntent(intent, resolvedType, 4838 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4839 : null; 4840 if (pprefs != null && pprefs.size() > 0) { 4841 final int M = pprefs.size(); 4842 for (int i=0; i<M; i++) { 4843 final PersistentPreferredActivity ppa = pprefs.get(i); 4844 if (DEBUG_PREFERRED || debug) { 4845 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4846 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4847 + "\n component=" + ppa.mComponent); 4848 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4849 } 4850 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4851 flags | MATCH_DISABLED_COMPONENTS, userId); 4852 if (DEBUG_PREFERRED || debug) { 4853 Slog.v(TAG, "Found persistent preferred activity:"); 4854 if (ai != null) { 4855 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4856 } else { 4857 Slog.v(TAG, " null"); 4858 } 4859 } 4860 if (ai == null) { 4861 // This previously registered persistent preferred activity 4862 // component is no longer known. Ignore it and do NOT remove it. 4863 continue; 4864 } 4865 for (int j=0; j<N; j++) { 4866 final ResolveInfo ri = query.get(j); 4867 if (!ri.activityInfo.applicationInfo.packageName 4868 .equals(ai.applicationInfo.packageName)) { 4869 continue; 4870 } 4871 if (!ri.activityInfo.name.equals(ai.name)) { 4872 continue; 4873 } 4874 // Found a persistent preference that can handle the intent. 4875 if (DEBUG_PREFERRED || debug) { 4876 Slog.v(TAG, "Returning persistent preferred activity: " + 4877 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4878 } 4879 return ri; 4880 } 4881 } 4882 } 4883 return null; 4884 } 4885 4886 // TODO: handle preferred activities missing while user has amnesia 4887 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4888 List<ResolveInfo> query, int priority, boolean always, 4889 boolean removeMatches, boolean debug, int userId) { 4890 if (!sUserManager.exists(userId)) return null; 4891 flags = updateFlagsForResolve(flags, userId, intent); 4892 // writer 4893 synchronized (mPackages) { 4894 if (intent.getSelector() != null) { 4895 intent = intent.getSelector(); 4896 } 4897 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4898 4899 // Try to find a matching persistent preferred activity. 4900 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4901 debug, userId); 4902 4903 // If a persistent preferred activity matched, use it. 4904 if (pri != null) { 4905 return pri; 4906 } 4907 4908 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4909 // Get the list of preferred activities that handle the intent 4910 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4911 List<PreferredActivity> prefs = pir != null 4912 ? pir.queryIntent(intent, resolvedType, 4913 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4914 : null; 4915 if (prefs != null && prefs.size() > 0) { 4916 boolean changed = false; 4917 try { 4918 // First figure out how good the original match set is. 4919 // We will only allow preferred activities that came 4920 // from the same match quality. 4921 int match = 0; 4922 4923 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4924 4925 final int N = query.size(); 4926 for (int j=0; j<N; j++) { 4927 final ResolveInfo ri = query.get(j); 4928 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4929 + ": 0x" + Integer.toHexString(match)); 4930 if (ri.match > match) { 4931 match = ri.match; 4932 } 4933 } 4934 4935 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4936 + Integer.toHexString(match)); 4937 4938 match &= IntentFilter.MATCH_CATEGORY_MASK; 4939 final int M = prefs.size(); 4940 for (int i=0; i<M; i++) { 4941 final PreferredActivity pa = prefs.get(i); 4942 if (DEBUG_PREFERRED || debug) { 4943 Slog.v(TAG, "Checking PreferredActivity ds=" 4944 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4945 + "\n component=" + pa.mPref.mComponent); 4946 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4947 } 4948 if (pa.mPref.mMatch != match) { 4949 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4950 + Integer.toHexString(pa.mPref.mMatch)); 4951 continue; 4952 } 4953 // If it's not an "always" type preferred activity and that's what we're 4954 // looking for, skip it. 4955 if (always && !pa.mPref.mAlways) { 4956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4957 continue; 4958 } 4959 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4960 flags | MATCH_DISABLED_COMPONENTS, userId); 4961 if (DEBUG_PREFERRED || debug) { 4962 Slog.v(TAG, "Found preferred activity:"); 4963 if (ai != null) { 4964 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4965 } else { 4966 Slog.v(TAG, " null"); 4967 } 4968 } 4969 if (ai == null) { 4970 // This previously registered preferred activity 4971 // component is no longer known. Most likely an update 4972 // to the app was installed and in the new version this 4973 // component no longer exists. Clean it up by removing 4974 // it from the preferred activities list, and skip it. 4975 Slog.w(TAG, "Removing dangling preferred activity: " 4976 + pa.mPref.mComponent); 4977 pir.removeFilter(pa); 4978 changed = true; 4979 continue; 4980 } 4981 for (int j=0; j<N; j++) { 4982 final ResolveInfo ri = query.get(j); 4983 if (!ri.activityInfo.applicationInfo.packageName 4984 .equals(ai.applicationInfo.packageName)) { 4985 continue; 4986 } 4987 if (!ri.activityInfo.name.equals(ai.name)) { 4988 continue; 4989 } 4990 4991 if (removeMatches) { 4992 pir.removeFilter(pa); 4993 changed = true; 4994 if (DEBUG_PREFERRED) { 4995 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4996 } 4997 break; 4998 } 4999 5000 // Okay we found a previously set preferred or last chosen app. 5001 // If the result set is different from when this 5002 // was created, we need to clear it and re-ask the 5003 // user their preference, if we're looking for an "always" type entry. 5004 if (always && !pa.mPref.sameSet(query)) { 5005 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5006 + intent + " type " + resolvedType); 5007 if (DEBUG_PREFERRED) { 5008 Slog.v(TAG, "Removing preferred activity since set changed " 5009 + pa.mPref.mComponent); 5010 } 5011 pir.removeFilter(pa); 5012 // Re-add the filter as a "last chosen" entry (!always) 5013 PreferredActivity lastChosen = new PreferredActivity( 5014 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5015 pir.addFilter(lastChosen); 5016 changed = true; 5017 return null; 5018 } 5019 5020 // Yay! Either the set matched or we're looking for the last chosen 5021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5022 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5023 return ri; 5024 } 5025 } 5026 } finally { 5027 if (changed) { 5028 if (DEBUG_PREFERRED) { 5029 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5030 } 5031 scheduleWritePackageRestrictionsLocked(userId); 5032 } 5033 } 5034 } 5035 } 5036 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5037 return null; 5038 } 5039 5040 /* 5041 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5042 */ 5043 @Override 5044 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5045 int targetUserId) { 5046 mContext.enforceCallingOrSelfPermission( 5047 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5048 List<CrossProfileIntentFilter> matches = 5049 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5050 if (matches != null) { 5051 int size = matches.size(); 5052 for (int i = 0; i < size; i++) { 5053 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5054 } 5055 } 5056 if (hasWebURI(intent)) { 5057 // cross-profile app linking works only towards the parent. 5058 final UserInfo parent = getProfileParent(sourceUserId); 5059 synchronized(mPackages) { 5060 int flags = updateFlagsForResolve(0, parent.id, intent); 5061 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5062 intent, resolvedType, flags, sourceUserId, parent.id); 5063 return xpDomainInfo != null; 5064 } 5065 } 5066 return false; 5067 } 5068 5069 private UserInfo getProfileParent(int userId) { 5070 final long identity = Binder.clearCallingIdentity(); 5071 try { 5072 return sUserManager.getProfileParent(userId); 5073 } finally { 5074 Binder.restoreCallingIdentity(identity); 5075 } 5076 } 5077 5078 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5079 String resolvedType, int userId) { 5080 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5081 if (resolver != null) { 5082 return resolver.queryIntent(intent, resolvedType, false, userId); 5083 } 5084 return null; 5085 } 5086 5087 @Override 5088 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5089 String resolvedType, int flags, int userId) { 5090 try { 5091 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5092 5093 return new ParceledListSlice<>( 5094 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5095 } finally { 5096 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5097 } 5098 } 5099 5100 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5101 String resolvedType, int flags, int userId) { 5102 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5103 flags = updateFlagsForResolve(flags, userId, intent); 5104 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5105 false /* requireFullPermission */, false /* checkShell */, 5106 "query intent activities"); 5107 ComponentName comp = intent.getComponent(); 5108 if (comp == null) { 5109 if (intent.getSelector() != null) { 5110 intent = intent.getSelector(); 5111 comp = intent.getComponent(); 5112 } 5113 } 5114 5115 if (comp != null) { 5116 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5117 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5118 if (ai != null) { 5119 final ResolveInfo ri = new ResolveInfo(); 5120 ri.activityInfo = ai; 5121 list.add(ri); 5122 } 5123 return list; 5124 } 5125 5126 // reader 5127 synchronized (mPackages) { 5128 final String pkgName = intent.getPackage(); 5129 if (pkgName == null) { 5130 List<CrossProfileIntentFilter> matchingFilters = 5131 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5132 // Check for results that need to skip the current profile. 5133 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5134 resolvedType, flags, userId); 5135 if (xpResolveInfo != null) { 5136 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5137 result.add(xpResolveInfo); 5138 return filterIfNotSystemUser(result, userId); 5139 } 5140 5141 // Check for results in the current profile. 5142 List<ResolveInfo> result = mActivities.queryIntent( 5143 intent, resolvedType, flags, userId); 5144 result = filterIfNotSystemUser(result, userId); 5145 5146 // Check for cross profile results. 5147 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5148 xpResolveInfo = queryCrossProfileIntents( 5149 matchingFilters, intent, resolvedType, flags, userId, 5150 hasNonNegativePriorityResult); 5151 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5152 boolean isVisibleToUser = filterIfNotSystemUser( 5153 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5154 if (isVisibleToUser) { 5155 result.add(xpResolveInfo); 5156 Collections.sort(result, mResolvePrioritySorter); 5157 } 5158 } 5159 if (hasWebURI(intent)) { 5160 CrossProfileDomainInfo xpDomainInfo = null; 5161 final UserInfo parent = getProfileParent(userId); 5162 if (parent != null) { 5163 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5164 flags, userId, parent.id); 5165 } 5166 if (xpDomainInfo != null) { 5167 if (xpResolveInfo != null) { 5168 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5169 // in the result. 5170 result.remove(xpResolveInfo); 5171 } 5172 if (result.size() == 0) { 5173 result.add(xpDomainInfo.resolveInfo); 5174 return result; 5175 } 5176 } else if (result.size() <= 1) { 5177 return result; 5178 } 5179 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5180 xpDomainInfo, userId); 5181 Collections.sort(result, mResolvePrioritySorter); 5182 } 5183 return result; 5184 } 5185 final PackageParser.Package pkg = mPackages.get(pkgName); 5186 if (pkg != null) { 5187 return filterIfNotSystemUser( 5188 mActivities.queryIntentForPackage( 5189 intent, resolvedType, flags, pkg.activities, userId), 5190 userId); 5191 } 5192 return new ArrayList<ResolveInfo>(); 5193 } 5194 } 5195 5196 private static class CrossProfileDomainInfo { 5197 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5198 ResolveInfo resolveInfo; 5199 /* Best domain verification status of the activities found in the other profile */ 5200 int bestDomainVerificationStatus; 5201 } 5202 5203 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5204 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5205 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5206 sourceUserId)) { 5207 return null; 5208 } 5209 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5210 resolvedType, flags, parentUserId); 5211 5212 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5213 return null; 5214 } 5215 CrossProfileDomainInfo result = null; 5216 int size = resultTargetUser.size(); 5217 for (int i = 0; i < size; i++) { 5218 ResolveInfo riTargetUser = resultTargetUser.get(i); 5219 // Intent filter verification is only for filters that specify a host. So don't return 5220 // those that handle all web uris. 5221 if (riTargetUser.handleAllWebDataURI) { 5222 continue; 5223 } 5224 String packageName = riTargetUser.activityInfo.packageName; 5225 PackageSetting ps = mSettings.mPackages.get(packageName); 5226 if (ps == null) { 5227 continue; 5228 } 5229 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5230 int status = (int)(verificationState >> 32); 5231 if (result == null) { 5232 result = new CrossProfileDomainInfo(); 5233 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5234 sourceUserId, parentUserId); 5235 result.bestDomainVerificationStatus = status; 5236 } else { 5237 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5238 result.bestDomainVerificationStatus); 5239 } 5240 } 5241 // Don't consider matches with status NEVER across profiles. 5242 if (result != null && result.bestDomainVerificationStatus 5243 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5244 return null; 5245 } 5246 return result; 5247 } 5248 5249 /** 5250 * Verification statuses are ordered from the worse to the best, except for 5251 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5252 */ 5253 private int bestDomainVerificationStatus(int status1, int status2) { 5254 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5255 return status2; 5256 } 5257 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5258 return status1; 5259 } 5260 return (int) MathUtils.max(status1, status2); 5261 } 5262 5263 private boolean isUserEnabled(int userId) { 5264 long callingId = Binder.clearCallingIdentity(); 5265 try { 5266 UserInfo userInfo = sUserManager.getUserInfo(userId); 5267 return userInfo != null && userInfo.isEnabled(); 5268 } finally { 5269 Binder.restoreCallingIdentity(callingId); 5270 } 5271 } 5272 5273 /** 5274 * Filter out activities with systemUserOnly flag set, when current user is not System. 5275 * 5276 * @return filtered list 5277 */ 5278 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5279 if (userId == UserHandle.USER_SYSTEM) { 5280 return resolveInfos; 5281 } 5282 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5283 ResolveInfo info = resolveInfos.get(i); 5284 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5285 resolveInfos.remove(i); 5286 } 5287 } 5288 return resolveInfos; 5289 } 5290 5291 /** 5292 * @param resolveInfos list of resolve infos in descending priority order 5293 * @return if the list contains a resolve info with non-negative priority 5294 */ 5295 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5296 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5297 } 5298 5299 private static boolean hasWebURI(Intent intent) { 5300 if (intent.getData() == null) { 5301 return false; 5302 } 5303 final String scheme = intent.getScheme(); 5304 if (TextUtils.isEmpty(scheme)) { 5305 return false; 5306 } 5307 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5308 } 5309 5310 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5311 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5312 int userId) { 5313 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5314 5315 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5316 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5317 candidates.size()); 5318 } 5319 5320 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5321 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5322 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5323 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5324 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5325 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5326 5327 synchronized (mPackages) { 5328 final int count = candidates.size(); 5329 // First, try to use linked apps. Partition the candidates into four lists: 5330 // one for the final results, one for the "do not use ever", one for "undefined status" 5331 // and finally one for "browser app type". 5332 for (int n=0; n<count; n++) { 5333 ResolveInfo info = candidates.get(n); 5334 String packageName = info.activityInfo.packageName; 5335 PackageSetting ps = mSettings.mPackages.get(packageName); 5336 if (ps != null) { 5337 // Add to the special match all list (Browser use case) 5338 if (info.handleAllWebDataURI) { 5339 matchAllList.add(info); 5340 continue; 5341 } 5342 // Try to get the status from User settings first 5343 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5344 int status = (int)(packedStatus >> 32); 5345 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5346 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5347 if (DEBUG_DOMAIN_VERIFICATION) { 5348 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5349 + " : linkgen=" + linkGeneration); 5350 } 5351 // Use link-enabled generation as preferredOrder, i.e. 5352 // prefer newly-enabled over earlier-enabled. 5353 info.preferredOrder = linkGeneration; 5354 alwaysList.add(info); 5355 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5356 if (DEBUG_DOMAIN_VERIFICATION) { 5357 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5358 } 5359 neverList.add(info); 5360 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5361 if (DEBUG_DOMAIN_VERIFICATION) { 5362 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5363 } 5364 alwaysAskList.add(info); 5365 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5366 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5367 if (DEBUG_DOMAIN_VERIFICATION) { 5368 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5369 } 5370 undefinedList.add(info); 5371 } 5372 } 5373 } 5374 5375 // We'll want to include browser possibilities in a few cases 5376 boolean includeBrowser = false; 5377 5378 // First try to add the "always" resolution(s) for the current user, if any 5379 if (alwaysList.size() > 0) { 5380 result.addAll(alwaysList); 5381 } else { 5382 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5383 result.addAll(undefinedList); 5384 // Maybe add one for the other profile. 5385 if (xpDomainInfo != null && ( 5386 xpDomainInfo.bestDomainVerificationStatus 5387 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5388 result.add(xpDomainInfo.resolveInfo); 5389 } 5390 includeBrowser = true; 5391 } 5392 5393 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5394 // If there were 'always' entries their preferred order has been set, so we also 5395 // back that off to make the alternatives equivalent 5396 if (alwaysAskList.size() > 0) { 5397 for (ResolveInfo i : result) { 5398 i.preferredOrder = 0; 5399 } 5400 result.addAll(alwaysAskList); 5401 includeBrowser = true; 5402 } 5403 5404 if (includeBrowser) { 5405 // Also add browsers (all of them or only the default one) 5406 if (DEBUG_DOMAIN_VERIFICATION) { 5407 Slog.v(TAG, " ...including browsers in candidate set"); 5408 } 5409 if ((matchFlags & MATCH_ALL) != 0) { 5410 result.addAll(matchAllList); 5411 } else { 5412 // Browser/generic handling case. If there's a default browser, go straight 5413 // to that (but only if there is no other higher-priority match). 5414 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5415 int maxMatchPrio = 0; 5416 ResolveInfo defaultBrowserMatch = null; 5417 final int numCandidates = matchAllList.size(); 5418 for (int n = 0; n < numCandidates; n++) { 5419 ResolveInfo info = matchAllList.get(n); 5420 // track the highest overall match priority... 5421 if (info.priority > maxMatchPrio) { 5422 maxMatchPrio = info.priority; 5423 } 5424 // ...and the highest-priority default browser match 5425 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5426 if (defaultBrowserMatch == null 5427 || (defaultBrowserMatch.priority < info.priority)) { 5428 if (debug) { 5429 Slog.v(TAG, "Considering default browser match " + info); 5430 } 5431 defaultBrowserMatch = info; 5432 } 5433 } 5434 } 5435 if (defaultBrowserMatch != null 5436 && defaultBrowserMatch.priority >= maxMatchPrio 5437 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5438 { 5439 if (debug) { 5440 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5441 } 5442 result.add(defaultBrowserMatch); 5443 } else { 5444 result.addAll(matchAllList); 5445 } 5446 } 5447 5448 // If there is nothing selected, add all candidates and remove the ones that the user 5449 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5450 if (result.size() == 0) { 5451 result.addAll(candidates); 5452 result.removeAll(neverList); 5453 } 5454 } 5455 } 5456 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5457 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5458 result.size()); 5459 for (ResolveInfo info : result) { 5460 Slog.v(TAG, " + " + info.activityInfo); 5461 } 5462 } 5463 return result; 5464 } 5465 5466 // Returns a packed value as a long: 5467 // 5468 // high 'int'-sized word: link status: undefined/ask/never/always. 5469 // low 'int'-sized word: relative priority among 'always' results. 5470 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5471 long result = ps.getDomainVerificationStatusForUser(userId); 5472 // if none available, get the master status 5473 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5474 if (ps.getIntentFilterVerificationInfo() != null) { 5475 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5476 } 5477 } 5478 return result; 5479 } 5480 5481 private ResolveInfo querySkipCurrentProfileIntents( 5482 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5483 int flags, int sourceUserId) { 5484 if (matchingFilters != null) { 5485 int size = matchingFilters.size(); 5486 for (int i = 0; i < size; i ++) { 5487 CrossProfileIntentFilter filter = matchingFilters.get(i); 5488 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5489 // Checking if there are activities in the target user that can handle the 5490 // intent. 5491 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5492 resolvedType, flags, sourceUserId); 5493 if (resolveInfo != null) { 5494 return resolveInfo; 5495 } 5496 } 5497 } 5498 } 5499 return null; 5500 } 5501 5502 // Return matching ResolveInfo in target user if any. 5503 private ResolveInfo queryCrossProfileIntents( 5504 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5505 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5506 if (matchingFilters != null) { 5507 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5508 // match the same intent. For performance reasons, it is better not to 5509 // run queryIntent twice for the same userId 5510 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5511 int size = matchingFilters.size(); 5512 for (int i = 0; i < size; i++) { 5513 CrossProfileIntentFilter filter = matchingFilters.get(i); 5514 int targetUserId = filter.getTargetUserId(); 5515 boolean skipCurrentProfile = 5516 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5517 boolean skipCurrentProfileIfNoMatchFound = 5518 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5519 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5520 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5521 // Checking if there are activities in the target user that can handle the 5522 // intent. 5523 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5524 resolvedType, flags, sourceUserId); 5525 if (resolveInfo != null) return resolveInfo; 5526 alreadyTriedUserIds.put(targetUserId, true); 5527 } 5528 } 5529 } 5530 return null; 5531 } 5532 5533 /** 5534 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5535 * will forward the intent to the filter's target user. 5536 * Otherwise, returns null. 5537 */ 5538 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5539 String resolvedType, int flags, int sourceUserId) { 5540 int targetUserId = filter.getTargetUserId(); 5541 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5542 resolvedType, flags, targetUserId); 5543 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5544 // If all the matches in the target profile are suspended, return null. 5545 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5546 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5547 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5548 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5549 targetUserId); 5550 } 5551 } 5552 } 5553 return null; 5554 } 5555 5556 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5557 int sourceUserId, int targetUserId) { 5558 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5559 long ident = Binder.clearCallingIdentity(); 5560 boolean targetIsProfile; 5561 try { 5562 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5563 } finally { 5564 Binder.restoreCallingIdentity(ident); 5565 } 5566 String className; 5567 if (targetIsProfile) { 5568 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5569 } else { 5570 className = FORWARD_INTENT_TO_PARENT; 5571 } 5572 ComponentName forwardingActivityComponentName = new ComponentName( 5573 mAndroidApplication.packageName, className); 5574 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5575 sourceUserId); 5576 if (!targetIsProfile) { 5577 forwardingActivityInfo.showUserIcon = targetUserId; 5578 forwardingResolveInfo.noResourceId = true; 5579 } 5580 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5581 forwardingResolveInfo.priority = 0; 5582 forwardingResolveInfo.preferredOrder = 0; 5583 forwardingResolveInfo.match = 0; 5584 forwardingResolveInfo.isDefault = true; 5585 forwardingResolveInfo.filter = filter; 5586 forwardingResolveInfo.targetUserId = targetUserId; 5587 return forwardingResolveInfo; 5588 } 5589 5590 @Override 5591 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5592 Intent[] specifics, String[] specificTypes, Intent intent, 5593 String resolvedType, int flags, int userId) { 5594 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5595 specificTypes, intent, resolvedType, flags, userId)); 5596 } 5597 5598 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5599 Intent[] specifics, String[] specificTypes, Intent intent, 5600 String resolvedType, int flags, int userId) { 5601 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5602 flags = updateFlagsForResolve(flags, userId, intent); 5603 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5604 false /* requireFullPermission */, false /* checkShell */, 5605 "query intent activity options"); 5606 final String resultsAction = intent.getAction(); 5607 5608 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5609 | PackageManager.GET_RESOLVED_FILTER, userId); 5610 5611 if (DEBUG_INTENT_MATCHING) { 5612 Log.v(TAG, "Query " + intent + ": " + results); 5613 } 5614 5615 int specificsPos = 0; 5616 int N; 5617 5618 // todo: note that the algorithm used here is O(N^2). This 5619 // isn't a problem in our current environment, but if we start running 5620 // into situations where we have more than 5 or 10 matches then this 5621 // should probably be changed to something smarter... 5622 5623 // First we go through and resolve each of the specific items 5624 // that were supplied, taking care of removing any corresponding 5625 // duplicate items in the generic resolve list. 5626 if (specifics != null) { 5627 for (int i=0; i<specifics.length; i++) { 5628 final Intent sintent = specifics[i]; 5629 if (sintent == null) { 5630 continue; 5631 } 5632 5633 if (DEBUG_INTENT_MATCHING) { 5634 Log.v(TAG, "Specific #" + i + ": " + sintent); 5635 } 5636 5637 String action = sintent.getAction(); 5638 if (resultsAction != null && resultsAction.equals(action)) { 5639 // If this action was explicitly requested, then don't 5640 // remove things that have it. 5641 action = null; 5642 } 5643 5644 ResolveInfo ri = null; 5645 ActivityInfo ai = null; 5646 5647 ComponentName comp = sintent.getComponent(); 5648 if (comp == null) { 5649 ri = resolveIntent( 5650 sintent, 5651 specificTypes != null ? specificTypes[i] : null, 5652 flags, userId); 5653 if (ri == null) { 5654 continue; 5655 } 5656 if (ri == mResolveInfo) { 5657 // ACK! Must do something better with this. 5658 } 5659 ai = ri.activityInfo; 5660 comp = new ComponentName(ai.applicationInfo.packageName, 5661 ai.name); 5662 } else { 5663 ai = getActivityInfo(comp, flags, userId); 5664 if (ai == null) { 5665 continue; 5666 } 5667 } 5668 5669 // Look for any generic query activities that are duplicates 5670 // of this specific one, and remove them from the results. 5671 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5672 N = results.size(); 5673 int j; 5674 for (j=specificsPos; j<N; j++) { 5675 ResolveInfo sri = results.get(j); 5676 if ((sri.activityInfo.name.equals(comp.getClassName()) 5677 && sri.activityInfo.applicationInfo.packageName.equals( 5678 comp.getPackageName())) 5679 || (action != null && sri.filter.matchAction(action))) { 5680 results.remove(j); 5681 if (DEBUG_INTENT_MATCHING) Log.v( 5682 TAG, "Removing duplicate item from " + j 5683 + " due to specific " + specificsPos); 5684 if (ri == null) { 5685 ri = sri; 5686 } 5687 j--; 5688 N--; 5689 } 5690 } 5691 5692 // Add this specific item to its proper place. 5693 if (ri == null) { 5694 ri = new ResolveInfo(); 5695 ri.activityInfo = ai; 5696 } 5697 results.add(specificsPos, ri); 5698 ri.specificIndex = i; 5699 specificsPos++; 5700 } 5701 } 5702 5703 // Now we go through the remaining generic results and remove any 5704 // duplicate actions that are found here. 5705 N = results.size(); 5706 for (int i=specificsPos; i<N-1; i++) { 5707 final ResolveInfo rii = results.get(i); 5708 if (rii.filter == null) { 5709 continue; 5710 } 5711 5712 // Iterate over all of the actions of this result's intent 5713 // filter... typically this should be just one. 5714 final Iterator<String> it = rii.filter.actionsIterator(); 5715 if (it == null) { 5716 continue; 5717 } 5718 while (it.hasNext()) { 5719 final String action = it.next(); 5720 if (resultsAction != null && resultsAction.equals(action)) { 5721 // If this action was explicitly requested, then don't 5722 // remove things that have it. 5723 continue; 5724 } 5725 for (int j=i+1; j<N; j++) { 5726 final ResolveInfo rij = results.get(j); 5727 if (rij.filter != null && rij.filter.hasAction(action)) { 5728 results.remove(j); 5729 if (DEBUG_INTENT_MATCHING) Log.v( 5730 TAG, "Removing duplicate item from " + j 5731 + " due to action " + action + " at " + i); 5732 j--; 5733 N--; 5734 } 5735 } 5736 } 5737 5738 // If the caller didn't request filter information, drop it now 5739 // so we don't have to marshall/unmarshall it. 5740 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5741 rii.filter = null; 5742 } 5743 } 5744 5745 // Filter out the caller activity if so requested. 5746 if (caller != null) { 5747 N = results.size(); 5748 for (int i=0; i<N; i++) { 5749 ActivityInfo ainfo = results.get(i).activityInfo; 5750 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5751 && caller.getClassName().equals(ainfo.name)) { 5752 results.remove(i); 5753 break; 5754 } 5755 } 5756 } 5757 5758 // If the caller didn't request filter information, 5759 // drop them now so we don't have to 5760 // marshall/unmarshall it. 5761 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5762 N = results.size(); 5763 for (int i=0; i<N; i++) { 5764 results.get(i).filter = null; 5765 } 5766 } 5767 5768 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5769 return results; 5770 } 5771 5772 @Override 5773 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5774 String resolvedType, int flags, int userId) { 5775 return new ParceledListSlice<>( 5776 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5777 } 5778 5779 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5780 String resolvedType, int flags, int userId) { 5781 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5782 flags = updateFlagsForResolve(flags, userId, intent); 5783 ComponentName comp = intent.getComponent(); 5784 if (comp == null) { 5785 if (intent.getSelector() != null) { 5786 intent = intent.getSelector(); 5787 comp = intent.getComponent(); 5788 } 5789 } 5790 if (comp != null) { 5791 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5792 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5793 if (ai != null) { 5794 ResolveInfo ri = new ResolveInfo(); 5795 ri.activityInfo = ai; 5796 list.add(ri); 5797 } 5798 return list; 5799 } 5800 5801 // reader 5802 synchronized (mPackages) { 5803 String pkgName = intent.getPackage(); 5804 if (pkgName == null) { 5805 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5806 } 5807 final PackageParser.Package pkg = mPackages.get(pkgName); 5808 if (pkg != null) { 5809 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5810 userId); 5811 } 5812 return Collections.emptyList(); 5813 } 5814 } 5815 5816 @Override 5817 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5818 if (!sUserManager.exists(userId)) return null; 5819 flags = updateFlagsForResolve(flags, userId, intent); 5820 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5821 if (query != null) { 5822 if (query.size() >= 1) { 5823 // If there is more than one service with the same priority, 5824 // just arbitrarily pick the first one. 5825 return query.get(0); 5826 } 5827 } 5828 return null; 5829 } 5830 5831 @Override 5832 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5833 String resolvedType, int flags, int userId) { 5834 return new ParceledListSlice<>( 5835 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5836 } 5837 5838 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5839 String resolvedType, int flags, int userId) { 5840 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5841 flags = updateFlagsForResolve(flags, userId, intent); 5842 ComponentName comp = intent.getComponent(); 5843 if (comp == null) { 5844 if (intent.getSelector() != null) { 5845 intent = intent.getSelector(); 5846 comp = intent.getComponent(); 5847 } 5848 } 5849 if (comp != null) { 5850 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5851 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5852 if (si != null) { 5853 final ResolveInfo ri = new ResolveInfo(); 5854 ri.serviceInfo = si; 5855 list.add(ri); 5856 } 5857 return list; 5858 } 5859 5860 // reader 5861 synchronized (mPackages) { 5862 String pkgName = intent.getPackage(); 5863 if (pkgName == null) { 5864 return mServices.queryIntent(intent, resolvedType, flags, userId); 5865 } 5866 final PackageParser.Package pkg = mPackages.get(pkgName); 5867 if (pkg != null) { 5868 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5869 userId); 5870 } 5871 return Collections.emptyList(); 5872 } 5873 } 5874 5875 @Override 5876 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5877 String resolvedType, int flags, int userId) { 5878 return new ParceledListSlice<>( 5879 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5880 } 5881 5882 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5883 Intent intent, String resolvedType, int flags, int userId) { 5884 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5885 flags = updateFlagsForResolve(flags, userId, intent); 5886 ComponentName comp = intent.getComponent(); 5887 if (comp == null) { 5888 if (intent.getSelector() != null) { 5889 intent = intent.getSelector(); 5890 comp = intent.getComponent(); 5891 } 5892 } 5893 if (comp != null) { 5894 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5895 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5896 if (pi != null) { 5897 final ResolveInfo ri = new ResolveInfo(); 5898 ri.providerInfo = pi; 5899 list.add(ri); 5900 } 5901 return list; 5902 } 5903 5904 // reader 5905 synchronized (mPackages) { 5906 String pkgName = intent.getPackage(); 5907 if (pkgName == null) { 5908 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5909 } 5910 final PackageParser.Package pkg = mPackages.get(pkgName); 5911 if (pkg != null) { 5912 return mProviders.queryIntentForPackage( 5913 intent, resolvedType, flags, pkg.providers, userId); 5914 } 5915 return Collections.emptyList(); 5916 } 5917 } 5918 5919 @Override 5920 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5921 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5922 flags = updateFlagsForPackage(flags, userId, null); 5923 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5924 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5925 true /* requireFullPermission */, false /* checkShell */, 5926 "get installed packages"); 5927 5928 // writer 5929 synchronized (mPackages) { 5930 ArrayList<PackageInfo> list; 5931 if (listUninstalled) { 5932 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5933 for (PackageSetting ps : mSettings.mPackages.values()) { 5934 PackageInfo pi; 5935 if (ps.pkg != null) { 5936 pi = generatePackageInfo(ps.pkg, flags, userId); 5937 } else { 5938 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5939 } 5940 if (pi != null) { 5941 list.add(pi); 5942 } 5943 } 5944 } else { 5945 list = new ArrayList<PackageInfo>(mPackages.size()); 5946 for (PackageParser.Package p : mPackages.values()) { 5947 PackageInfo pi = generatePackageInfo(p, flags, userId); 5948 if (pi != null) { 5949 list.add(pi); 5950 } 5951 } 5952 } 5953 5954 return new ParceledListSlice<PackageInfo>(list); 5955 } 5956 } 5957 5958 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5959 String[] permissions, boolean[] tmp, int flags, int userId) { 5960 int numMatch = 0; 5961 final PermissionsState permissionsState = ps.getPermissionsState(); 5962 for (int i=0; i<permissions.length; i++) { 5963 final String permission = permissions[i]; 5964 if (permissionsState.hasPermission(permission, userId)) { 5965 tmp[i] = true; 5966 numMatch++; 5967 } else { 5968 tmp[i] = false; 5969 } 5970 } 5971 if (numMatch == 0) { 5972 return; 5973 } 5974 PackageInfo pi; 5975 if (ps.pkg != null) { 5976 pi = generatePackageInfo(ps.pkg, flags, userId); 5977 } else { 5978 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5979 } 5980 // The above might return null in cases of uninstalled apps or install-state 5981 // skew across users/profiles. 5982 if (pi != null) { 5983 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5984 if (numMatch == permissions.length) { 5985 pi.requestedPermissions = permissions; 5986 } else { 5987 pi.requestedPermissions = new String[numMatch]; 5988 numMatch = 0; 5989 for (int i=0; i<permissions.length; i++) { 5990 if (tmp[i]) { 5991 pi.requestedPermissions[numMatch] = permissions[i]; 5992 numMatch++; 5993 } 5994 } 5995 } 5996 } 5997 list.add(pi); 5998 } 5999 } 6000 6001 @Override 6002 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6003 String[] permissions, int flags, int userId) { 6004 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6005 flags = updateFlagsForPackage(flags, userId, permissions); 6006 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6007 6008 // writer 6009 synchronized (mPackages) { 6010 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6011 boolean[] tmpBools = new boolean[permissions.length]; 6012 if (listUninstalled) { 6013 for (PackageSetting ps : mSettings.mPackages.values()) { 6014 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6015 } 6016 } else { 6017 for (PackageParser.Package pkg : mPackages.values()) { 6018 PackageSetting ps = (PackageSetting)pkg.mExtras; 6019 if (ps != null) { 6020 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6021 userId); 6022 } 6023 } 6024 } 6025 6026 return new ParceledListSlice<PackageInfo>(list); 6027 } 6028 } 6029 6030 @Override 6031 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6032 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6033 flags = updateFlagsForApplication(flags, userId, null); 6034 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6035 6036 // writer 6037 synchronized (mPackages) { 6038 ArrayList<ApplicationInfo> list; 6039 if (listUninstalled) { 6040 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6041 for (PackageSetting ps : mSettings.mPackages.values()) { 6042 ApplicationInfo ai; 6043 if (ps.pkg != null) { 6044 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6045 ps.readUserState(userId), userId); 6046 } else { 6047 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6048 } 6049 if (ai != null) { 6050 list.add(ai); 6051 } 6052 } 6053 } else { 6054 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6055 for (PackageParser.Package p : mPackages.values()) { 6056 if (p.mExtras != null) { 6057 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6058 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6059 if (ai != null) { 6060 list.add(ai); 6061 } 6062 } 6063 } 6064 } 6065 6066 return new ParceledListSlice<ApplicationInfo>(list); 6067 } 6068 } 6069 6070 @Override 6071 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6072 if (DISABLE_EPHEMERAL_APPS) { 6073 return null; 6074 } 6075 6076 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6077 "getEphemeralApplications"); 6078 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6079 true /* requireFullPermission */, false /* checkShell */, 6080 "getEphemeralApplications"); 6081 synchronized (mPackages) { 6082 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6083 .getEphemeralApplicationsLPw(userId); 6084 if (ephemeralApps != null) { 6085 return new ParceledListSlice<>(ephemeralApps); 6086 } 6087 } 6088 return null; 6089 } 6090 6091 @Override 6092 public boolean isEphemeralApplication(String packageName, int userId) { 6093 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6094 true /* requireFullPermission */, false /* checkShell */, 6095 "isEphemeral"); 6096 if (DISABLE_EPHEMERAL_APPS) { 6097 return false; 6098 } 6099 6100 if (!isCallerSameApp(packageName)) { 6101 return false; 6102 } 6103 synchronized (mPackages) { 6104 PackageParser.Package pkg = mPackages.get(packageName); 6105 if (pkg != null) { 6106 return pkg.applicationInfo.isEphemeralApp(); 6107 } 6108 } 6109 return false; 6110 } 6111 6112 @Override 6113 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6114 if (DISABLE_EPHEMERAL_APPS) { 6115 return null; 6116 } 6117 6118 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6119 true /* requireFullPermission */, false /* checkShell */, 6120 "getCookie"); 6121 if (!isCallerSameApp(packageName)) { 6122 return null; 6123 } 6124 synchronized (mPackages) { 6125 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6126 packageName, userId); 6127 } 6128 } 6129 6130 @Override 6131 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6132 if (DISABLE_EPHEMERAL_APPS) { 6133 return true; 6134 } 6135 6136 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6137 true /* requireFullPermission */, true /* checkShell */, 6138 "setCookie"); 6139 if (!isCallerSameApp(packageName)) { 6140 return false; 6141 } 6142 synchronized (mPackages) { 6143 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6144 packageName, cookie, userId); 6145 } 6146 } 6147 6148 @Override 6149 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6150 if (DISABLE_EPHEMERAL_APPS) { 6151 return null; 6152 } 6153 6154 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6155 "getEphemeralApplicationIcon"); 6156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6157 true /* requireFullPermission */, false /* checkShell */, 6158 "getEphemeralApplicationIcon"); 6159 synchronized (mPackages) { 6160 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6161 packageName, userId); 6162 } 6163 } 6164 6165 private boolean isCallerSameApp(String packageName) { 6166 PackageParser.Package pkg = mPackages.get(packageName); 6167 return pkg != null 6168 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6169 } 6170 6171 @Override 6172 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6173 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6174 } 6175 6176 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6177 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6178 6179 // reader 6180 synchronized (mPackages) { 6181 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6182 final int userId = UserHandle.getCallingUserId(); 6183 while (i.hasNext()) { 6184 final PackageParser.Package p = i.next(); 6185 if (p.applicationInfo == null) continue; 6186 6187 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6188 && !p.applicationInfo.isDirectBootAware(); 6189 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6190 && p.applicationInfo.isDirectBootAware(); 6191 6192 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6193 && (!mSafeMode || isSystemApp(p)) 6194 && (matchesUnaware || matchesAware)) { 6195 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6196 if (ps != null) { 6197 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6198 ps.readUserState(userId), userId); 6199 if (ai != null) { 6200 finalList.add(ai); 6201 } 6202 } 6203 } 6204 } 6205 } 6206 6207 return finalList; 6208 } 6209 6210 @Override 6211 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6212 if (!sUserManager.exists(userId)) return null; 6213 flags = updateFlagsForComponent(flags, userId, name); 6214 // reader 6215 synchronized (mPackages) { 6216 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6217 PackageSetting ps = provider != null 6218 ? mSettings.mPackages.get(provider.owner.packageName) 6219 : null; 6220 return ps != null 6221 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6222 ? PackageParser.generateProviderInfo(provider, flags, 6223 ps.readUserState(userId), userId) 6224 : null; 6225 } 6226 } 6227 6228 /** 6229 * @deprecated 6230 */ 6231 @Deprecated 6232 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6233 // reader 6234 synchronized (mPackages) { 6235 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6236 .entrySet().iterator(); 6237 final int userId = UserHandle.getCallingUserId(); 6238 while (i.hasNext()) { 6239 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6240 PackageParser.Provider p = entry.getValue(); 6241 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6242 6243 if (ps != null && p.syncable 6244 && (!mSafeMode || (p.info.applicationInfo.flags 6245 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6246 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6247 ps.readUserState(userId), userId); 6248 if (info != null) { 6249 outNames.add(entry.getKey()); 6250 outInfo.add(info); 6251 } 6252 } 6253 } 6254 } 6255 } 6256 6257 @Override 6258 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6259 int uid, int flags) { 6260 final int userId = processName != null ? UserHandle.getUserId(uid) 6261 : UserHandle.getCallingUserId(); 6262 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6263 flags = updateFlagsForComponent(flags, userId, processName); 6264 6265 ArrayList<ProviderInfo> finalList = null; 6266 // reader 6267 synchronized (mPackages) { 6268 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6269 while (i.hasNext()) { 6270 final PackageParser.Provider p = i.next(); 6271 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6272 if (ps != null && p.info.authority != null 6273 && (processName == null 6274 || (p.info.processName.equals(processName) 6275 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6276 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6277 if (finalList == null) { 6278 finalList = new ArrayList<ProviderInfo>(3); 6279 } 6280 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6281 ps.readUserState(userId), userId); 6282 if (info != null) { 6283 finalList.add(info); 6284 } 6285 } 6286 } 6287 } 6288 6289 if (finalList != null) { 6290 Collections.sort(finalList, mProviderInitOrderSorter); 6291 return new ParceledListSlice<ProviderInfo>(finalList); 6292 } 6293 6294 return ParceledListSlice.emptyList(); 6295 } 6296 6297 @Override 6298 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6299 // reader 6300 synchronized (mPackages) { 6301 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6302 return PackageParser.generateInstrumentationInfo(i, flags); 6303 } 6304 } 6305 6306 @Override 6307 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6308 String targetPackage, int flags) { 6309 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6310 } 6311 6312 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6313 int flags) { 6314 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6315 6316 // reader 6317 synchronized (mPackages) { 6318 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6319 while (i.hasNext()) { 6320 final PackageParser.Instrumentation p = i.next(); 6321 if (targetPackage == null 6322 || targetPackage.equals(p.info.targetPackage)) { 6323 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6324 flags); 6325 if (ii != null) { 6326 finalList.add(ii); 6327 } 6328 } 6329 } 6330 } 6331 6332 return finalList; 6333 } 6334 6335 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6336 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6337 if (overlays == null) { 6338 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6339 return; 6340 } 6341 for (PackageParser.Package opkg : overlays.values()) { 6342 // Not much to do if idmap fails: we already logged the error 6343 // and we certainly don't want to abort installation of pkg simply 6344 // because an overlay didn't fit properly. For these reasons, 6345 // ignore the return value of createIdmapForPackagePairLI. 6346 createIdmapForPackagePairLI(pkg, opkg); 6347 } 6348 } 6349 6350 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6351 PackageParser.Package opkg) { 6352 if (!opkg.mTrustedOverlay) { 6353 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6354 opkg.baseCodePath + ": overlay not trusted"); 6355 return false; 6356 } 6357 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6358 if (overlaySet == null) { 6359 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6360 opkg.baseCodePath + " but target package has no known overlays"); 6361 return false; 6362 } 6363 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6364 // TODO: generate idmap for split APKs 6365 try { 6366 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6367 } catch (InstallerException e) { 6368 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6369 + opkg.baseCodePath); 6370 return false; 6371 } 6372 PackageParser.Package[] overlayArray = 6373 overlaySet.values().toArray(new PackageParser.Package[0]); 6374 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6375 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6376 return p1.mOverlayPriority - p2.mOverlayPriority; 6377 } 6378 }; 6379 Arrays.sort(overlayArray, cmp); 6380 6381 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6382 int i = 0; 6383 for (PackageParser.Package p : overlayArray) { 6384 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6385 } 6386 return true; 6387 } 6388 6389 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6391 try { 6392 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6393 } finally { 6394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6395 } 6396 } 6397 6398 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6399 final File[] files = dir.listFiles(); 6400 if (ArrayUtils.isEmpty(files)) { 6401 Log.d(TAG, "No files in app dir " + dir); 6402 return; 6403 } 6404 6405 if (DEBUG_PACKAGE_SCANNING) { 6406 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6407 + " flags=0x" + Integer.toHexString(parseFlags)); 6408 } 6409 6410 for (File file : files) { 6411 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6412 && !PackageInstallerService.isStageName(file.getName()); 6413 if (!isPackage) { 6414 // Ignore entries which are not packages 6415 continue; 6416 } 6417 try { 6418 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6419 scanFlags, currentTime, null); 6420 } catch (PackageManagerException e) { 6421 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6422 6423 // Delete invalid userdata apps 6424 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6425 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6426 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6427 removeCodePathLI(file); 6428 } 6429 } 6430 } 6431 } 6432 6433 private static File getSettingsProblemFile() { 6434 File dataDir = Environment.getDataDirectory(); 6435 File systemDir = new File(dataDir, "system"); 6436 File fname = new File(systemDir, "uiderrors.txt"); 6437 return fname; 6438 } 6439 6440 static void reportSettingsProblem(int priority, String msg) { 6441 logCriticalInfo(priority, msg); 6442 } 6443 6444 static void logCriticalInfo(int priority, String msg) { 6445 Slog.println(priority, TAG, msg); 6446 EventLogTags.writePmCriticalInfo(msg); 6447 try { 6448 File fname = getSettingsProblemFile(); 6449 FileOutputStream out = new FileOutputStream(fname, true); 6450 PrintWriter pw = new FastPrintWriter(out); 6451 SimpleDateFormat formatter = new SimpleDateFormat(); 6452 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6453 pw.println(dateString + ": " + msg); 6454 pw.close(); 6455 FileUtils.setPermissions( 6456 fname.toString(), 6457 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6458 -1, -1); 6459 } catch (java.io.IOException e) { 6460 } 6461 } 6462 6463 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6464 int parseFlags) throws PackageManagerException { 6465 if (ps != null 6466 && ps.codePath.equals(srcFile) 6467 && ps.timeStamp == srcFile.lastModified() 6468 && !isCompatSignatureUpdateNeeded(pkg) 6469 && !isRecoverSignatureUpdateNeeded(pkg)) { 6470 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6471 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6472 ArraySet<PublicKey> signingKs; 6473 synchronized (mPackages) { 6474 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6475 } 6476 if (ps.signatures.mSignatures != null 6477 && ps.signatures.mSignatures.length != 0 6478 && signingKs != null) { 6479 // Optimization: reuse the existing cached certificates 6480 // if the package appears to be unchanged. 6481 pkg.mSignatures = ps.signatures.mSignatures; 6482 pkg.mSigningKeys = signingKs; 6483 return; 6484 } 6485 6486 Slog.w(TAG, "PackageSetting for " + ps.name 6487 + " is missing signatures. Collecting certs again to recover them."); 6488 } else { 6489 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6490 } 6491 6492 try { 6493 PackageParser.collectCertificates(pkg, parseFlags); 6494 } catch (PackageParserException e) { 6495 throw PackageManagerException.from(e); 6496 } 6497 } 6498 6499 /** 6500 * Traces a package scan. 6501 * @see #scanPackageLI(File, int, int, long, UserHandle) 6502 */ 6503 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6504 long currentTime, UserHandle user) throws PackageManagerException { 6505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6506 try { 6507 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6508 } finally { 6509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6510 } 6511 } 6512 6513 /** 6514 * Scans a package and returns the newly parsed package. 6515 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6516 */ 6517 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6518 long currentTime, UserHandle user) throws PackageManagerException { 6519 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6520 parseFlags |= mDefParseFlags; 6521 PackageParser pp = new PackageParser(); 6522 pp.setSeparateProcesses(mSeparateProcesses); 6523 pp.setOnlyCoreApps(mOnlyCore); 6524 pp.setDisplayMetrics(mMetrics); 6525 6526 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6527 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6528 } 6529 6530 final PackageParser.Package pkg; 6531 try { 6532 pkg = pp.parsePackage(scanFile, parseFlags); 6533 } catch (PackageParserException e) { 6534 throw PackageManagerException.from(e); 6535 } 6536 6537 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6538 } 6539 6540 /** 6541 * Scans a package and returns the newly parsed package. 6542 * @throws PackageManagerException on a parse error. 6543 */ 6544 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6545 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6546 throws PackageManagerException { 6547 // If the package has children and this is the first dive in the function 6548 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6549 // packages (parent and children) would be successfully scanned before the 6550 // actual scan since scanning mutates internal state and we want to atomically 6551 // install the package and its children. 6552 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6553 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6554 scanFlags |= SCAN_CHECK_ONLY; 6555 } 6556 } else { 6557 scanFlags &= ~SCAN_CHECK_ONLY; 6558 } 6559 6560 // Scan the parent 6561 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6562 scanFlags, currentTime, user); 6563 6564 // Scan the children 6565 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6566 for (int i = 0; i < childCount; i++) { 6567 PackageParser.Package childPackage = pkg.childPackages.get(i); 6568 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6569 currentTime, user); 6570 } 6571 6572 6573 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6574 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6575 } 6576 6577 return scannedPkg; 6578 } 6579 6580 /** 6581 * Scans a package and returns the newly parsed package. 6582 * @throws PackageManagerException on a parse error. 6583 */ 6584 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6585 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6586 throws PackageManagerException { 6587 PackageSetting ps = null; 6588 PackageSetting updatedPkg; 6589 // reader 6590 synchronized (mPackages) { 6591 // Look to see if we already know about this package. 6592 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6593 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6594 // This package has been renamed to its original name. Let's 6595 // use that. 6596 ps = mSettings.peekPackageLPr(oldName); 6597 } 6598 // If there was no original package, see one for the real package name. 6599 if (ps == null) { 6600 ps = mSettings.peekPackageLPr(pkg.packageName); 6601 } 6602 // Check to see if this package could be hiding/updating a system 6603 // package. Must look for it either under the original or real 6604 // package name depending on our state. 6605 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6606 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6607 6608 // If this is a package we don't know about on the system partition, we 6609 // may need to remove disabled child packages on the system partition 6610 // or may need to not add child packages if the parent apk is updated 6611 // on the data partition and no longer defines this child package. 6612 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6613 // If this is a parent package for an updated system app and this system 6614 // app got an OTA update which no longer defines some of the child packages 6615 // we have to prune them from the disabled system packages. 6616 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6617 if (disabledPs != null) { 6618 final int scannedChildCount = (pkg.childPackages != null) 6619 ? pkg.childPackages.size() : 0; 6620 final int disabledChildCount = disabledPs.childPackageNames != null 6621 ? disabledPs.childPackageNames.size() : 0; 6622 for (int i = 0; i < disabledChildCount; i++) { 6623 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6624 boolean disabledPackageAvailable = false; 6625 for (int j = 0; j < scannedChildCount; j++) { 6626 PackageParser.Package childPkg = pkg.childPackages.get(j); 6627 if (childPkg.packageName.equals(disabledChildPackageName)) { 6628 disabledPackageAvailable = true; 6629 break; 6630 } 6631 } 6632 if (!disabledPackageAvailable) { 6633 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6634 } 6635 } 6636 } 6637 } 6638 } 6639 6640 boolean updatedPkgBetter = false; 6641 // First check if this is a system package that may involve an update 6642 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6643 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6644 // it needs to drop FLAG_PRIVILEGED. 6645 if (locationIsPrivileged(scanFile)) { 6646 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6647 } else { 6648 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6649 } 6650 6651 if (ps != null && !ps.codePath.equals(scanFile)) { 6652 // The path has changed from what was last scanned... check the 6653 // version of the new path against what we have stored to determine 6654 // what to do. 6655 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6656 if (pkg.mVersionCode <= ps.versionCode) { 6657 // The system package has been updated and the code path does not match 6658 // Ignore entry. Skip it. 6659 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6660 + " ignored: updated version " + ps.versionCode 6661 + " better than this " + pkg.mVersionCode); 6662 if (!updatedPkg.codePath.equals(scanFile)) { 6663 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6664 + ps.name + " changing from " + updatedPkg.codePathString 6665 + " to " + scanFile); 6666 updatedPkg.codePath = scanFile; 6667 updatedPkg.codePathString = scanFile.toString(); 6668 updatedPkg.resourcePath = scanFile; 6669 updatedPkg.resourcePathString = scanFile.toString(); 6670 } 6671 updatedPkg.pkg = pkg; 6672 updatedPkg.versionCode = pkg.mVersionCode; 6673 6674 // Update the disabled system child packages to point to the package too. 6675 final int childCount = updatedPkg.childPackageNames != null 6676 ? updatedPkg.childPackageNames.size() : 0; 6677 for (int i = 0; i < childCount; i++) { 6678 String childPackageName = updatedPkg.childPackageNames.get(i); 6679 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6680 childPackageName); 6681 if (updatedChildPkg != null) { 6682 updatedChildPkg.pkg = pkg; 6683 updatedChildPkg.versionCode = pkg.mVersionCode; 6684 } 6685 } 6686 6687 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6688 + scanFile + " ignored: updated version " + ps.versionCode 6689 + " better than this " + pkg.mVersionCode); 6690 } else { 6691 // The current app on the system partition is better than 6692 // what we have updated to on the data partition; switch 6693 // back to the system partition version. 6694 // At this point, its safely assumed that package installation for 6695 // apps in system partition will go through. If not there won't be a working 6696 // version of the app 6697 // writer 6698 synchronized (mPackages) { 6699 // Just remove the loaded entries from package lists. 6700 mPackages.remove(ps.name); 6701 } 6702 6703 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6704 + " reverting from " + ps.codePathString 6705 + ": new version " + pkg.mVersionCode 6706 + " better than installed " + ps.versionCode); 6707 6708 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6709 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6710 synchronized (mInstallLock) { 6711 args.cleanUpResourcesLI(); 6712 } 6713 synchronized (mPackages) { 6714 mSettings.enableSystemPackageLPw(ps.name); 6715 } 6716 updatedPkgBetter = true; 6717 } 6718 } 6719 } 6720 6721 if (updatedPkg != null) { 6722 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6723 // initially 6724 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6725 6726 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6727 // flag set initially 6728 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6729 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6730 } 6731 } 6732 6733 // Verify certificates against what was last scanned 6734 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6735 6736 /* 6737 * A new system app appeared, but we already had a non-system one of the 6738 * same name installed earlier. 6739 */ 6740 boolean shouldHideSystemApp = false; 6741 if (updatedPkg == null && ps != null 6742 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6743 /* 6744 * Check to make sure the signatures match first. If they don't, 6745 * wipe the installed application and its data. 6746 */ 6747 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6748 != PackageManager.SIGNATURE_MATCH) { 6749 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6750 + " signatures don't match existing userdata copy; removing"); 6751 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6752 ps = null; 6753 } else { 6754 /* 6755 * If the newly-added system app is an older version than the 6756 * already installed version, hide it. It will be scanned later 6757 * and re-added like an update. 6758 */ 6759 if (pkg.mVersionCode <= ps.versionCode) { 6760 shouldHideSystemApp = true; 6761 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6762 + " but new version " + pkg.mVersionCode + " better than installed " 6763 + ps.versionCode + "; hiding system"); 6764 } else { 6765 /* 6766 * The newly found system app is a newer version that the 6767 * one previously installed. Simply remove the 6768 * already-installed application and replace it with our own 6769 * while keeping the application data. 6770 */ 6771 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6772 + " reverting from " + ps.codePathString + ": new version " 6773 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6774 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6775 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6776 synchronized (mInstallLock) { 6777 args.cleanUpResourcesLI(); 6778 } 6779 } 6780 } 6781 } 6782 6783 // The apk is forward locked (not public) if its code and resources 6784 // are kept in different files. (except for app in either system or 6785 // vendor path). 6786 // TODO grab this value from PackageSettings 6787 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6788 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6789 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6790 } 6791 } 6792 6793 // TODO: extend to support forward-locked splits 6794 String resourcePath = null; 6795 String baseResourcePath = null; 6796 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6797 if (ps != null && ps.resourcePathString != null) { 6798 resourcePath = ps.resourcePathString; 6799 baseResourcePath = ps.resourcePathString; 6800 } else { 6801 // Should not happen at all. Just log an error. 6802 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6803 } 6804 } else { 6805 resourcePath = pkg.codePath; 6806 baseResourcePath = pkg.baseCodePath; 6807 } 6808 6809 // Set application objects path explicitly. 6810 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6811 pkg.setApplicationInfoCodePath(pkg.codePath); 6812 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6813 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6814 pkg.setApplicationInfoResourcePath(resourcePath); 6815 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6816 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6817 6818 // Note that we invoke the following method only if we are about to unpack an application 6819 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6820 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6821 6822 /* 6823 * If the system app should be overridden by a previously installed 6824 * data, hide the system app now and let the /data/app scan pick it up 6825 * again. 6826 */ 6827 if (shouldHideSystemApp) { 6828 synchronized (mPackages) { 6829 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6830 } 6831 } 6832 6833 return scannedPkg; 6834 } 6835 6836 private static String fixProcessName(String defProcessName, 6837 String processName, int uid) { 6838 if (processName == null) { 6839 return defProcessName; 6840 } 6841 return processName; 6842 } 6843 6844 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6845 throws PackageManagerException { 6846 if (pkgSetting.signatures.mSignatures != null) { 6847 // Already existing package. Make sure signatures match 6848 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6849 == PackageManager.SIGNATURE_MATCH; 6850 if (!match) { 6851 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6852 == PackageManager.SIGNATURE_MATCH; 6853 } 6854 if (!match) { 6855 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6856 == PackageManager.SIGNATURE_MATCH; 6857 } 6858 if (!match) { 6859 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6860 + pkg.packageName + " signatures do not match the " 6861 + "previously installed version; ignoring!"); 6862 } 6863 } 6864 6865 // Check for shared user signatures 6866 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6867 // Already existing package. Make sure signatures match 6868 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6869 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6870 if (!match) { 6871 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6872 == PackageManager.SIGNATURE_MATCH; 6873 } 6874 if (!match) { 6875 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6876 == PackageManager.SIGNATURE_MATCH; 6877 } 6878 if (!match) { 6879 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6880 "Package " + pkg.packageName 6881 + " has no signatures that match those in shared user " 6882 + pkgSetting.sharedUser.name + "; ignoring!"); 6883 } 6884 } 6885 } 6886 6887 /** 6888 * Enforces that only the system UID or root's UID can call a method exposed 6889 * via Binder. 6890 * 6891 * @param message used as message if SecurityException is thrown 6892 * @throws SecurityException if the caller is not system or root 6893 */ 6894 private static final void enforceSystemOrRoot(String message) { 6895 final int uid = Binder.getCallingUid(); 6896 if (uid != Process.SYSTEM_UID && uid != 0) { 6897 throw new SecurityException(message); 6898 } 6899 } 6900 6901 @Override 6902 public void performFstrimIfNeeded() { 6903 enforceSystemOrRoot("Only the system can request fstrim"); 6904 6905 // Before everything else, see whether we need to fstrim. 6906 try { 6907 IMountService ms = PackageHelper.getMountService(); 6908 if (ms != null) { 6909 final boolean isUpgrade = isUpgrade(); 6910 boolean doTrim = isUpgrade; 6911 if (doTrim) { 6912 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6913 } else { 6914 final long interval = android.provider.Settings.Global.getLong( 6915 mContext.getContentResolver(), 6916 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6917 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6918 if (interval > 0) { 6919 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6920 if (timeSinceLast > interval) { 6921 doTrim = true; 6922 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6923 + "; running immediately"); 6924 } 6925 } 6926 } 6927 if (doTrim) { 6928 if (!isFirstBoot()) { 6929 try { 6930 ActivityManagerNative.getDefault().showBootMessage( 6931 mContext.getResources().getString( 6932 R.string.android_upgrading_fstrim), true); 6933 } catch (RemoteException e) { 6934 } 6935 } 6936 ms.runMaintenance(); 6937 } 6938 } else { 6939 Slog.e(TAG, "Mount service unavailable!"); 6940 } 6941 } catch (RemoteException e) { 6942 // Can't happen; MountService is local 6943 } 6944 } 6945 6946 @Override 6947 public void updatePackagesIfNeeded() { 6948 enforceSystemOrRoot("Only the system can request package update"); 6949 6950 // We need to re-extract after an OTA. 6951 boolean causeUpgrade = isUpgrade(); 6952 6953 // First boot or factory reset. 6954 // Note: we also handle devices that are upgrading to N right now as if it is their 6955 // first boot, as they do not have profile data. 6956 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6957 6958 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6959 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6960 6961 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 6962 return; 6963 } 6964 6965 List<PackageParser.Package> pkgs; 6966 synchronized (mPackages) { 6967 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6968 } 6969 6970 int curr = 0; 6971 int total = pkgs.size(); 6972 for (PackageParser.Package pkg : pkgs) { 6973 curr++; 6974 6975 if (DEBUG_DEXOPT) { 6976 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6977 } 6978 6979 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6980 // If the cache was pruned, any compiled odex files will likely be out of date 6981 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6982 // Instead, force the extraction in this case. 6983 performDexOpt(pkg.packageName, null /* instructionSet */, 6984 false /* checkProfiles */, 6985 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 6986 causePrunedCache); 6987 } 6988 } 6989 } 6990 6991 @Override 6992 public void notifyPackageUse(String packageName) { 6993 synchronized (mPackages) { 6994 PackageParser.Package p = mPackages.get(packageName); 6995 if (p == null) { 6996 return; 6997 } 6998 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6999 } 7000 } 7001 7002 // TODO: this is not used nor needed. Delete it. 7003 @Override 7004 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7005 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7006 getFullCompilerFilter(), false /* force */); 7007 } 7008 7009 @Override 7010 public boolean performDexOpt(String packageName, String instructionSet, 7011 boolean checkProfiles, int compileReason, boolean force) { 7012 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7013 getCompilerFilterForReason(compileReason), force); 7014 } 7015 7016 @Override 7017 public boolean performDexOptMode(String packageName, String instructionSet, 7018 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7019 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7020 targetCompilerFilter, force); 7021 } 7022 7023 private boolean performDexOptTraced(String packageName, String instructionSet, 7024 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7025 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7026 try { 7027 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7028 targetCompilerFilter, force); 7029 } finally { 7030 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7031 } 7032 } 7033 7034 private boolean performDexOptInternal(String packageName, String instructionSet, 7035 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7036 PackageParser.Package p; 7037 final String targetInstructionSet; 7038 synchronized (mPackages) { 7039 p = mPackages.get(packageName); 7040 if (p == null) { 7041 return false; 7042 } 7043 mPackageUsage.write(false); 7044 7045 targetInstructionSet = instructionSet != null ? instructionSet : 7046 getPrimaryInstructionSet(p.applicationInfo); 7047 } 7048 long callingId = Binder.clearCallingIdentity(); 7049 try { 7050 synchronized (mInstallLock) { 7051 final String[] instructionSets = new String[] { targetInstructionSet }; 7052 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7053 checkProfiles, targetCompilerFilter, force); 7054 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7055 } 7056 } finally { 7057 Binder.restoreCallingIdentity(callingId); 7058 } 7059 } 7060 7061 public ArraySet<String> getOptimizablePackages() { 7062 ArraySet<String> pkgs = new ArraySet<String>(); 7063 synchronized (mPackages) { 7064 for (PackageParser.Package p : mPackages.values()) { 7065 if (PackageDexOptimizer.canOptimizePackage(p)) { 7066 pkgs.add(p.packageName); 7067 } 7068 } 7069 } 7070 return pkgs; 7071 } 7072 7073 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7074 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7075 boolean force) { 7076 // Select the dex optimizer based on the force parameter. 7077 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7078 // allocate an object here. 7079 PackageDexOptimizer pdo = force 7080 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7081 : mPackageDexOptimizer; 7082 7083 // Optimize all dependencies first. Note: we ignore the return value and march on 7084 // on errors. 7085 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7086 if (!deps.isEmpty()) { 7087 for (PackageParser.Package depPackage : deps) { 7088 // TODO: Analyze and investigate if we (should) profile libraries. 7089 // Currently this will do a full compilation of the library by default. 7090 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7091 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7092 } 7093 } 7094 7095 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7096 } 7097 7098 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7099 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7100 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7101 Set<String> collectedNames = new HashSet<>(); 7102 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7103 7104 retValue.remove(p); 7105 7106 return retValue; 7107 } else { 7108 return Collections.emptyList(); 7109 } 7110 } 7111 7112 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7113 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7114 if (!collectedNames.contains(p.packageName)) { 7115 collectedNames.add(p.packageName); 7116 collected.add(p); 7117 7118 if (p.usesLibraries != null) { 7119 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7120 } 7121 if (p.usesOptionalLibraries != null) { 7122 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7123 collectedNames); 7124 } 7125 } 7126 } 7127 7128 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7129 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7130 for (String libName : libs) { 7131 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7132 if (libPkg != null) { 7133 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7134 } 7135 } 7136 } 7137 7138 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7139 synchronized (mPackages) { 7140 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7141 if (lib != null && lib.apk != null) { 7142 return mPackages.get(lib.apk); 7143 } 7144 } 7145 return null; 7146 } 7147 7148 public void shutdown() { 7149 mPackageUsage.write(true); 7150 } 7151 7152 @Override 7153 public void forceDexOpt(String packageName) { 7154 enforceSystemOrRoot("forceDexOpt"); 7155 7156 PackageParser.Package pkg; 7157 synchronized (mPackages) { 7158 pkg = mPackages.get(packageName); 7159 if (pkg == null) { 7160 throw new IllegalArgumentException("Unknown package: " + packageName); 7161 } 7162 } 7163 7164 synchronized (mInstallLock) { 7165 final String[] instructionSets = new String[] { 7166 getPrimaryInstructionSet(pkg.applicationInfo) }; 7167 7168 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7169 7170 // Whoever is calling forceDexOpt wants a fully compiled package. 7171 // Don't use profiles since that may cause compilation to be skipped. 7172 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7173 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7174 true /* force */); 7175 7176 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7177 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7178 throw new IllegalStateException("Failed to dexopt: " + res); 7179 } 7180 } 7181 } 7182 7183 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7184 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7185 Slog.w(TAG, "Unable to update from " + oldPkg.name 7186 + " to " + newPkg.packageName 7187 + ": old package not in system partition"); 7188 return false; 7189 } else if (mPackages.get(oldPkg.name) != null) { 7190 Slog.w(TAG, "Unable to update from " + oldPkg.name 7191 + " to " + newPkg.packageName 7192 + ": old package still exists"); 7193 return false; 7194 } 7195 return true; 7196 } 7197 7198 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7199 // TODO: triage flags as part of 26466827 7200 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7201 7202 boolean res = true; 7203 final int[] users = sUserManager.getUserIds(); 7204 for (int user : users) { 7205 try { 7206 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7207 } catch (InstallerException e) { 7208 Slog.w(TAG, "Failed to delete data directory", e); 7209 res = false; 7210 } 7211 } 7212 return res; 7213 } 7214 7215 void removeCodePathLI(File codePath) { 7216 if (codePath.isDirectory()) { 7217 try { 7218 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7219 } catch (InstallerException e) { 7220 Slog.w(TAG, "Failed to remove code path", e); 7221 } 7222 } else { 7223 codePath.delete(); 7224 } 7225 } 7226 7227 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7228 try { 7229 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7230 } catch (InstallerException e) { 7231 Slog.w(TAG, "Failed to destroy app data", e); 7232 } 7233 } 7234 7235 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7236 int appId, String seinfo) { 7237 try { 7238 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7239 } catch (InstallerException e) { 7240 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7241 } 7242 } 7243 7244 private void deleteProfilesLI(String packageName, boolean destroy) { 7245 final PackageParser.Package pkg; 7246 synchronized (mPackages) { 7247 pkg = mPackages.get(packageName); 7248 } 7249 if (pkg == null) { 7250 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7251 return; 7252 } 7253 deleteProfilesLI(pkg, destroy); 7254 } 7255 7256 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7257 try { 7258 if (destroy) { 7259 mInstaller.destroyAppProfiles(pkg.packageName); 7260 } else { 7261 mInstaller.clearAppProfiles(pkg.packageName); 7262 } 7263 } catch (InstallerException ex) { 7264 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7265 } 7266 } 7267 7268 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7269 final PackageParser.Package pkg; 7270 synchronized (mPackages) { 7271 pkg = mPackages.get(packageName); 7272 } 7273 if (pkg == null) { 7274 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7275 return; 7276 } 7277 deleteCodeCacheDirsLI(pkg); 7278 } 7279 7280 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7281 // TODO: triage flags as part of 26466827 7282 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7283 7284 int[] users = sUserManager.getUserIds(); 7285 int res = 0; 7286 for (int user : users) { 7287 // Remove the parent code cache 7288 try { 7289 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7290 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7291 } catch (InstallerException e) { 7292 Slog.w(TAG, "Failed to delete code cache directory", e); 7293 } 7294 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7295 for (int i = 0; i < childCount; i++) { 7296 PackageParser.Package childPkg = pkg.childPackages.get(i); 7297 // Remove the child code cache 7298 try { 7299 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7300 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7301 } catch (InstallerException e) { 7302 Slog.w(TAG, "Failed to delete code cache directory", e); 7303 } 7304 } 7305 } 7306 } 7307 7308 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7309 long lastUpdateTime) { 7310 // Set parent install/update time 7311 PackageSetting ps = (PackageSetting) pkg.mExtras; 7312 if (ps != null) { 7313 ps.firstInstallTime = firstInstallTime; 7314 ps.lastUpdateTime = lastUpdateTime; 7315 } 7316 // Set children install/update time 7317 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7318 for (int i = 0; i < childCount; i++) { 7319 PackageParser.Package childPkg = pkg.childPackages.get(i); 7320 ps = (PackageSetting) childPkg.mExtras; 7321 if (ps != null) { 7322 ps.firstInstallTime = firstInstallTime; 7323 ps.lastUpdateTime = lastUpdateTime; 7324 } 7325 } 7326 } 7327 7328 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7329 PackageParser.Package changingLib) { 7330 if (file.path != null) { 7331 usesLibraryFiles.add(file.path); 7332 return; 7333 } 7334 PackageParser.Package p = mPackages.get(file.apk); 7335 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7336 // If we are doing this while in the middle of updating a library apk, 7337 // then we need to make sure to use that new apk for determining the 7338 // dependencies here. (We haven't yet finished committing the new apk 7339 // to the package manager state.) 7340 if (p == null || p.packageName.equals(changingLib.packageName)) { 7341 p = changingLib; 7342 } 7343 } 7344 if (p != null) { 7345 usesLibraryFiles.addAll(p.getAllCodePaths()); 7346 } 7347 } 7348 7349 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7350 PackageParser.Package changingLib) throws PackageManagerException { 7351 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7352 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7353 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7354 for (int i=0; i<N; i++) { 7355 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7356 if (file == null) { 7357 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7358 "Package " + pkg.packageName + " requires unavailable shared library " 7359 + pkg.usesLibraries.get(i) + "; failing!"); 7360 } 7361 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7362 } 7363 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7364 for (int i=0; i<N; i++) { 7365 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7366 if (file == null) { 7367 Slog.w(TAG, "Package " + pkg.packageName 7368 + " desires unavailable shared library " 7369 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7370 } else { 7371 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7372 } 7373 } 7374 N = usesLibraryFiles.size(); 7375 if (N > 0) { 7376 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7377 } else { 7378 pkg.usesLibraryFiles = null; 7379 } 7380 } 7381 } 7382 7383 private static boolean hasString(List<String> list, List<String> which) { 7384 if (list == null) { 7385 return false; 7386 } 7387 for (int i=list.size()-1; i>=0; i--) { 7388 for (int j=which.size()-1; j>=0; j--) { 7389 if (which.get(j).equals(list.get(i))) { 7390 return true; 7391 } 7392 } 7393 } 7394 return false; 7395 } 7396 7397 private void updateAllSharedLibrariesLPw() { 7398 for (PackageParser.Package pkg : mPackages.values()) { 7399 try { 7400 updateSharedLibrariesLPw(pkg, null); 7401 } catch (PackageManagerException e) { 7402 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7403 } 7404 } 7405 } 7406 7407 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7408 PackageParser.Package changingPkg) { 7409 ArrayList<PackageParser.Package> res = null; 7410 for (PackageParser.Package pkg : mPackages.values()) { 7411 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7412 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7413 if (res == null) { 7414 res = new ArrayList<PackageParser.Package>(); 7415 } 7416 res.add(pkg); 7417 try { 7418 updateSharedLibrariesLPw(pkg, changingPkg); 7419 } catch (PackageManagerException e) { 7420 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7421 } 7422 } 7423 } 7424 return res; 7425 } 7426 7427 /** 7428 * Derive the value of the {@code cpuAbiOverride} based on the provided 7429 * value and an optional stored value from the package settings. 7430 */ 7431 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7432 String cpuAbiOverride = null; 7433 7434 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7435 cpuAbiOverride = null; 7436 } else if (abiOverride != null) { 7437 cpuAbiOverride = abiOverride; 7438 } else if (settings != null) { 7439 cpuAbiOverride = settings.cpuAbiOverrideString; 7440 } 7441 7442 return cpuAbiOverride; 7443 } 7444 7445 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7446 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7448 // If the package has children and this is the first dive in the function 7449 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7450 // whether all packages (parent and children) would be successfully scanned 7451 // before the actual scan since scanning mutates internal state and we want 7452 // to atomically install the package and its children. 7453 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7454 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7455 scanFlags |= SCAN_CHECK_ONLY; 7456 } 7457 } else { 7458 scanFlags &= ~SCAN_CHECK_ONLY; 7459 } 7460 7461 final PackageParser.Package scannedPkg; 7462 try { 7463 // Scan the parent 7464 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7465 // Scan the children 7466 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7467 for (int i = 0; i < childCount; i++) { 7468 PackageParser.Package childPkg = pkg.childPackages.get(i); 7469 scanPackageLI(childPkg, parseFlags, 7470 scanFlags, currentTime, user); 7471 } 7472 } finally { 7473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7474 } 7475 7476 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7477 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7478 } 7479 7480 return scannedPkg; 7481 } 7482 7483 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7484 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7485 boolean success = false; 7486 try { 7487 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7488 currentTime, user); 7489 success = true; 7490 return res; 7491 } finally { 7492 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7493 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7494 } 7495 } 7496 } 7497 7498 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7499 int scanFlags, long currentTime, UserHandle user) 7500 throws PackageManagerException { 7501 final File scanFile = new File(pkg.codePath); 7502 if (pkg.applicationInfo.getCodePath() == null || 7503 pkg.applicationInfo.getResourcePath() == null) { 7504 // Bail out. The resource and code paths haven't been set. 7505 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7506 "Code and resource paths haven't been set correctly"); 7507 } 7508 7509 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7510 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7511 } else { 7512 // Only allow system apps to be flagged as core apps. 7513 pkg.coreApp = false; 7514 } 7515 7516 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7517 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7518 } 7519 7520 if (mCustomResolverComponentName != null && 7521 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7522 setUpCustomResolverActivity(pkg); 7523 } 7524 7525 if (pkg.packageName.equals("android")) { 7526 synchronized (mPackages) { 7527 if (mAndroidApplication != null) { 7528 Slog.w(TAG, "*************************************************"); 7529 Slog.w(TAG, "Core android package being redefined. Skipping."); 7530 Slog.w(TAG, " file=" + scanFile); 7531 Slog.w(TAG, "*************************************************"); 7532 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7533 "Core android package being redefined. Skipping."); 7534 } 7535 7536 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7537 // Set up information for our fall-back user intent resolution activity. 7538 mPlatformPackage = pkg; 7539 pkg.mVersionCode = mSdkVersion; 7540 mAndroidApplication = pkg.applicationInfo; 7541 7542 if (!mResolverReplaced) { 7543 mResolveActivity.applicationInfo = mAndroidApplication; 7544 mResolveActivity.name = ResolverActivity.class.getName(); 7545 mResolveActivity.packageName = mAndroidApplication.packageName; 7546 mResolveActivity.processName = "system:ui"; 7547 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7548 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7549 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7550 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7551 mResolveActivity.exported = true; 7552 mResolveActivity.enabled = true; 7553 mResolveInfo.activityInfo = mResolveActivity; 7554 mResolveInfo.priority = 0; 7555 mResolveInfo.preferredOrder = 0; 7556 mResolveInfo.match = 0; 7557 mResolveComponentName = new ComponentName( 7558 mAndroidApplication.packageName, mResolveActivity.name); 7559 } 7560 } 7561 } 7562 } 7563 7564 if (DEBUG_PACKAGE_SCANNING) { 7565 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7566 Log.d(TAG, "Scanning package " + pkg.packageName); 7567 } 7568 7569 synchronized (mPackages) { 7570 if (mPackages.containsKey(pkg.packageName) 7571 || mSharedLibraries.containsKey(pkg.packageName)) { 7572 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7573 "Application package " + pkg.packageName 7574 + " already installed. Skipping duplicate."); 7575 } 7576 7577 // If we're only installing presumed-existing packages, require that the 7578 // scanned APK is both already known and at the path previously established 7579 // for it. Previously unknown packages we pick up normally, but if we have an 7580 // a priori expectation about this package's install presence, enforce it. 7581 // With a singular exception for new system packages. When an OTA contains 7582 // a new system package, we allow the codepath to change from a system location 7583 // to the user-installed location. If we don't allow this change, any newer, 7584 // user-installed version of the application will be ignored. 7585 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7586 if (mExpectingBetter.containsKey(pkg.packageName)) { 7587 logCriticalInfo(Log.WARN, 7588 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7589 } else { 7590 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7591 if (known != null) { 7592 if (DEBUG_PACKAGE_SCANNING) { 7593 Log.d(TAG, "Examining " + pkg.codePath 7594 + " and requiring known paths " + known.codePathString 7595 + " & " + known.resourcePathString); 7596 } 7597 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7598 || !pkg.applicationInfo.getResourcePath().equals( 7599 known.resourcePathString)) { 7600 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7601 "Application package " + pkg.packageName 7602 + " found at " + pkg.applicationInfo.getCodePath() 7603 + " but expected at " + known.codePathString 7604 + "; ignoring."); 7605 } 7606 } 7607 } 7608 } 7609 } 7610 7611 // Initialize package source and resource directories 7612 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7613 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7614 7615 SharedUserSetting suid = null; 7616 PackageSetting pkgSetting = null; 7617 7618 if (!isSystemApp(pkg)) { 7619 // Only system apps can use these features. 7620 pkg.mOriginalPackages = null; 7621 pkg.mRealPackage = null; 7622 pkg.mAdoptPermissions = null; 7623 } 7624 7625 // Getting the package setting may have a side-effect, so if we 7626 // are only checking if scan would succeed, stash a copy of the 7627 // old setting to restore at the end. 7628 PackageSetting nonMutatedPs = null; 7629 7630 // writer 7631 synchronized (mPackages) { 7632 if (pkg.mSharedUserId != null) { 7633 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7634 if (suid == null) { 7635 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7636 "Creating application package " + pkg.packageName 7637 + " for shared user failed"); 7638 } 7639 if (DEBUG_PACKAGE_SCANNING) { 7640 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7641 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7642 + "): packages=" + suid.packages); 7643 } 7644 } 7645 7646 // Check if we are renaming from an original package name. 7647 PackageSetting origPackage = null; 7648 String realName = null; 7649 if (pkg.mOriginalPackages != null) { 7650 // This package may need to be renamed to a previously 7651 // installed name. Let's check on that... 7652 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7653 if (pkg.mOriginalPackages.contains(renamed)) { 7654 // This package had originally been installed as the 7655 // original name, and we have already taken care of 7656 // transitioning to the new one. Just update the new 7657 // one to continue using the old name. 7658 realName = pkg.mRealPackage; 7659 if (!pkg.packageName.equals(renamed)) { 7660 // Callers into this function may have already taken 7661 // care of renaming the package; only do it here if 7662 // it is not already done. 7663 pkg.setPackageName(renamed); 7664 } 7665 7666 } else { 7667 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7668 if ((origPackage = mSettings.peekPackageLPr( 7669 pkg.mOriginalPackages.get(i))) != null) { 7670 // We do have the package already installed under its 7671 // original name... should we use it? 7672 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7673 // New package is not compatible with original. 7674 origPackage = null; 7675 continue; 7676 } else if (origPackage.sharedUser != null) { 7677 // Make sure uid is compatible between packages. 7678 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7679 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7680 + " to " + pkg.packageName + ": old uid " 7681 + origPackage.sharedUser.name 7682 + " differs from " + pkg.mSharedUserId); 7683 origPackage = null; 7684 continue; 7685 } 7686 } else { 7687 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7688 + pkg.packageName + " to old name " + origPackage.name); 7689 } 7690 break; 7691 } 7692 } 7693 } 7694 } 7695 7696 if (mTransferedPackages.contains(pkg.packageName)) { 7697 Slog.w(TAG, "Package " + pkg.packageName 7698 + " was transferred to another, but its .apk remains"); 7699 } 7700 7701 // See comments in nonMutatedPs declaration 7702 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7703 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7704 if (foundPs != null) { 7705 nonMutatedPs = new PackageSetting(foundPs); 7706 } 7707 } 7708 7709 // Just create the setting, don't add it yet. For already existing packages 7710 // the PkgSetting exists already and doesn't have to be created. 7711 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7712 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7713 pkg.applicationInfo.primaryCpuAbi, 7714 pkg.applicationInfo.secondaryCpuAbi, 7715 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7716 user, false); 7717 if (pkgSetting == null) { 7718 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7719 "Creating application package " + pkg.packageName + " failed"); 7720 } 7721 7722 if (pkgSetting.origPackage != null) { 7723 // If we are first transitioning from an original package, 7724 // fix up the new package's name now. We need to do this after 7725 // looking up the package under its new name, so getPackageLP 7726 // can take care of fiddling things correctly. 7727 pkg.setPackageName(origPackage.name); 7728 7729 // File a report about this. 7730 String msg = "New package " + pkgSetting.realName 7731 + " renamed to replace old package " + pkgSetting.name; 7732 reportSettingsProblem(Log.WARN, msg); 7733 7734 // Make a note of it. 7735 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7736 mTransferedPackages.add(origPackage.name); 7737 } 7738 7739 // No longer need to retain this. 7740 pkgSetting.origPackage = null; 7741 } 7742 7743 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7744 // Make a note of it. 7745 mTransferedPackages.add(pkg.packageName); 7746 } 7747 7748 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7749 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7750 } 7751 7752 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7753 // Check all shared libraries and map to their actual file path. 7754 // We only do this here for apps not on a system dir, because those 7755 // are the only ones that can fail an install due to this. We 7756 // will take care of the system apps by updating all of their 7757 // library paths after the scan is done. 7758 updateSharedLibrariesLPw(pkg, null); 7759 } 7760 7761 if (mFoundPolicyFile) { 7762 SELinuxMMAC.assignSeinfoValue(pkg); 7763 } 7764 7765 pkg.applicationInfo.uid = pkgSetting.appId; 7766 pkg.mExtras = pkgSetting; 7767 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7768 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7769 // We just determined the app is signed correctly, so bring 7770 // over the latest parsed certs. 7771 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7772 } else { 7773 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7774 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7775 "Package " + pkg.packageName + " upgrade keys do not match the " 7776 + "previously installed version"); 7777 } else { 7778 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7779 String msg = "System package " + pkg.packageName 7780 + " signature changed; retaining data."; 7781 reportSettingsProblem(Log.WARN, msg); 7782 } 7783 } 7784 } else { 7785 try { 7786 verifySignaturesLP(pkgSetting, pkg); 7787 // We just determined the app is signed correctly, so bring 7788 // over the latest parsed certs. 7789 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7790 } catch (PackageManagerException e) { 7791 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7792 throw e; 7793 } 7794 // The signature has changed, but this package is in the system 7795 // image... let's recover! 7796 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7797 // However... if this package is part of a shared user, but it 7798 // doesn't match the signature of the shared user, let's fail. 7799 // What this means is that you can't change the signatures 7800 // associated with an overall shared user, which doesn't seem all 7801 // that unreasonable. 7802 if (pkgSetting.sharedUser != null) { 7803 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7804 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7805 throw new PackageManagerException( 7806 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7807 "Signature mismatch for shared user: " 7808 + pkgSetting.sharedUser); 7809 } 7810 } 7811 // File a report about this. 7812 String msg = "System package " + pkg.packageName 7813 + " signature changed; retaining data."; 7814 reportSettingsProblem(Log.WARN, msg); 7815 } 7816 } 7817 // Verify that this new package doesn't have any content providers 7818 // that conflict with existing packages. Only do this if the 7819 // package isn't already installed, since we don't want to break 7820 // things that are installed. 7821 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7822 final int N = pkg.providers.size(); 7823 int i; 7824 for (i=0; i<N; i++) { 7825 PackageParser.Provider p = pkg.providers.get(i); 7826 if (p.info.authority != null) { 7827 String names[] = p.info.authority.split(";"); 7828 for (int j = 0; j < names.length; j++) { 7829 if (mProvidersByAuthority.containsKey(names[j])) { 7830 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7831 final String otherPackageName = 7832 ((other != null && other.getComponentName() != null) ? 7833 other.getComponentName().getPackageName() : "?"); 7834 throw new PackageManagerException( 7835 INSTALL_FAILED_CONFLICTING_PROVIDER, 7836 "Can't install because provider name " + names[j] 7837 + " (in package " + pkg.applicationInfo.packageName 7838 + ") is already used by " + otherPackageName); 7839 } 7840 } 7841 } 7842 } 7843 } 7844 7845 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7846 // This package wants to adopt ownership of permissions from 7847 // another package. 7848 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7849 final String origName = pkg.mAdoptPermissions.get(i); 7850 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7851 if (orig != null) { 7852 if (verifyPackageUpdateLPr(orig, pkg)) { 7853 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7854 + pkg.packageName); 7855 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7856 } 7857 } 7858 } 7859 } 7860 } 7861 7862 final String pkgName = pkg.packageName; 7863 7864 final long scanFileTime = scanFile.lastModified(); 7865 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7866 pkg.applicationInfo.processName = fixProcessName( 7867 pkg.applicationInfo.packageName, 7868 pkg.applicationInfo.processName, 7869 pkg.applicationInfo.uid); 7870 7871 if (pkg != mPlatformPackage) { 7872 // Get all of our default paths setup 7873 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7874 } 7875 7876 final String path = scanFile.getPath(); 7877 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7878 7879 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7880 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7881 7882 // Some system apps still use directory structure for native libraries 7883 // in which case we might end up not detecting abi solely based on apk 7884 // structure. Try to detect abi based on directory structure. 7885 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7886 pkg.applicationInfo.primaryCpuAbi == null) { 7887 setBundledAppAbisAndRoots(pkg, pkgSetting); 7888 setNativeLibraryPaths(pkg); 7889 } 7890 7891 } else { 7892 if ((scanFlags & SCAN_MOVE) != 0) { 7893 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7894 // but we already have this packages package info in the PackageSetting. We just 7895 // use that and derive the native library path based on the new codepath. 7896 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7897 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7898 } 7899 7900 // Set native library paths again. For moves, the path will be updated based on the 7901 // ABIs we've determined above. For non-moves, the path will be updated based on the 7902 // ABIs we determined during compilation, but the path will depend on the final 7903 // package path (after the rename away from the stage path). 7904 setNativeLibraryPaths(pkg); 7905 } 7906 7907 // This is a special case for the "system" package, where the ABI is 7908 // dictated by the zygote configuration (and init.rc). We should keep track 7909 // of this ABI so that we can deal with "normal" applications that run under 7910 // the same UID correctly. 7911 if (mPlatformPackage == pkg) { 7912 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7913 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7914 } 7915 7916 // If there's a mismatch between the abi-override in the package setting 7917 // and the abiOverride specified for the install. Warn about this because we 7918 // would've already compiled the app without taking the package setting into 7919 // account. 7920 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7921 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7922 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7923 " for package " + pkg.packageName); 7924 } 7925 } 7926 7927 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7928 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7929 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7930 7931 // Copy the derived override back to the parsed package, so that we can 7932 // update the package settings accordingly. 7933 pkg.cpuAbiOverride = cpuAbiOverride; 7934 7935 if (DEBUG_ABI_SELECTION) { 7936 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7937 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7938 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7939 } 7940 7941 // Push the derived path down into PackageSettings so we know what to 7942 // clean up at uninstall time. 7943 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7944 7945 if (DEBUG_ABI_SELECTION) { 7946 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7947 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7948 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7949 } 7950 7951 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7952 // We don't do this here during boot because we can do it all 7953 // at once after scanning all existing packages. 7954 // 7955 // We also do this *before* we perform dexopt on this package, so that 7956 // we can avoid redundant dexopts, and also to make sure we've got the 7957 // code and package path correct. 7958 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7959 pkg, true /* boot complete */); 7960 } 7961 7962 if (mFactoryTest && pkg.requestedPermissions.contains( 7963 android.Manifest.permission.FACTORY_TEST)) { 7964 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7965 } 7966 7967 ArrayList<PackageParser.Package> clientLibPkgs = null; 7968 7969 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7970 if (nonMutatedPs != null) { 7971 synchronized (mPackages) { 7972 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7973 } 7974 } 7975 return pkg; 7976 } 7977 7978 // Only privileged apps and updated privileged apps can add child packages. 7979 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7980 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7981 throw new PackageManagerException("Only privileged apps and updated " 7982 + "privileged apps can add child packages. Ignoring package " 7983 + pkg.packageName); 7984 } 7985 final int childCount = pkg.childPackages.size(); 7986 for (int i = 0; i < childCount; i++) { 7987 PackageParser.Package childPkg = pkg.childPackages.get(i); 7988 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7989 childPkg.packageName)) { 7990 throw new PackageManagerException("Cannot override a child package of " 7991 + "another disabled system app. Ignoring package " + pkg.packageName); 7992 } 7993 } 7994 } 7995 7996 // writer 7997 synchronized (mPackages) { 7998 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7999 // Only system apps can add new shared libraries. 8000 if (pkg.libraryNames != null) { 8001 for (int i=0; i<pkg.libraryNames.size(); i++) { 8002 String name = pkg.libraryNames.get(i); 8003 boolean allowed = false; 8004 if (pkg.isUpdatedSystemApp()) { 8005 // New library entries can only be added through the 8006 // system image. This is important to get rid of a lot 8007 // of nasty edge cases: for example if we allowed a non- 8008 // system update of the app to add a library, then uninstalling 8009 // the update would make the library go away, and assumptions 8010 // we made such as through app install filtering would now 8011 // have allowed apps on the device which aren't compatible 8012 // with it. Better to just have the restriction here, be 8013 // conservative, and create many fewer cases that can negatively 8014 // impact the user experience. 8015 final PackageSetting sysPs = mSettings 8016 .getDisabledSystemPkgLPr(pkg.packageName); 8017 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8018 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8019 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8020 allowed = true; 8021 break; 8022 } 8023 } 8024 } 8025 } else { 8026 allowed = true; 8027 } 8028 if (allowed) { 8029 if (!mSharedLibraries.containsKey(name)) { 8030 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8031 } else if (!name.equals(pkg.packageName)) { 8032 Slog.w(TAG, "Package " + pkg.packageName + " library " 8033 + name + " already exists; skipping"); 8034 } 8035 } else { 8036 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8037 + name + " that is not declared on system image; skipping"); 8038 } 8039 } 8040 if ((scanFlags & SCAN_BOOTING) == 0) { 8041 // If we are not booting, we need to update any applications 8042 // that are clients of our shared library. If we are booting, 8043 // this will all be done once the scan is complete. 8044 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8045 } 8046 } 8047 } 8048 } 8049 8050 // Request the ActivityManager to kill the process(only for existing packages) 8051 // so that we do not end up in a confused state while the user is still using the older 8052 // version of the application while the new one gets installed. 8053 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8054 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8055 if (killApp) { 8056 if (isReplacing) { 8057 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8058 8059 killApplication(pkg.applicationInfo.packageName, 8060 pkg.applicationInfo.uid, "replace pkg"); 8061 8062 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8063 } 8064 } 8065 8066 // Also need to kill any apps that are dependent on the library. 8067 if (clientLibPkgs != null) { 8068 for (int i=0; i<clientLibPkgs.size(); i++) { 8069 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8070 killApplication(clientPkg.applicationInfo.packageName, 8071 clientPkg.applicationInfo.uid, "update lib"); 8072 } 8073 } 8074 8075 // Make sure we're not adding any bogus keyset info 8076 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8077 ksms.assertScannedPackageValid(pkg); 8078 8079 // writer 8080 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8081 8082 boolean createIdmapFailed = false; 8083 synchronized (mPackages) { 8084 // We don't expect installation to fail beyond this point 8085 8086 // Add the new setting to mSettings 8087 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8088 // Add the new setting to mPackages 8089 mPackages.put(pkg.applicationInfo.packageName, pkg); 8090 // Make sure we don't accidentally delete its data. 8091 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8092 while (iter.hasNext()) { 8093 PackageCleanItem item = iter.next(); 8094 if (pkgName.equals(item.packageName)) { 8095 iter.remove(); 8096 } 8097 } 8098 8099 // Take care of first install / last update times. 8100 if (currentTime != 0) { 8101 if (pkgSetting.firstInstallTime == 0) { 8102 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8103 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8104 pkgSetting.lastUpdateTime = currentTime; 8105 } 8106 } else if (pkgSetting.firstInstallTime == 0) { 8107 // We need *something*. Take time time stamp of the file. 8108 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8109 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8110 if (scanFileTime != pkgSetting.timeStamp) { 8111 // A package on the system image has changed; consider this 8112 // to be an update. 8113 pkgSetting.lastUpdateTime = scanFileTime; 8114 } 8115 } 8116 8117 // Add the package's KeySets to the global KeySetManagerService 8118 ksms.addScannedPackageLPw(pkg); 8119 8120 int N = pkg.providers.size(); 8121 StringBuilder r = null; 8122 int i; 8123 for (i=0; i<N; i++) { 8124 PackageParser.Provider p = pkg.providers.get(i); 8125 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8126 p.info.processName, pkg.applicationInfo.uid); 8127 mProviders.addProvider(p); 8128 p.syncable = p.info.isSyncable; 8129 if (p.info.authority != null) { 8130 String names[] = p.info.authority.split(";"); 8131 p.info.authority = null; 8132 for (int j = 0; j < names.length; j++) { 8133 if (j == 1 && p.syncable) { 8134 // We only want the first authority for a provider to possibly be 8135 // syncable, so if we already added this provider using a different 8136 // authority clear the syncable flag. We copy the provider before 8137 // changing it because the mProviders object contains a reference 8138 // to a provider that we don't want to change. 8139 // Only do this for the second authority since the resulting provider 8140 // object can be the same for all future authorities for this provider. 8141 p = new PackageParser.Provider(p); 8142 p.syncable = false; 8143 } 8144 if (!mProvidersByAuthority.containsKey(names[j])) { 8145 mProvidersByAuthority.put(names[j], p); 8146 if (p.info.authority == null) { 8147 p.info.authority = names[j]; 8148 } else { 8149 p.info.authority = p.info.authority + ";" + names[j]; 8150 } 8151 if (DEBUG_PACKAGE_SCANNING) { 8152 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8153 Log.d(TAG, "Registered content provider: " + names[j] 8154 + ", className = " + p.info.name + ", isSyncable = " 8155 + p.info.isSyncable); 8156 } 8157 } else { 8158 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8159 Slog.w(TAG, "Skipping provider name " + names[j] + 8160 " (in package " + pkg.applicationInfo.packageName + 8161 "): name already used by " 8162 + ((other != null && other.getComponentName() != null) 8163 ? other.getComponentName().getPackageName() : "?")); 8164 } 8165 } 8166 } 8167 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8168 if (r == null) { 8169 r = new StringBuilder(256); 8170 } else { 8171 r.append(' '); 8172 } 8173 r.append(p.info.name); 8174 } 8175 } 8176 if (r != null) { 8177 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8178 } 8179 8180 N = pkg.services.size(); 8181 r = null; 8182 for (i=0; i<N; i++) { 8183 PackageParser.Service s = pkg.services.get(i); 8184 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8185 s.info.processName, pkg.applicationInfo.uid); 8186 mServices.addService(s); 8187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8188 if (r == null) { 8189 r = new StringBuilder(256); 8190 } else { 8191 r.append(' '); 8192 } 8193 r.append(s.info.name); 8194 } 8195 } 8196 if (r != null) { 8197 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8198 } 8199 8200 N = pkg.receivers.size(); 8201 r = null; 8202 for (i=0; i<N; i++) { 8203 PackageParser.Activity a = pkg.receivers.get(i); 8204 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8205 a.info.processName, pkg.applicationInfo.uid); 8206 mReceivers.addActivity(a, "receiver"); 8207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8208 if (r == null) { 8209 r = new StringBuilder(256); 8210 } else { 8211 r.append(' '); 8212 } 8213 r.append(a.info.name); 8214 } 8215 } 8216 if (r != null) { 8217 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8218 } 8219 8220 N = pkg.activities.size(); 8221 r = null; 8222 for (i=0; i<N; i++) { 8223 PackageParser.Activity a = pkg.activities.get(i); 8224 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8225 a.info.processName, pkg.applicationInfo.uid); 8226 mActivities.addActivity(a, "activity"); 8227 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8228 if (r == null) { 8229 r = new StringBuilder(256); 8230 } else { 8231 r.append(' '); 8232 } 8233 r.append(a.info.name); 8234 } 8235 } 8236 if (r != null) { 8237 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8238 } 8239 8240 N = pkg.permissionGroups.size(); 8241 r = null; 8242 for (i=0; i<N; i++) { 8243 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8244 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8245 if (cur == null) { 8246 mPermissionGroups.put(pg.info.name, pg); 8247 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8248 if (r == null) { 8249 r = new StringBuilder(256); 8250 } else { 8251 r.append(' '); 8252 } 8253 r.append(pg.info.name); 8254 } 8255 } else { 8256 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8257 + pg.info.packageName + " ignored: original from " 8258 + cur.info.packageName); 8259 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8260 if (r == null) { 8261 r = new StringBuilder(256); 8262 } else { 8263 r.append(' '); 8264 } 8265 r.append("DUP:"); 8266 r.append(pg.info.name); 8267 } 8268 } 8269 } 8270 if (r != null) { 8271 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8272 } 8273 8274 N = pkg.permissions.size(); 8275 r = null; 8276 for (i=0; i<N; i++) { 8277 PackageParser.Permission p = pkg.permissions.get(i); 8278 8279 // Assume by default that we did not install this permission into the system. 8280 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8281 8282 // Now that permission groups have a special meaning, we ignore permission 8283 // groups for legacy apps to prevent unexpected behavior. In particular, 8284 // permissions for one app being granted to someone just becase they happen 8285 // to be in a group defined by another app (before this had no implications). 8286 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8287 p.group = mPermissionGroups.get(p.info.group); 8288 // Warn for a permission in an unknown group. 8289 if (p.info.group != null && p.group == null) { 8290 Slog.w(TAG, "Permission " + p.info.name + " from package " 8291 + p.info.packageName + " in an unknown group " + p.info.group); 8292 } 8293 } 8294 8295 ArrayMap<String, BasePermission> permissionMap = 8296 p.tree ? mSettings.mPermissionTrees 8297 : mSettings.mPermissions; 8298 BasePermission bp = permissionMap.get(p.info.name); 8299 8300 // Allow system apps to redefine non-system permissions 8301 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8302 final boolean currentOwnerIsSystem = (bp.perm != null 8303 && isSystemApp(bp.perm.owner)); 8304 if (isSystemApp(p.owner)) { 8305 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8306 // It's a built-in permission and no owner, take ownership now 8307 bp.packageSetting = pkgSetting; 8308 bp.perm = p; 8309 bp.uid = pkg.applicationInfo.uid; 8310 bp.sourcePackage = p.info.packageName; 8311 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8312 } else if (!currentOwnerIsSystem) { 8313 String msg = "New decl " + p.owner + " of permission " 8314 + p.info.name + " is system; overriding " + bp.sourcePackage; 8315 reportSettingsProblem(Log.WARN, msg); 8316 bp = null; 8317 } 8318 } 8319 } 8320 8321 if (bp == null) { 8322 bp = new BasePermission(p.info.name, p.info.packageName, 8323 BasePermission.TYPE_NORMAL); 8324 permissionMap.put(p.info.name, bp); 8325 } 8326 8327 if (bp.perm == null) { 8328 if (bp.sourcePackage == null 8329 || bp.sourcePackage.equals(p.info.packageName)) { 8330 BasePermission tree = findPermissionTreeLP(p.info.name); 8331 if (tree == null 8332 || tree.sourcePackage.equals(p.info.packageName)) { 8333 bp.packageSetting = pkgSetting; 8334 bp.perm = p; 8335 bp.uid = pkg.applicationInfo.uid; 8336 bp.sourcePackage = p.info.packageName; 8337 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8338 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8339 if (r == null) { 8340 r = new StringBuilder(256); 8341 } else { 8342 r.append(' '); 8343 } 8344 r.append(p.info.name); 8345 } 8346 } else { 8347 Slog.w(TAG, "Permission " + p.info.name + " from package " 8348 + p.info.packageName + " ignored: base tree " 8349 + tree.name + " is from package " 8350 + tree.sourcePackage); 8351 } 8352 } else { 8353 Slog.w(TAG, "Permission " + p.info.name + " from package " 8354 + p.info.packageName + " ignored: original from " 8355 + bp.sourcePackage); 8356 } 8357 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8358 if (r == null) { 8359 r = new StringBuilder(256); 8360 } else { 8361 r.append(' '); 8362 } 8363 r.append("DUP:"); 8364 r.append(p.info.name); 8365 } 8366 if (bp.perm == p) { 8367 bp.protectionLevel = p.info.protectionLevel; 8368 } 8369 } 8370 8371 if (r != null) { 8372 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8373 } 8374 8375 N = pkg.instrumentation.size(); 8376 r = null; 8377 for (i=0; i<N; i++) { 8378 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8379 a.info.packageName = pkg.applicationInfo.packageName; 8380 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8381 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8382 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8383 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8384 a.info.dataDir = pkg.applicationInfo.dataDir; 8385 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8386 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8387 8388 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8389 // need other information about the application, like the ABI and what not ? 8390 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8391 mInstrumentation.put(a.getComponentName(), a); 8392 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8393 if (r == null) { 8394 r = new StringBuilder(256); 8395 } else { 8396 r.append(' '); 8397 } 8398 r.append(a.info.name); 8399 } 8400 } 8401 if (r != null) { 8402 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8403 } 8404 8405 if (pkg.protectedBroadcasts != null) { 8406 N = pkg.protectedBroadcasts.size(); 8407 for (i=0; i<N; i++) { 8408 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8409 } 8410 } 8411 8412 pkgSetting.setTimeStamp(scanFileTime); 8413 8414 // Create idmap files for pairs of (packages, overlay packages). 8415 // Note: "android", ie framework-res.apk, is handled by native layers. 8416 if (pkg.mOverlayTarget != null) { 8417 // This is an overlay package. 8418 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8419 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8420 mOverlays.put(pkg.mOverlayTarget, 8421 new ArrayMap<String, PackageParser.Package>()); 8422 } 8423 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8424 map.put(pkg.packageName, pkg); 8425 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8426 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8427 createIdmapFailed = true; 8428 } 8429 } 8430 } else if (mOverlays.containsKey(pkg.packageName) && 8431 !pkg.packageName.equals("android")) { 8432 // This is a regular package, with one or more known overlay packages. 8433 createIdmapsForPackageLI(pkg); 8434 } 8435 } 8436 8437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8438 8439 if (createIdmapFailed) { 8440 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8441 "scanPackageLI failed to createIdmap"); 8442 } 8443 return pkg; 8444 } 8445 8446 /** 8447 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8448 * is derived purely on the basis of the contents of {@code scanFile} and 8449 * {@code cpuAbiOverride}. 8450 * 8451 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8452 */ 8453 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8454 String cpuAbiOverride, boolean extractLibs) 8455 throws PackageManagerException { 8456 // TODO: We can probably be smarter about this stuff. For installed apps, 8457 // we can calculate this information at install time once and for all. For 8458 // system apps, we can probably assume that this information doesn't change 8459 // after the first boot scan. As things stand, we do lots of unnecessary work. 8460 8461 // Give ourselves some initial paths; we'll come back for another 8462 // pass once we've determined ABI below. 8463 setNativeLibraryPaths(pkg); 8464 8465 // We would never need to extract libs for forward-locked and external packages, 8466 // since the container service will do it for us. We shouldn't attempt to 8467 // extract libs from system app when it was not updated. 8468 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8469 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8470 extractLibs = false; 8471 } 8472 8473 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8474 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8475 8476 NativeLibraryHelper.Handle handle = null; 8477 try { 8478 handle = NativeLibraryHelper.Handle.create(pkg); 8479 // TODO(multiArch): This can be null for apps that didn't go through the 8480 // usual installation process. We can calculate it again, like we 8481 // do during install time. 8482 // 8483 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8484 // unnecessary. 8485 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8486 8487 // Null out the abis so that they can be recalculated. 8488 pkg.applicationInfo.primaryCpuAbi = null; 8489 pkg.applicationInfo.secondaryCpuAbi = null; 8490 if (isMultiArch(pkg.applicationInfo)) { 8491 // Warn if we've set an abiOverride for multi-lib packages.. 8492 // By definition, we need to copy both 32 and 64 bit libraries for 8493 // such packages. 8494 if (pkg.cpuAbiOverride != null 8495 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8496 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8497 } 8498 8499 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8500 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8501 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8502 if (extractLibs) { 8503 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8504 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8505 useIsaSpecificSubdirs); 8506 } else { 8507 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8508 } 8509 } 8510 8511 maybeThrowExceptionForMultiArchCopy( 8512 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8513 8514 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8515 if (extractLibs) { 8516 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8517 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8518 useIsaSpecificSubdirs); 8519 } else { 8520 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8521 } 8522 } 8523 8524 maybeThrowExceptionForMultiArchCopy( 8525 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8526 8527 if (abi64 >= 0) { 8528 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8529 } 8530 8531 if (abi32 >= 0) { 8532 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8533 if (abi64 >= 0) { 8534 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8535 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8536 pkg.applicationInfo.primaryCpuAbi = abi; 8537 } else { 8538 pkg.applicationInfo.secondaryCpuAbi = abi; 8539 } 8540 } else { 8541 pkg.applicationInfo.primaryCpuAbi = abi; 8542 } 8543 } 8544 8545 } else { 8546 String[] abiList = (cpuAbiOverride != null) ? 8547 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8548 8549 // Enable gross and lame hacks for apps that are built with old 8550 // SDK tools. We must scan their APKs for renderscript bitcode and 8551 // not launch them if it's present. Don't bother checking on devices 8552 // that don't have 64 bit support. 8553 boolean needsRenderScriptOverride = false; 8554 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8555 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8556 abiList = Build.SUPPORTED_32_BIT_ABIS; 8557 needsRenderScriptOverride = true; 8558 } 8559 8560 final int copyRet; 8561 if (extractLibs) { 8562 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8563 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8564 } else { 8565 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8566 } 8567 8568 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8569 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8570 "Error unpackaging native libs for app, errorCode=" + copyRet); 8571 } 8572 8573 if (copyRet >= 0) { 8574 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8575 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8576 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8577 } else if (needsRenderScriptOverride) { 8578 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8579 } 8580 } 8581 } catch (IOException ioe) { 8582 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8583 } finally { 8584 IoUtils.closeQuietly(handle); 8585 } 8586 8587 // Now that we've calculated the ABIs and determined if it's an internal app, 8588 // we will go ahead and populate the nativeLibraryPath. 8589 setNativeLibraryPaths(pkg); 8590 } 8591 8592 /** 8593 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8594 * i.e, so that all packages can be run inside a single process if required. 8595 * 8596 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8597 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8598 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8599 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8600 * updating a package that belongs to a shared user. 8601 * 8602 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8603 * adds unnecessary complexity. 8604 */ 8605 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8606 PackageParser.Package scannedPackage, boolean bootComplete) { 8607 String requiredInstructionSet = null; 8608 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8609 requiredInstructionSet = VMRuntime.getInstructionSet( 8610 scannedPackage.applicationInfo.primaryCpuAbi); 8611 } 8612 8613 PackageSetting requirer = null; 8614 for (PackageSetting ps : packagesForUser) { 8615 // If packagesForUser contains scannedPackage, we skip it. This will happen 8616 // when scannedPackage is an update of an existing package. Without this check, 8617 // we will never be able to change the ABI of any package belonging to a shared 8618 // user, even if it's compatible with other packages. 8619 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8620 if (ps.primaryCpuAbiString == null) { 8621 continue; 8622 } 8623 8624 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8625 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8626 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8627 // this but there's not much we can do. 8628 String errorMessage = "Instruction set mismatch, " 8629 + ((requirer == null) ? "[caller]" : requirer) 8630 + " requires " + requiredInstructionSet + " whereas " + ps 8631 + " requires " + instructionSet; 8632 Slog.w(TAG, errorMessage); 8633 } 8634 8635 if (requiredInstructionSet == null) { 8636 requiredInstructionSet = instructionSet; 8637 requirer = ps; 8638 } 8639 } 8640 } 8641 8642 if (requiredInstructionSet != null) { 8643 String adjustedAbi; 8644 if (requirer != null) { 8645 // requirer != null implies that either scannedPackage was null or that scannedPackage 8646 // did not require an ABI, in which case we have to adjust scannedPackage to match 8647 // the ABI of the set (which is the same as requirer's ABI) 8648 adjustedAbi = requirer.primaryCpuAbiString; 8649 if (scannedPackage != null) { 8650 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8651 } 8652 } else { 8653 // requirer == null implies that we're updating all ABIs in the set to 8654 // match scannedPackage. 8655 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8656 } 8657 8658 for (PackageSetting ps : packagesForUser) { 8659 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8660 if (ps.primaryCpuAbiString != null) { 8661 continue; 8662 } 8663 8664 ps.primaryCpuAbiString = adjustedAbi; 8665 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8666 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8667 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8668 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8669 + " (requirer=" 8670 + (requirer == null ? "null" : requirer.pkg.packageName) 8671 + ", scannedPackage=" 8672 + (scannedPackage != null ? scannedPackage.packageName : "null") 8673 + ")"); 8674 try { 8675 mInstaller.rmdex(ps.codePathString, 8676 getDexCodeInstructionSet(getPreferredInstructionSet())); 8677 } catch (InstallerException ignored) { 8678 } 8679 } 8680 } 8681 } 8682 } 8683 } 8684 8685 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8686 synchronized (mPackages) { 8687 mResolverReplaced = true; 8688 // Set up information for custom user intent resolution activity. 8689 mResolveActivity.applicationInfo = pkg.applicationInfo; 8690 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8691 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8692 mResolveActivity.processName = pkg.applicationInfo.packageName; 8693 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8694 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8695 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8696 mResolveActivity.theme = 0; 8697 mResolveActivity.exported = true; 8698 mResolveActivity.enabled = true; 8699 mResolveInfo.activityInfo = mResolveActivity; 8700 mResolveInfo.priority = 0; 8701 mResolveInfo.preferredOrder = 0; 8702 mResolveInfo.match = 0; 8703 mResolveComponentName = mCustomResolverComponentName; 8704 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8705 mResolveComponentName); 8706 } 8707 } 8708 8709 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8710 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8711 8712 // Set up information for ephemeral installer activity 8713 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8714 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8715 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8716 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8717 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8718 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8719 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8720 mEphemeralInstallerActivity.theme = 0; 8721 mEphemeralInstallerActivity.exported = true; 8722 mEphemeralInstallerActivity.enabled = true; 8723 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8724 mEphemeralInstallerInfo.priority = 0; 8725 mEphemeralInstallerInfo.preferredOrder = 0; 8726 mEphemeralInstallerInfo.match = 0; 8727 8728 if (DEBUG_EPHEMERAL) { 8729 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8730 } 8731 } 8732 8733 private static String calculateBundledApkRoot(final String codePathString) { 8734 final File codePath = new File(codePathString); 8735 final File codeRoot; 8736 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8737 codeRoot = Environment.getRootDirectory(); 8738 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8739 codeRoot = Environment.getOemDirectory(); 8740 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8741 codeRoot = Environment.getVendorDirectory(); 8742 } else { 8743 // Unrecognized code path; take its top real segment as the apk root: 8744 // e.g. /something/app/blah.apk => /something 8745 try { 8746 File f = codePath.getCanonicalFile(); 8747 File parent = f.getParentFile(); // non-null because codePath is a file 8748 File tmp; 8749 while ((tmp = parent.getParentFile()) != null) { 8750 f = parent; 8751 parent = tmp; 8752 } 8753 codeRoot = f; 8754 Slog.w(TAG, "Unrecognized code path " 8755 + codePath + " - using " + codeRoot); 8756 } catch (IOException e) { 8757 // Can't canonicalize the code path -- shenanigans? 8758 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8759 return Environment.getRootDirectory().getPath(); 8760 } 8761 } 8762 return codeRoot.getPath(); 8763 } 8764 8765 /** 8766 * Derive and set the location of native libraries for the given package, 8767 * which varies depending on where and how the package was installed. 8768 */ 8769 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8770 final ApplicationInfo info = pkg.applicationInfo; 8771 final String codePath = pkg.codePath; 8772 final File codeFile = new File(codePath); 8773 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8774 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8775 8776 info.nativeLibraryRootDir = null; 8777 info.nativeLibraryRootRequiresIsa = false; 8778 info.nativeLibraryDir = null; 8779 info.secondaryNativeLibraryDir = null; 8780 8781 if (isApkFile(codeFile)) { 8782 // Monolithic install 8783 if (bundledApp) { 8784 // If "/system/lib64/apkname" exists, assume that is the per-package 8785 // native library directory to use; otherwise use "/system/lib/apkname". 8786 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8787 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8788 getPrimaryInstructionSet(info)); 8789 8790 // This is a bundled system app so choose the path based on the ABI. 8791 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8792 // is just the default path. 8793 final String apkName = deriveCodePathName(codePath); 8794 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8795 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8796 apkName).getAbsolutePath(); 8797 8798 if (info.secondaryCpuAbi != null) { 8799 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8800 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8801 secondaryLibDir, apkName).getAbsolutePath(); 8802 } 8803 } else if (asecApp) { 8804 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8805 .getAbsolutePath(); 8806 } else { 8807 final String apkName = deriveCodePathName(codePath); 8808 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8809 .getAbsolutePath(); 8810 } 8811 8812 info.nativeLibraryRootRequiresIsa = false; 8813 info.nativeLibraryDir = info.nativeLibraryRootDir; 8814 } else { 8815 // Cluster install 8816 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8817 info.nativeLibraryRootRequiresIsa = true; 8818 8819 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8820 getPrimaryInstructionSet(info)).getAbsolutePath(); 8821 8822 if (info.secondaryCpuAbi != null) { 8823 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8824 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8825 } 8826 } 8827 } 8828 8829 /** 8830 * Calculate the abis and roots for a bundled app. These can uniquely 8831 * be determined from the contents of the system partition, i.e whether 8832 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8833 * of this information, and instead assume that the system was built 8834 * sensibly. 8835 */ 8836 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8837 PackageSetting pkgSetting) { 8838 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8839 8840 // If "/system/lib64/apkname" exists, assume that is the per-package 8841 // native library directory to use; otherwise use "/system/lib/apkname". 8842 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8843 setBundledAppAbi(pkg, apkRoot, apkName); 8844 // pkgSetting might be null during rescan following uninstall of updates 8845 // to a bundled app, so accommodate that possibility. The settings in 8846 // that case will be established later from the parsed package. 8847 // 8848 // If the settings aren't null, sync them up with what we've just derived. 8849 // note that apkRoot isn't stored in the package settings. 8850 if (pkgSetting != null) { 8851 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8852 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8853 } 8854 } 8855 8856 /** 8857 * Deduces the ABI of a bundled app and sets the relevant fields on the 8858 * parsed pkg object. 8859 * 8860 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8861 * under which system libraries are installed. 8862 * @param apkName the name of the installed package. 8863 */ 8864 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8865 final File codeFile = new File(pkg.codePath); 8866 8867 final boolean has64BitLibs; 8868 final boolean has32BitLibs; 8869 if (isApkFile(codeFile)) { 8870 // Monolithic install 8871 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8872 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8873 } else { 8874 // Cluster install 8875 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8876 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8877 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8878 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8879 has64BitLibs = (new File(rootDir, isa)).exists(); 8880 } else { 8881 has64BitLibs = false; 8882 } 8883 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8884 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8885 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8886 has32BitLibs = (new File(rootDir, isa)).exists(); 8887 } else { 8888 has32BitLibs = false; 8889 } 8890 } 8891 8892 if (has64BitLibs && !has32BitLibs) { 8893 // The package has 64 bit libs, but not 32 bit libs. Its primary 8894 // ABI should be 64 bit. We can safely assume here that the bundled 8895 // native libraries correspond to the most preferred ABI in the list. 8896 8897 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8898 pkg.applicationInfo.secondaryCpuAbi = null; 8899 } else if (has32BitLibs && !has64BitLibs) { 8900 // The package has 32 bit libs but not 64 bit libs. Its primary 8901 // ABI should be 32 bit. 8902 8903 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8904 pkg.applicationInfo.secondaryCpuAbi = null; 8905 } else if (has32BitLibs && has64BitLibs) { 8906 // The application has both 64 and 32 bit bundled libraries. We check 8907 // here that the app declares multiArch support, and warn if it doesn't. 8908 // 8909 // We will be lenient here and record both ABIs. The primary will be the 8910 // ABI that's higher on the list, i.e, a device that's configured to prefer 8911 // 64 bit apps will see a 64 bit primary ABI, 8912 8913 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8914 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8915 } 8916 8917 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8918 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8919 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8920 } else { 8921 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8922 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8923 } 8924 } else { 8925 pkg.applicationInfo.primaryCpuAbi = null; 8926 pkg.applicationInfo.secondaryCpuAbi = null; 8927 } 8928 } 8929 8930 private void killPackage(PackageParser.Package pkg, String reason) { 8931 // Kill the parent package 8932 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8933 // Kill the child packages 8934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8935 for (int i = 0; i < childCount; i++) { 8936 PackageParser.Package childPkg = pkg.childPackages.get(i); 8937 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8938 } 8939 } 8940 8941 private void killApplication(String pkgName, int appId, String reason) { 8942 // Request the ActivityManager to kill the process(only for existing packages) 8943 // so that we do not end up in a confused state while the user is still using the older 8944 // version of the application while the new one gets installed. 8945 IActivityManager am = ActivityManagerNative.getDefault(); 8946 if (am != null) { 8947 try { 8948 am.killApplicationWithAppId(pkgName, appId, reason); 8949 } catch (RemoteException e) { 8950 } 8951 } 8952 } 8953 8954 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8955 // Remove the parent package setting 8956 PackageSetting ps = (PackageSetting) pkg.mExtras; 8957 if (ps != null) { 8958 removePackageLI(ps, chatty); 8959 } 8960 // Remove the child package setting 8961 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8962 for (int i = 0; i < childCount; i++) { 8963 PackageParser.Package childPkg = pkg.childPackages.get(i); 8964 ps = (PackageSetting) childPkg.mExtras; 8965 if (ps != null) { 8966 removePackageLI(ps, chatty); 8967 } 8968 } 8969 } 8970 8971 void removePackageLI(PackageSetting ps, boolean chatty) { 8972 if (DEBUG_INSTALL) { 8973 if (chatty) 8974 Log.d(TAG, "Removing package " + ps.name); 8975 } 8976 8977 // writer 8978 synchronized (mPackages) { 8979 mPackages.remove(ps.name); 8980 final PackageParser.Package pkg = ps.pkg; 8981 if (pkg != null) { 8982 cleanPackageDataStructuresLILPw(pkg, chatty); 8983 } 8984 } 8985 } 8986 8987 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8988 if (DEBUG_INSTALL) { 8989 if (chatty) 8990 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8991 } 8992 8993 // writer 8994 synchronized (mPackages) { 8995 // Remove the parent package 8996 mPackages.remove(pkg.applicationInfo.packageName); 8997 cleanPackageDataStructuresLILPw(pkg, chatty); 8998 8999 // Remove the child packages 9000 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9001 for (int i = 0; i < childCount; i++) { 9002 PackageParser.Package childPkg = pkg.childPackages.get(i); 9003 mPackages.remove(childPkg.applicationInfo.packageName); 9004 cleanPackageDataStructuresLILPw(childPkg, chatty); 9005 } 9006 } 9007 } 9008 9009 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9010 int N = pkg.providers.size(); 9011 StringBuilder r = null; 9012 int i; 9013 for (i=0; i<N; i++) { 9014 PackageParser.Provider p = pkg.providers.get(i); 9015 mProviders.removeProvider(p); 9016 if (p.info.authority == null) { 9017 9018 /* There was another ContentProvider with this authority when 9019 * this app was installed so this authority is null, 9020 * Ignore it as we don't have to unregister the provider. 9021 */ 9022 continue; 9023 } 9024 String names[] = p.info.authority.split(";"); 9025 for (int j = 0; j < names.length; j++) { 9026 if (mProvidersByAuthority.get(names[j]) == p) { 9027 mProvidersByAuthority.remove(names[j]); 9028 if (DEBUG_REMOVE) { 9029 if (chatty) 9030 Log.d(TAG, "Unregistered content provider: " + names[j] 9031 + ", className = " + p.info.name + ", isSyncable = " 9032 + p.info.isSyncable); 9033 } 9034 } 9035 } 9036 if (DEBUG_REMOVE && chatty) { 9037 if (r == null) { 9038 r = new StringBuilder(256); 9039 } else { 9040 r.append(' '); 9041 } 9042 r.append(p.info.name); 9043 } 9044 } 9045 if (r != null) { 9046 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9047 } 9048 9049 N = pkg.services.size(); 9050 r = null; 9051 for (i=0; i<N; i++) { 9052 PackageParser.Service s = pkg.services.get(i); 9053 mServices.removeService(s); 9054 if (chatty) { 9055 if (r == null) { 9056 r = new StringBuilder(256); 9057 } else { 9058 r.append(' '); 9059 } 9060 r.append(s.info.name); 9061 } 9062 } 9063 if (r != null) { 9064 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9065 } 9066 9067 N = pkg.receivers.size(); 9068 r = null; 9069 for (i=0; i<N; i++) { 9070 PackageParser.Activity a = pkg.receivers.get(i); 9071 mReceivers.removeActivity(a, "receiver"); 9072 if (DEBUG_REMOVE && chatty) { 9073 if (r == null) { 9074 r = new StringBuilder(256); 9075 } else { 9076 r.append(' '); 9077 } 9078 r.append(a.info.name); 9079 } 9080 } 9081 if (r != null) { 9082 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9083 } 9084 9085 N = pkg.activities.size(); 9086 r = null; 9087 for (i=0; i<N; i++) { 9088 PackageParser.Activity a = pkg.activities.get(i); 9089 mActivities.removeActivity(a, "activity"); 9090 if (DEBUG_REMOVE && chatty) { 9091 if (r == null) { 9092 r = new StringBuilder(256); 9093 } else { 9094 r.append(' '); 9095 } 9096 r.append(a.info.name); 9097 } 9098 } 9099 if (r != null) { 9100 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9101 } 9102 9103 N = pkg.permissions.size(); 9104 r = null; 9105 for (i=0; i<N; i++) { 9106 PackageParser.Permission p = pkg.permissions.get(i); 9107 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9108 if (bp == null) { 9109 bp = mSettings.mPermissionTrees.get(p.info.name); 9110 } 9111 if (bp != null && bp.perm == p) { 9112 bp.perm = null; 9113 if (DEBUG_REMOVE && chatty) { 9114 if (r == null) { 9115 r = new StringBuilder(256); 9116 } else { 9117 r.append(' '); 9118 } 9119 r.append(p.info.name); 9120 } 9121 } 9122 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9123 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9124 if (appOpPkgs != null) { 9125 appOpPkgs.remove(pkg.packageName); 9126 } 9127 } 9128 } 9129 if (r != null) { 9130 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9131 } 9132 9133 N = pkg.requestedPermissions.size(); 9134 r = null; 9135 for (i=0; i<N; i++) { 9136 String perm = pkg.requestedPermissions.get(i); 9137 BasePermission bp = mSettings.mPermissions.get(perm); 9138 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9139 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9140 if (appOpPkgs != null) { 9141 appOpPkgs.remove(pkg.packageName); 9142 if (appOpPkgs.isEmpty()) { 9143 mAppOpPermissionPackages.remove(perm); 9144 } 9145 } 9146 } 9147 } 9148 if (r != null) { 9149 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9150 } 9151 9152 N = pkg.instrumentation.size(); 9153 r = null; 9154 for (i=0; i<N; i++) { 9155 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9156 mInstrumentation.remove(a.getComponentName()); 9157 if (DEBUG_REMOVE && chatty) { 9158 if (r == null) { 9159 r = new StringBuilder(256); 9160 } else { 9161 r.append(' '); 9162 } 9163 r.append(a.info.name); 9164 } 9165 } 9166 if (r != null) { 9167 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9168 } 9169 9170 r = null; 9171 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9172 // Only system apps can hold shared libraries. 9173 if (pkg.libraryNames != null) { 9174 for (i=0; i<pkg.libraryNames.size(); i++) { 9175 String name = pkg.libraryNames.get(i); 9176 SharedLibraryEntry cur = mSharedLibraries.get(name); 9177 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9178 mSharedLibraries.remove(name); 9179 if (DEBUG_REMOVE && chatty) { 9180 if (r == null) { 9181 r = new StringBuilder(256); 9182 } else { 9183 r.append(' '); 9184 } 9185 r.append(name); 9186 } 9187 } 9188 } 9189 } 9190 } 9191 if (r != null) { 9192 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9193 } 9194 } 9195 9196 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9197 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9198 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9199 return true; 9200 } 9201 } 9202 return false; 9203 } 9204 9205 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9206 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9207 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9208 9209 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9210 // Update the parent permissions 9211 updatePermissionsLPw(pkg.packageName, pkg, flags); 9212 // Update the child permissions 9213 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9214 for (int i = 0; i < childCount; i++) { 9215 PackageParser.Package childPkg = pkg.childPackages.get(i); 9216 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9217 } 9218 } 9219 9220 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9221 int flags) { 9222 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9223 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9224 } 9225 9226 private void updatePermissionsLPw(String changingPkg, 9227 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9228 // Make sure there are no dangling permission trees. 9229 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9230 while (it.hasNext()) { 9231 final BasePermission bp = it.next(); 9232 if (bp.packageSetting == null) { 9233 // We may not yet have parsed the package, so just see if 9234 // we still know about its settings. 9235 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9236 } 9237 if (bp.packageSetting == null) { 9238 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9239 + " from package " + bp.sourcePackage); 9240 it.remove(); 9241 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9242 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9243 Slog.i(TAG, "Removing old permission tree: " + bp.name 9244 + " from package " + bp.sourcePackage); 9245 flags |= UPDATE_PERMISSIONS_ALL; 9246 it.remove(); 9247 } 9248 } 9249 } 9250 9251 // Make sure all dynamic permissions have been assigned to a package, 9252 // and make sure there are no dangling permissions. 9253 it = mSettings.mPermissions.values().iterator(); 9254 while (it.hasNext()) { 9255 final BasePermission bp = it.next(); 9256 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9257 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9258 + bp.name + " pkg=" + bp.sourcePackage 9259 + " info=" + bp.pendingInfo); 9260 if (bp.packageSetting == null && bp.pendingInfo != null) { 9261 final BasePermission tree = findPermissionTreeLP(bp.name); 9262 if (tree != null && tree.perm != null) { 9263 bp.packageSetting = tree.packageSetting; 9264 bp.perm = new PackageParser.Permission(tree.perm.owner, 9265 new PermissionInfo(bp.pendingInfo)); 9266 bp.perm.info.packageName = tree.perm.info.packageName; 9267 bp.perm.info.name = bp.name; 9268 bp.uid = tree.uid; 9269 } 9270 } 9271 } 9272 if (bp.packageSetting == null) { 9273 // We may not yet have parsed the package, so just see if 9274 // we still know about its settings. 9275 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9276 } 9277 if (bp.packageSetting == null) { 9278 Slog.w(TAG, "Removing dangling permission: " + bp.name 9279 + " from package " + bp.sourcePackage); 9280 it.remove(); 9281 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9282 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9283 Slog.i(TAG, "Removing old permission: " + bp.name 9284 + " from package " + bp.sourcePackage); 9285 flags |= UPDATE_PERMISSIONS_ALL; 9286 it.remove(); 9287 } 9288 } 9289 } 9290 9291 // Now update the permissions for all packages, in particular 9292 // replace the granted permissions of the system packages. 9293 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9294 for (PackageParser.Package pkg : mPackages.values()) { 9295 if (pkg != pkgInfo) { 9296 // Only replace for packages on requested volume 9297 final String volumeUuid = getVolumeUuidForPackage(pkg); 9298 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9299 && Objects.equals(replaceVolumeUuid, volumeUuid); 9300 grantPermissionsLPw(pkg, replace, changingPkg); 9301 } 9302 } 9303 } 9304 9305 if (pkgInfo != null) { 9306 // Only replace for packages on requested volume 9307 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9308 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9309 && Objects.equals(replaceVolumeUuid, volumeUuid); 9310 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9311 } 9312 } 9313 9314 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9315 String packageOfInterest) { 9316 // IMPORTANT: There are two types of permissions: install and runtime. 9317 // Install time permissions are granted when the app is installed to 9318 // all device users and users added in the future. Runtime permissions 9319 // are granted at runtime explicitly to specific users. Normal and signature 9320 // protected permissions are install time permissions. Dangerous permissions 9321 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9322 // otherwise they are runtime permissions. This function does not manage 9323 // runtime permissions except for the case an app targeting Lollipop MR1 9324 // being upgraded to target a newer SDK, in which case dangerous permissions 9325 // are transformed from install time to runtime ones. 9326 9327 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9328 if (ps == null) { 9329 return; 9330 } 9331 9332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9333 9334 PermissionsState permissionsState = ps.getPermissionsState(); 9335 PermissionsState origPermissions = permissionsState; 9336 9337 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9338 9339 boolean runtimePermissionsRevoked = false; 9340 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9341 9342 boolean changedInstallPermission = false; 9343 9344 if (replace) { 9345 ps.installPermissionsFixed = false; 9346 if (!ps.isSharedUser()) { 9347 origPermissions = new PermissionsState(permissionsState); 9348 permissionsState.reset(); 9349 } else { 9350 // We need to know only about runtime permission changes since the 9351 // calling code always writes the install permissions state but 9352 // the runtime ones are written only if changed. The only cases of 9353 // changed runtime permissions here are promotion of an install to 9354 // runtime and revocation of a runtime from a shared user. 9355 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9356 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9357 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9358 runtimePermissionsRevoked = true; 9359 } 9360 } 9361 } 9362 9363 permissionsState.setGlobalGids(mGlobalGids); 9364 9365 final int N = pkg.requestedPermissions.size(); 9366 for (int i=0; i<N; i++) { 9367 final String name = pkg.requestedPermissions.get(i); 9368 final BasePermission bp = mSettings.mPermissions.get(name); 9369 9370 if (DEBUG_INSTALL) { 9371 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9372 } 9373 9374 if (bp == null || bp.packageSetting == null) { 9375 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9376 Slog.w(TAG, "Unknown permission " + name 9377 + " in package " + pkg.packageName); 9378 } 9379 continue; 9380 } 9381 9382 final String perm = bp.name; 9383 boolean allowedSig = false; 9384 int grant = GRANT_DENIED; 9385 9386 // Keep track of app op permissions. 9387 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9388 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9389 if (pkgs == null) { 9390 pkgs = new ArraySet<>(); 9391 mAppOpPermissionPackages.put(bp.name, pkgs); 9392 } 9393 pkgs.add(pkg.packageName); 9394 } 9395 9396 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9397 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9398 >= Build.VERSION_CODES.M; 9399 switch (level) { 9400 case PermissionInfo.PROTECTION_NORMAL: { 9401 // For all apps normal permissions are install time ones. 9402 grant = GRANT_INSTALL; 9403 } break; 9404 9405 case PermissionInfo.PROTECTION_DANGEROUS: { 9406 // If a permission review is required for legacy apps we represent 9407 // their permissions as always granted runtime ones since we need 9408 // to keep the review required permission flag per user while an 9409 // install permission's state is shared across all users. 9410 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9411 // For legacy apps dangerous permissions are install time ones. 9412 grant = GRANT_INSTALL; 9413 } else if (origPermissions.hasInstallPermission(bp.name)) { 9414 // For legacy apps that became modern, install becomes runtime. 9415 grant = GRANT_UPGRADE; 9416 } else if (mPromoteSystemApps 9417 && isSystemApp(ps) 9418 && mExistingSystemPackages.contains(ps.name)) { 9419 // For legacy system apps, install becomes runtime. 9420 // We cannot check hasInstallPermission() for system apps since those 9421 // permissions were granted implicitly and not persisted pre-M. 9422 grant = GRANT_UPGRADE; 9423 } else { 9424 // For modern apps keep runtime permissions unchanged. 9425 grant = GRANT_RUNTIME; 9426 } 9427 } break; 9428 9429 case PermissionInfo.PROTECTION_SIGNATURE: { 9430 // For all apps signature permissions are install time ones. 9431 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9432 if (allowedSig) { 9433 grant = GRANT_INSTALL; 9434 } 9435 } break; 9436 } 9437 9438 if (DEBUG_INSTALL) { 9439 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9440 } 9441 9442 if (grant != GRANT_DENIED) { 9443 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9444 // If this is an existing, non-system package, then 9445 // we can't add any new permissions to it. 9446 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9447 // Except... if this is a permission that was added 9448 // to the platform (note: need to only do this when 9449 // updating the platform). 9450 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9451 grant = GRANT_DENIED; 9452 } 9453 } 9454 } 9455 9456 switch (grant) { 9457 case GRANT_INSTALL: { 9458 // Revoke this as runtime permission to handle the case of 9459 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9460 for (int userId : UserManagerService.getInstance().getUserIds()) { 9461 if (origPermissions.getRuntimePermissionState( 9462 bp.name, userId) != null) { 9463 // Revoke the runtime permission and clear the flags. 9464 origPermissions.revokeRuntimePermission(bp, userId); 9465 origPermissions.updatePermissionFlags(bp, userId, 9466 PackageManager.MASK_PERMISSION_FLAGS, 0); 9467 // If we revoked a permission permission, we have to write. 9468 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9469 changedRuntimePermissionUserIds, userId); 9470 } 9471 } 9472 // Grant an install permission. 9473 if (permissionsState.grantInstallPermission(bp) != 9474 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9475 changedInstallPermission = true; 9476 } 9477 } break; 9478 9479 case GRANT_RUNTIME: { 9480 // Grant previously granted runtime permissions. 9481 for (int userId : UserManagerService.getInstance().getUserIds()) { 9482 PermissionState permissionState = origPermissions 9483 .getRuntimePermissionState(bp.name, userId); 9484 int flags = permissionState != null 9485 ? permissionState.getFlags() : 0; 9486 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9487 if (permissionsState.grantRuntimePermission(bp, userId) == 9488 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9489 // If we cannot put the permission as it was, we have to write. 9490 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9491 changedRuntimePermissionUserIds, userId); 9492 } 9493 // If the app supports runtime permissions no need for a review. 9494 if (Build.PERMISSIONS_REVIEW_REQUIRED 9495 && appSupportsRuntimePermissions 9496 && (flags & PackageManager 9497 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9498 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9499 // Since we changed the flags, we have to write. 9500 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9501 changedRuntimePermissionUserIds, userId); 9502 } 9503 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9504 && !appSupportsRuntimePermissions) { 9505 // For legacy apps that need a permission review, every new 9506 // runtime permission is granted but it is pending a review. 9507 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9508 permissionsState.grantRuntimePermission(bp, userId); 9509 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9510 // We changed the permission and flags, hence have to write. 9511 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9512 changedRuntimePermissionUserIds, userId); 9513 } 9514 } 9515 // Propagate the permission flags. 9516 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9517 } 9518 } break; 9519 9520 case GRANT_UPGRADE: { 9521 // Grant runtime permissions for a previously held install permission. 9522 PermissionState permissionState = origPermissions 9523 .getInstallPermissionState(bp.name); 9524 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9525 9526 if (origPermissions.revokeInstallPermission(bp) 9527 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9528 // We will be transferring the permission flags, so clear them. 9529 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9530 PackageManager.MASK_PERMISSION_FLAGS, 0); 9531 changedInstallPermission = true; 9532 } 9533 9534 // If the permission is not to be promoted to runtime we ignore it and 9535 // also its other flags as they are not applicable to install permissions. 9536 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9537 for (int userId : currentUserIds) { 9538 if (permissionsState.grantRuntimePermission(bp, userId) != 9539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9540 // Transfer the permission flags. 9541 permissionsState.updatePermissionFlags(bp, userId, 9542 flags, flags); 9543 // If we granted the permission, we have to write. 9544 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9545 changedRuntimePermissionUserIds, userId); 9546 } 9547 } 9548 } 9549 } break; 9550 9551 default: { 9552 if (packageOfInterest == null 9553 || packageOfInterest.equals(pkg.packageName)) { 9554 Slog.w(TAG, "Not granting permission " + perm 9555 + " to package " + pkg.packageName 9556 + " because it was previously installed without"); 9557 } 9558 } break; 9559 } 9560 } else { 9561 if (permissionsState.revokeInstallPermission(bp) != 9562 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9563 // Also drop the permission flags. 9564 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9565 PackageManager.MASK_PERMISSION_FLAGS, 0); 9566 changedInstallPermission = true; 9567 Slog.i(TAG, "Un-granting permission " + perm 9568 + " from package " + pkg.packageName 9569 + " (protectionLevel=" + bp.protectionLevel 9570 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9571 + ")"); 9572 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9573 // Don't print warning for app op permissions, since it is fine for them 9574 // not to be granted, there is a UI for the user to decide. 9575 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9576 Slog.w(TAG, "Not granting permission " + perm 9577 + " to package " + pkg.packageName 9578 + " (protectionLevel=" + bp.protectionLevel 9579 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9580 + ")"); 9581 } 9582 } 9583 } 9584 } 9585 9586 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9587 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9588 // This is the first that we have heard about this package, so the 9589 // permissions we have now selected are fixed until explicitly 9590 // changed. 9591 ps.installPermissionsFixed = true; 9592 } 9593 9594 // Persist the runtime permissions state for users with changes. If permissions 9595 // were revoked because no app in the shared user declares them we have to 9596 // write synchronously to avoid losing runtime permissions state. 9597 for (int userId : changedRuntimePermissionUserIds) { 9598 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9599 } 9600 9601 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9602 } 9603 9604 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9605 boolean allowed = false; 9606 final int NP = PackageParser.NEW_PERMISSIONS.length; 9607 for (int ip=0; ip<NP; ip++) { 9608 final PackageParser.NewPermissionInfo npi 9609 = PackageParser.NEW_PERMISSIONS[ip]; 9610 if (npi.name.equals(perm) 9611 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9612 allowed = true; 9613 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9614 + pkg.packageName); 9615 break; 9616 } 9617 } 9618 return allowed; 9619 } 9620 9621 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9622 BasePermission bp, PermissionsState origPermissions) { 9623 boolean allowed; 9624 allowed = (compareSignatures( 9625 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9626 == PackageManager.SIGNATURE_MATCH) 9627 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9628 == PackageManager.SIGNATURE_MATCH); 9629 if (!allowed && (bp.protectionLevel 9630 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9631 if (isSystemApp(pkg)) { 9632 // For updated system applications, a system permission 9633 // is granted only if it had been defined by the original application. 9634 if (pkg.isUpdatedSystemApp()) { 9635 final PackageSetting sysPs = mSettings 9636 .getDisabledSystemPkgLPr(pkg.packageName); 9637 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9638 // If the original was granted this permission, we take 9639 // that grant decision as read and propagate it to the 9640 // update. 9641 if (sysPs.isPrivileged()) { 9642 allowed = true; 9643 } 9644 } else { 9645 // The system apk may have been updated with an older 9646 // version of the one on the data partition, but which 9647 // granted a new system permission that it didn't have 9648 // before. In this case we do want to allow the app to 9649 // now get the new permission if the ancestral apk is 9650 // privileged to get it. 9651 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9652 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9653 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9654 allowed = true; 9655 break; 9656 } 9657 } 9658 } 9659 // Also if a privileged parent package on the system image or any of 9660 // its children requested a privileged permission, the updated child 9661 // packages can also get the permission. 9662 if (pkg.parentPackage != null) { 9663 final PackageSetting disabledSysParentPs = mSettings 9664 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9665 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9666 && disabledSysParentPs.isPrivileged()) { 9667 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9668 allowed = true; 9669 } else if (disabledSysParentPs.pkg.childPackages != null) { 9670 final int count = disabledSysParentPs.pkg.childPackages.size(); 9671 for (int i = 0; i < count; i++) { 9672 PackageParser.Package disabledSysChildPkg = 9673 disabledSysParentPs.pkg.childPackages.get(i); 9674 if (isPackageRequestingPermission(disabledSysChildPkg, 9675 perm)) { 9676 allowed = true; 9677 break; 9678 } 9679 } 9680 } 9681 } 9682 } 9683 } 9684 } else { 9685 allowed = isPrivilegedApp(pkg); 9686 } 9687 } 9688 } 9689 if (!allowed) { 9690 if (!allowed && (bp.protectionLevel 9691 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9692 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9693 // If this was a previously normal/dangerous permission that got moved 9694 // to a system permission as part of the runtime permission redesign, then 9695 // we still want to blindly grant it to old apps. 9696 allowed = true; 9697 } 9698 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9699 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9700 // If this permission is to be granted to the system installer and 9701 // this app is an installer, then it gets the permission. 9702 allowed = true; 9703 } 9704 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9705 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9706 // If this permission is to be granted to the system verifier and 9707 // this app is a verifier, then it gets the permission. 9708 allowed = true; 9709 } 9710 if (!allowed && (bp.protectionLevel 9711 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9712 && isSystemApp(pkg)) { 9713 // Any pre-installed system app is allowed to get this permission. 9714 allowed = true; 9715 } 9716 if (!allowed && (bp.protectionLevel 9717 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9718 // For development permissions, a development permission 9719 // is granted only if it was already granted. 9720 allowed = origPermissions.hasInstallPermission(perm); 9721 } 9722 } 9723 return allowed; 9724 } 9725 9726 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9727 final int permCount = pkg.requestedPermissions.size(); 9728 for (int j = 0; j < permCount; j++) { 9729 String requestedPermission = pkg.requestedPermissions.get(j); 9730 if (permission.equals(requestedPermission)) { 9731 return true; 9732 } 9733 } 9734 return false; 9735 } 9736 9737 final class ActivityIntentResolver 9738 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9739 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9740 boolean defaultOnly, int userId) { 9741 if (!sUserManager.exists(userId)) return null; 9742 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9743 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9744 } 9745 9746 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9747 int userId) { 9748 if (!sUserManager.exists(userId)) return null; 9749 mFlags = flags; 9750 return super.queryIntent(intent, resolvedType, 9751 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9752 } 9753 9754 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9755 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9756 if (!sUserManager.exists(userId)) return null; 9757 if (packageActivities == null) { 9758 return null; 9759 } 9760 mFlags = flags; 9761 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9762 final int N = packageActivities.size(); 9763 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9764 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9765 9766 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9767 for (int i = 0; i < N; ++i) { 9768 intentFilters = packageActivities.get(i).intents; 9769 if (intentFilters != null && intentFilters.size() > 0) { 9770 PackageParser.ActivityIntentInfo[] array = 9771 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9772 intentFilters.toArray(array); 9773 listCut.add(array); 9774 } 9775 } 9776 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9777 } 9778 9779 public final void addActivity(PackageParser.Activity a, String type) { 9780 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9781 mActivities.put(a.getComponentName(), a); 9782 if (DEBUG_SHOW_INFO) 9783 Log.v( 9784 TAG, " " + type + " " + 9785 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9786 if (DEBUG_SHOW_INFO) 9787 Log.v(TAG, " Class=" + a.info.name); 9788 final int NI = a.intents.size(); 9789 for (int j=0; j<NI; j++) { 9790 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9791 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9792 intent.setPriority(0); 9793 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9794 + a.className + " with priority > 0, forcing to 0"); 9795 } 9796 if (DEBUG_SHOW_INFO) { 9797 Log.v(TAG, " IntentFilter:"); 9798 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9799 } 9800 if (!intent.debugCheck()) { 9801 Log.w(TAG, "==> For Activity " + a.info.name); 9802 } 9803 addFilter(intent); 9804 } 9805 } 9806 9807 public final void removeActivity(PackageParser.Activity a, String type) { 9808 mActivities.remove(a.getComponentName()); 9809 if (DEBUG_SHOW_INFO) { 9810 Log.v(TAG, " " + type + " " 9811 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9812 : a.info.name) + ":"); 9813 Log.v(TAG, " Class=" + a.info.name); 9814 } 9815 final int NI = a.intents.size(); 9816 for (int j=0; j<NI; j++) { 9817 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9818 if (DEBUG_SHOW_INFO) { 9819 Log.v(TAG, " IntentFilter:"); 9820 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9821 } 9822 removeFilter(intent); 9823 } 9824 } 9825 9826 @Override 9827 protected boolean allowFilterResult( 9828 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9829 ActivityInfo filterAi = filter.activity.info; 9830 for (int i=dest.size()-1; i>=0; i--) { 9831 ActivityInfo destAi = dest.get(i).activityInfo; 9832 if (destAi.name == filterAi.name 9833 && destAi.packageName == filterAi.packageName) { 9834 return false; 9835 } 9836 } 9837 return true; 9838 } 9839 9840 @Override 9841 protected ActivityIntentInfo[] newArray(int size) { 9842 return new ActivityIntentInfo[size]; 9843 } 9844 9845 @Override 9846 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9847 if (!sUserManager.exists(userId)) return true; 9848 PackageParser.Package p = filter.activity.owner; 9849 if (p != null) { 9850 PackageSetting ps = (PackageSetting)p.mExtras; 9851 if (ps != null) { 9852 // System apps are never considered stopped for purposes of 9853 // filtering, because there may be no way for the user to 9854 // actually re-launch them. 9855 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9856 && ps.getStopped(userId); 9857 } 9858 } 9859 return false; 9860 } 9861 9862 @Override 9863 protected boolean isPackageForFilter(String packageName, 9864 PackageParser.ActivityIntentInfo info) { 9865 return packageName.equals(info.activity.owner.packageName); 9866 } 9867 9868 @Override 9869 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9870 int match, int userId) { 9871 if (!sUserManager.exists(userId)) return null; 9872 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9873 return null; 9874 } 9875 final PackageParser.Activity activity = info.activity; 9876 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9877 if (ps == null) { 9878 return null; 9879 } 9880 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9881 ps.readUserState(userId), userId); 9882 if (ai == null) { 9883 return null; 9884 } 9885 final ResolveInfo res = new ResolveInfo(); 9886 res.activityInfo = ai; 9887 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9888 res.filter = info; 9889 } 9890 if (info != null) { 9891 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9892 } 9893 res.priority = info.getPriority(); 9894 res.preferredOrder = activity.owner.mPreferredOrder; 9895 //System.out.println("Result: " + res.activityInfo.className + 9896 // " = " + res.priority); 9897 res.match = match; 9898 res.isDefault = info.hasDefault; 9899 res.labelRes = info.labelRes; 9900 res.nonLocalizedLabel = info.nonLocalizedLabel; 9901 if (userNeedsBadging(userId)) { 9902 res.noResourceId = true; 9903 } else { 9904 res.icon = info.icon; 9905 } 9906 res.iconResourceId = info.icon; 9907 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9908 return res; 9909 } 9910 9911 @Override 9912 protected void sortResults(List<ResolveInfo> results) { 9913 Collections.sort(results, mResolvePrioritySorter); 9914 } 9915 9916 @Override 9917 protected void dumpFilter(PrintWriter out, String prefix, 9918 PackageParser.ActivityIntentInfo filter) { 9919 out.print(prefix); out.print( 9920 Integer.toHexString(System.identityHashCode(filter.activity))); 9921 out.print(' '); 9922 filter.activity.printComponentShortName(out); 9923 out.print(" filter "); 9924 out.println(Integer.toHexString(System.identityHashCode(filter))); 9925 } 9926 9927 @Override 9928 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9929 return filter.activity; 9930 } 9931 9932 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9933 PackageParser.Activity activity = (PackageParser.Activity)label; 9934 out.print(prefix); out.print( 9935 Integer.toHexString(System.identityHashCode(activity))); 9936 out.print(' '); 9937 activity.printComponentShortName(out); 9938 if (count > 1) { 9939 out.print(" ("); out.print(count); out.print(" filters)"); 9940 } 9941 out.println(); 9942 } 9943 9944// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9945// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9946// final List<ResolveInfo> retList = Lists.newArrayList(); 9947// while (i.hasNext()) { 9948// final ResolveInfo resolveInfo = i.next(); 9949// if (isEnabledLP(resolveInfo.activityInfo)) { 9950// retList.add(resolveInfo); 9951// } 9952// } 9953// return retList; 9954// } 9955 9956 // Keys are String (activity class name), values are Activity. 9957 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9958 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9959 private int mFlags; 9960 } 9961 9962 private final class ServiceIntentResolver 9963 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9964 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9965 boolean defaultOnly, int userId) { 9966 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9967 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9968 } 9969 9970 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9971 int userId) { 9972 if (!sUserManager.exists(userId)) return null; 9973 mFlags = flags; 9974 return super.queryIntent(intent, resolvedType, 9975 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9976 } 9977 9978 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9979 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9980 if (!sUserManager.exists(userId)) return null; 9981 if (packageServices == null) { 9982 return null; 9983 } 9984 mFlags = flags; 9985 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9986 final int N = packageServices.size(); 9987 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9988 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9989 9990 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9991 for (int i = 0; i < N; ++i) { 9992 intentFilters = packageServices.get(i).intents; 9993 if (intentFilters != null && intentFilters.size() > 0) { 9994 PackageParser.ServiceIntentInfo[] array = 9995 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9996 intentFilters.toArray(array); 9997 listCut.add(array); 9998 } 9999 } 10000 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10001 } 10002 10003 public final void addService(PackageParser.Service s) { 10004 mServices.put(s.getComponentName(), s); 10005 if (DEBUG_SHOW_INFO) { 10006 Log.v(TAG, " " 10007 + (s.info.nonLocalizedLabel != null 10008 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10009 Log.v(TAG, " Class=" + s.info.name); 10010 } 10011 final int NI = s.intents.size(); 10012 int j; 10013 for (j=0; j<NI; j++) { 10014 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10015 if (DEBUG_SHOW_INFO) { 10016 Log.v(TAG, " IntentFilter:"); 10017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10018 } 10019 if (!intent.debugCheck()) { 10020 Log.w(TAG, "==> For Service " + s.info.name); 10021 } 10022 addFilter(intent); 10023 } 10024 } 10025 10026 public final void removeService(PackageParser.Service s) { 10027 mServices.remove(s.getComponentName()); 10028 if (DEBUG_SHOW_INFO) { 10029 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10030 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10031 Log.v(TAG, " Class=" + s.info.name); 10032 } 10033 final int NI = s.intents.size(); 10034 int j; 10035 for (j=0; j<NI; j++) { 10036 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10037 if (DEBUG_SHOW_INFO) { 10038 Log.v(TAG, " IntentFilter:"); 10039 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10040 } 10041 removeFilter(intent); 10042 } 10043 } 10044 10045 @Override 10046 protected boolean allowFilterResult( 10047 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10048 ServiceInfo filterSi = filter.service.info; 10049 for (int i=dest.size()-1; i>=0; i--) { 10050 ServiceInfo destAi = dest.get(i).serviceInfo; 10051 if (destAi.name == filterSi.name 10052 && destAi.packageName == filterSi.packageName) { 10053 return false; 10054 } 10055 } 10056 return true; 10057 } 10058 10059 @Override 10060 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10061 return new PackageParser.ServiceIntentInfo[size]; 10062 } 10063 10064 @Override 10065 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10066 if (!sUserManager.exists(userId)) return true; 10067 PackageParser.Package p = filter.service.owner; 10068 if (p != null) { 10069 PackageSetting ps = (PackageSetting)p.mExtras; 10070 if (ps != null) { 10071 // System apps are never considered stopped for purposes of 10072 // filtering, because there may be no way for the user to 10073 // actually re-launch them. 10074 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10075 && ps.getStopped(userId); 10076 } 10077 } 10078 return false; 10079 } 10080 10081 @Override 10082 protected boolean isPackageForFilter(String packageName, 10083 PackageParser.ServiceIntentInfo info) { 10084 return packageName.equals(info.service.owner.packageName); 10085 } 10086 10087 @Override 10088 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10089 int match, int userId) { 10090 if (!sUserManager.exists(userId)) return null; 10091 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10092 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10093 return null; 10094 } 10095 final PackageParser.Service service = info.service; 10096 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10097 if (ps == null) { 10098 return null; 10099 } 10100 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10101 ps.readUserState(userId), userId); 10102 if (si == null) { 10103 return null; 10104 } 10105 final ResolveInfo res = new ResolveInfo(); 10106 res.serviceInfo = si; 10107 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10108 res.filter = filter; 10109 } 10110 res.priority = info.getPriority(); 10111 res.preferredOrder = service.owner.mPreferredOrder; 10112 res.match = match; 10113 res.isDefault = info.hasDefault; 10114 res.labelRes = info.labelRes; 10115 res.nonLocalizedLabel = info.nonLocalizedLabel; 10116 res.icon = info.icon; 10117 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10118 return res; 10119 } 10120 10121 @Override 10122 protected void sortResults(List<ResolveInfo> results) { 10123 Collections.sort(results, mResolvePrioritySorter); 10124 } 10125 10126 @Override 10127 protected void dumpFilter(PrintWriter out, String prefix, 10128 PackageParser.ServiceIntentInfo filter) { 10129 out.print(prefix); out.print( 10130 Integer.toHexString(System.identityHashCode(filter.service))); 10131 out.print(' '); 10132 filter.service.printComponentShortName(out); 10133 out.print(" filter "); 10134 out.println(Integer.toHexString(System.identityHashCode(filter))); 10135 } 10136 10137 @Override 10138 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10139 return filter.service; 10140 } 10141 10142 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10143 PackageParser.Service service = (PackageParser.Service)label; 10144 out.print(prefix); out.print( 10145 Integer.toHexString(System.identityHashCode(service))); 10146 out.print(' '); 10147 service.printComponentShortName(out); 10148 if (count > 1) { 10149 out.print(" ("); out.print(count); out.print(" filters)"); 10150 } 10151 out.println(); 10152 } 10153 10154// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10155// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10156// final List<ResolveInfo> retList = Lists.newArrayList(); 10157// while (i.hasNext()) { 10158// final ResolveInfo resolveInfo = (ResolveInfo) i; 10159// if (isEnabledLP(resolveInfo.serviceInfo)) { 10160// retList.add(resolveInfo); 10161// } 10162// } 10163// return retList; 10164// } 10165 10166 // Keys are String (activity class name), values are Activity. 10167 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10168 = new ArrayMap<ComponentName, PackageParser.Service>(); 10169 private int mFlags; 10170 }; 10171 10172 private final class ProviderIntentResolver 10173 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10174 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10175 boolean defaultOnly, int userId) { 10176 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10177 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10178 } 10179 10180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10181 int userId) { 10182 if (!sUserManager.exists(userId)) 10183 return null; 10184 mFlags = flags; 10185 return super.queryIntent(intent, resolvedType, 10186 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10187 } 10188 10189 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10190 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10191 if (!sUserManager.exists(userId)) 10192 return null; 10193 if (packageProviders == null) { 10194 return null; 10195 } 10196 mFlags = flags; 10197 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10198 final int N = packageProviders.size(); 10199 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10200 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10201 10202 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10203 for (int i = 0; i < N; ++i) { 10204 intentFilters = packageProviders.get(i).intents; 10205 if (intentFilters != null && intentFilters.size() > 0) { 10206 PackageParser.ProviderIntentInfo[] array = 10207 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10208 intentFilters.toArray(array); 10209 listCut.add(array); 10210 } 10211 } 10212 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10213 } 10214 10215 public final void addProvider(PackageParser.Provider p) { 10216 if (mProviders.containsKey(p.getComponentName())) { 10217 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10218 return; 10219 } 10220 10221 mProviders.put(p.getComponentName(), p); 10222 if (DEBUG_SHOW_INFO) { 10223 Log.v(TAG, " " 10224 + (p.info.nonLocalizedLabel != null 10225 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10226 Log.v(TAG, " Class=" + p.info.name); 10227 } 10228 final int NI = p.intents.size(); 10229 int j; 10230 for (j = 0; j < NI; j++) { 10231 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10232 if (DEBUG_SHOW_INFO) { 10233 Log.v(TAG, " IntentFilter:"); 10234 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10235 } 10236 if (!intent.debugCheck()) { 10237 Log.w(TAG, "==> For Provider " + p.info.name); 10238 } 10239 addFilter(intent); 10240 } 10241 } 10242 10243 public final void removeProvider(PackageParser.Provider p) { 10244 mProviders.remove(p.getComponentName()); 10245 if (DEBUG_SHOW_INFO) { 10246 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10247 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10248 Log.v(TAG, " Class=" + p.info.name); 10249 } 10250 final int NI = p.intents.size(); 10251 int j; 10252 for (j = 0; j < NI; j++) { 10253 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10254 if (DEBUG_SHOW_INFO) { 10255 Log.v(TAG, " IntentFilter:"); 10256 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10257 } 10258 removeFilter(intent); 10259 } 10260 } 10261 10262 @Override 10263 protected boolean allowFilterResult( 10264 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10265 ProviderInfo filterPi = filter.provider.info; 10266 for (int i = dest.size() - 1; i >= 0; i--) { 10267 ProviderInfo destPi = dest.get(i).providerInfo; 10268 if (destPi.name == filterPi.name 10269 && destPi.packageName == filterPi.packageName) { 10270 return false; 10271 } 10272 } 10273 return true; 10274 } 10275 10276 @Override 10277 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10278 return new PackageParser.ProviderIntentInfo[size]; 10279 } 10280 10281 @Override 10282 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10283 if (!sUserManager.exists(userId)) 10284 return true; 10285 PackageParser.Package p = filter.provider.owner; 10286 if (p != null) { 10287 PackageSetting ps = (PackageSetting) p.mExtras; 10288 if (ps != null) { 10289 // System apps are never considered stopped for purposes of 10290 // filtering, because there may be no way for the user to 10291 // actually re-launch them. 10292 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10293 && ps.getStopped(userId); 10294 } 10295 } 10296 return false; 10297 } 10298 10299 @Override 10300 protected boolean isPackageForFilter(String packageName, 10301 PackageParser.ProviderIntentInfo info) { 10302 return packageName.equals(info.provider.owner.packageName); 10303 } 10304 10305 @Override 10306 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10307 int match, int userId) { 10308 if (!sUserManager.exists(userId)) 10309 return null; 10310 final PackageParser.ProviderIntentInfo info = filter; 10311 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10312 return null; 10313 } 10314 final PackageParser.Provider provider = info.provider; 10315 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10316 if (ps == null) { 10317 return null; 10318 } 10319 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10320 ps.readUserState(userId), userId); 10321 if (pi == null) { 10322 return null; 10323 } 10324 final ResolveInfo res = new ResolveInfo(); 10325 res.providerInfo = pi; 10326 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10327 res.filter = filter; 10328 } 10329 res.priority = info.getPriority(); 10330 res.preferredOrder = provider.owner.mPreferredOrder; 10331 res.match = match; 10332 res.isDefault = info.hasDefault; 10333 res.labelRes = info.labelRes; 10334 res.nonLocalizedLabel = info.nonLocalizedLabel; 10335 res.icon = info.icon; 10336 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10337 return res; 10338 } 10339 10340 @Override 10341 protected void sortResults(List<ResolveInfo> results) { 10342 Collections.sort(results, mResolvePrioritySorter); 10343 } 10344 10345 @Override 10346 protected void dumpFilter(PrintWriter out, String prefix, 10347 PackageParser.ProviderIntentInfo filter) { 10348 out.print(prefix); 10349 out.print( 10350 Integer.toHexString(System.identityHashCode(filter.provider))); 10351 out.print(' '); 10352 filter.provider.printComponentShortName(out); 10353 out.print(" filter "); 10354 out.println(Integer.toHexString(System.identityHashCode(filter))); 10355 } 10356 10357 @Override 10358 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10359 return filter.provider; 10360 } 10361 10362 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10363 PackageParser.Provider provider = (PackageParser.Provider)label; 10364 out.print(prefix); out.print( 10365 Integer.toHexString(System.identityHashCode(provider))); 10366 out.print(' '); 10367 provider.printComponentShortName(out); 10368 if (count > 1) { 10369 out.print(" ("); out.print(count); out.print(" filters)"); 10370 } 10371 out.println(); 10372 } 10373 10374 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10375 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10376 private int mFlags; 10377 } 10378 10379 private static final class EphemeralIntentResolver 10380 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10381 @Override 10382 protected EphemeralResolveIntentInfo[] newArray(int size) { 10383 return new EphemeralResolveIntentInfo[size]; 10384 } 10385 10386 @Override 10387 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10388 return true; 10389 } 10390 10391 @Override 10392 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10393 int userId) { 10394 if (!sUserManager.exists(userId)) { 10395 return null; 10396 } 10397 return info.getEphemeralResolveInfo(); 10398 } 10399 } 10400 10401 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10402 new Comparator<ResolveInfo>() { 10403 public int compare(ResolveInfo r1, ResolveInfo r2) { 10404 int v1 = r1.priority; 10405 int v2 = r2.priority; 10406 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10407 if (v1 != v2) { 10408 return (v1 > v2) ? -1 : 1; 10409 } 10410 v1 = r1.preferredOrder; 10411 v2 = r2.preferredOrder; 10412 if (v1 != v2) { 10413 return (v1 > v2) ? -1 : 1; 10414 } 10415 if (r1.isDefault != r2.isDefault) { 10416 return r1.isDefault ? -1 : 1; 10417 } 10418 v1 = r1.match; 10419 v2 = r2.match; 10420 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10421 if (v1 != v2) { 10422 return (v1 > v2) ? -1 : 1; 10423 } 10424 if (r1.system != r2.system) { 10425 return r1.system ? -1 : 1; 10426 } 10427 if (r1.activityInfo != null) { 10428 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10429 } 10430 if (r1.serviceInfo != null) { 10431 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10432 } 10433 if (r1.providerInfo != null) { 10434 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10435 } 10436 return 0; 10437 } 10438 }; 10439 10440 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10441 new Comparator<ProviderInfo>() { 10442 public int compare(ProviderInfo p1, ProviderInfo p2) { 10443 final int v1 = p1.initOrder; 10444 final int v2 = p2.initOrder; 10445 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10446 } 10447 }; 10448 10449 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10450 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10451 final int[] userIds) { 10452 mHandler.post(new Runnable() { 10453 @Override 10454 public void run() { 10455 try { 10456 final IActivityManager am = ActivityManagerNative.getDefault(); 10457 if (am == null) return; 10458 final int[] resolvedUserIds; 10459 if (userIds == null) { 10460 resolvedUserIds = am.getRunningUserIds(); 10461 } else { 10462 resolvedUserIds = userIds; 10463 } 10464 for (int id : resolvedUserIds) { 10465 final Intent intent = new Intent(action, 10466 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10467 if (extras != null) { 10468 intent.putExtras(extras); 10469 } 10470 if (targetPkg != null) { 10471 intent.setPackage(targetPkg); 10472 } 10473 // Modify the UID when posting to other users 10474 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10475 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10476 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10477 intent.putExtra(Intent.EXTRA_UID, uid); 10478 } 10479 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10480 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10481 if (DEBUG_BROADCASTS) { 10482 RuntimeException here = new RuntimeException("here"); 10483 here.fillInStackTrace(); 10484 Slog.d(TAG, "Sending to user " + id + ": " 10485 + intent.toShortString(false, true, false, false) 10486 + " " + intent.getExtras(), here); 10487 } 10488 am.broadcastIntent(null, intent, null, finishedReceiver, 10489 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10490 null, finishedReceiver != null, false, id); 10491 } 10492 } catch (RemoteException ex) { 10493 } 10494 } 10495 }); 10496 } 10497 10498 /** 10499 * Check if the external storage media is available. This is true if there 10500 * is a mounted external storage medium or if the external storage is 10501 * emulated. 10502 */ 10503 private boolean isExternalMediaAvailable() { 10504 return mMediaMounted || Environment.isExternalStorageEmulated(); 10505 } 10506 10507 @Override 10508 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10509 // writer 10510 synchronized (mPackages) { 10511 if (!isExternalMediaAvailable()) { 10512 // If the external storage is no longer mounted at this point, 10513 // the caller may not have been able to delete all of this 10514 // packages files and can not delete any more. Bail. 10515 return null; 10516 } 10517 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10518 if (lastPackage != null) { 10519 pkgs.remove(lastPackage); 10520 } 10521 if (pkgs.size() > 0) { 10522 return pkgs.get(0); 10523 } 10524 } 10525 return null; 10526 } 10527 10528 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10529 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10530 userId, andCode ? 1 : 0, packageName); 10531 if (mSystemReady) { 10532 msg.sendToTarget(); 10533 } else { 10534 if (mPostSystemReadyMessages == null) { 10535 mPostSystemReadyMessages = new ArrayList<>(); 10536 } 10537 mPostSystemReadyMessages.add(msg); 10538 } 10539 } 10540 10541 void startCleaningPackages() { 10542 // reader 10543 if (!isExternalMediaAvailable()) { 10544 return; 10545 } 10546 synchronized (mPackages) { 10547 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10548 return; 10549 } 10550 } 10551 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10552 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10553 IActivityManager am = ActivityManagerNative.getDefault(); 10554 if (am != null) { 10555 try { 10556 am.startService(null, intent, null, mContext.getOpPackageName(), 10557 UserHandle.USER_SYSTEM); 10558 } catch (RemoteException e) { 10559 } 10560 } 10561 } 10562 10563 @Override 10564 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10565 int installFlags, String installerPackageName, int userId) { 10566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10567 10568 final int callingUid = Binder.getCallingUid(); 10569 enforceCrossUserPermission(callingUid, userId, 10570 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10571 10572 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10573 try { 10574 if (observer != null) { 10575 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10576 } 10577 } catch (RemoteException re) { 10578 } 10579 return; 10580 } 10581 10582 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10583 installFlags |= PackageManager.INSTALL_FROM_ADB; 10584 10585 } else { 10586 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10587 // about installerPackageName. 10588 10589 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10590 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10591 } 10592 10593 UserHandle user; 10594 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10595 user = UserHandle.ALL; 10596 } else { 10597 user = new UserHandle(userId); 10598 } 10599 10600 // Only system components can circumvent runtime permissions when installing. 10601 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10602 && mContext.checkCallingOrSelfPermission(Manifest.permission 10603 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10604 throw new SecurityException("You need the " 10605 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10606 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10607 } 10608 10609 final File originFile = new File(originPath); 10610 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10611 10612 final Message msg = mHandler.obtainMessage(INIT_COPY); 10613 final VerificationInfo verificationInfo = new VerificationInfo( 10614 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10615 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10616 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10617 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10618 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10619 msg.obj = params; 10620 10621 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10622 System.identityHashCode(msg.obj)); 10623 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10624 System.identityHashCode(msg.obj)); 10625 10626 mHandler.sendMessage(msg); 10627 } 10628 10629 void installStage(String packageName, File stagedDir, String stagedCid, 10630 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10631 String installerPackageName, int installerUid, UserHandle user) { 10632 if (DEBUG_EPHEMERAL) { 10633 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10634 Slog.d(TAG, "Ephemeral install of " + packageName); 10635 } 10636 } 10637 final VerificationInfo verificationInfo = new VerificationInfo( 10638 sessionParams.originatingUri, sessionParams.referrerUri, 10639 sessionParams.originatingUid, installerUid); 10640 10641 final OriginInfo origin; 10642 if (stagedDir != null) { 10643 origin = OriginInfo.fromStagedFile(stagedDir); 10644 } else { 10645 origin = OriginInfo.fromStagedContainer(stagedCid); 10646 } 10647 10648 final Message msg = mHandler.obtainMessage(INIT_COPY); 10649 final InstallParams params = new InstallParams(origin, null, observer, 10650 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10651 verificationInfo, user, sessionParams.abiOverride, 10652 sessionParams.grantedRuntimePermissions); 10653 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10654 msg.obj = params; 10655 10656 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10657 System.identityHashCode(msg.obj)); 10658 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10659 System.identityHashCode(msg.obj)); 10660 10661 mHandler.sendMessage(msg); 10662 } 10663 10664 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10665 int userId) { 10666 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10667 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10668 } 10669 10670 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10671 int appId, int userId) { 10672 Bundle extras = new Bundle(1); 10673 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10674 10675 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10676 packageName, extras, 0, null, null, new int[] {userId}); 10677 try { 10678 IActivityManager am = ActivityManagerNative.getDefault(); 10679 if (isSystem && am.isUserRunning(userId, 0)) { 10680 // The just-installed/enabled app is bundled on the system, so presumed 10681 // to be able to run automatically without needing an explicit launch. 10682 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10683 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10684 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10685 .setPackage(packageName); 10686 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10687 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10688 } 10689 } catch (RemoteException e) { 10690 // shouldn't happen 10691 Slog.w(TAG, "Unable to bootstrap installed package", e); 10692 } 10693 } 10694 10695 @Override 10696 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10697 int userId) { 10698 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10699 PackageSetting pkgSetting; 10700 final int uid = Binder.getCallingUid(); 10701 enforceCrossUserPermission(uid, userId, 10702 true /* requireFullPermission */, true /* checkShell */, 10703 "setApplicationHiddenSetting for user " + userId); 10704 10705 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10706 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10707 return false; 10708 } 10709 10710 long callingId = Binder.clearCallingIdentity(); 10711 try { 10712 boolean sendAdded = false; 10713 boolean sendRemoved = false; 10714 // writer 10715 synchronized (mPackages) { 10716 pkgSetting = mSettings.mPackages.get(packageName); 10717 if (pkgSetting == null) { 10718 return false; 10719 } 10720 if (pkgSetting.getHidden(userId) != hidden) { 10721 pkgSetting.setHidden(hidden, userId); 10722 mSettings.writePackageRestrictionsLPr(userId); 10723 if (hidden) { 10724 sendRemoved = true; 10725 } else { 10726 sendAdded = true; 10727 } 10728 } 10729 } 10730 if (sendAdded) { 10731 sendPackageAddedForUser(packageName, pkgSetting, userId); 10732 return true; 10733 } 10734 if (sendRemoved) { 10735 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10736 "hiding pkg"); 10737 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10738 return true; 10739 } 10740 } finally { 10741 Binder.restoreCallingIdentity(callingId); 10742 } 10743 return false; 10744 } 10745 10746 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10747 int userId) { 10748 final PackageRemovedInfo info = new PackageRemovedInfo(); 10749 info.removedPackage = packageName; 10750 info.removedUsers = new int[] {userId}; 10751 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10752 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10753 } 10754 10755 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10756 if (pkgList.length > 0) { 10757 Bundle extras = new Bundle(1); 10758 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10759 10760 sendPackageBroadcast( 10761 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10762 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10763 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10764 new int[] {userId}); 10765 } 10766 } 10767 10768 /** 10769 * Returns true if application is not found or there was an error. Otherwise it returns 10770 * the hidden state of the package for the given user. 10771 */ 10772 @Override 10773 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10775 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10776 true /* requireFullPermission */, false /* checkShell */, 10777 "getApplicationHidden for user " + userId); 10778 PackageSetting pkgSetting; 10779 long callingId = Binder.clearCallingIdentity(); 10780 try { 10781 // writer 10782 synchronized (mPackages) { 10783 pkgSetting = mSettings.mPackages.get(packageName); 10784 if (pkgSetting == null) { 10785 return true; 10786 } 10787 return pkgSetting.getHidden(userId); 10788 } 10789 } finally { 10790 Binder.restoreCallingIdentity(callingId); 10791 } 10792 } 10793 10794 /** 10795 * @hide 10796 */ 10797 @Override 10798 public int installExistingPackageAsUser(String packageName, int userId) { 10799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10800 null); 10801 PackageSetting pkgSetting; 10802 final int uid = Binder.getCallingUid(); 10803 enforceCrossUserPermission(uid, userId, 10804 true /* requireFullPermission */, true /* checkShell */, 10805 "installExistingPackage for user " + userId); 10806 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10807 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10808 } 10809 10810 long callingId = Binder.clearCallingIdentity(); 10811 try { 10812 boolean installed = false; 10813 10814 // writer 10815 synchronized (mPackages) { 10816 pkgSetting = mSettings.mPackages.get(packageName); 10817 if (pkgSetting == null) { 10818 return PackageManager.INSTALL_FAILED_INVALID_URI; 10819 } 10820 if (!pkgSetting.getInstalled(userId)) { 10821 pkgSetting.setInstalled(true, userId); 10822 pkgSetting.setHidden(false, userId); 10823 mSettings.writePackageRestrictionsLPr(userId); 10824 installed = true; 10825 } 10826 } 10827 10828 if (installed) { 10829 if (pkgSetting.pkg != null) { 10830 prepareAppDataAfterInstall(pkgSetting.pkg); 10831 } 10832 sendPackageAddedForUser(packageName, pkgSetting, userId); 10833 } 10834 } finally { 10835 Binder.restoreCallingIdentity(callingId); 10836 } 10837 10838 return PackageManager.INSTALL_SUCCEEDED; 10839 } 10840 10841 boolean isUserRestricted(int userId, String restrictionKey) { 10842 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10843 if (restrictions.getBoolean(restrictionKey, false)) { 10844 Log.w(TAG, "User is restricted: " + restrictionKey); 10845 return true; 10846 } 10847 return false; 10848 } 10849 10850 @Override 10851 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10852 int userId) { 10853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10854 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10855 true /* requireFullPermission */, true /* checkShell */, 10856 "setPackagesSuspended for user " + userId); 10857 10858 if (ArrayUtils.isEmpty(packageNames)) { 10859 return packageNames; 10860 } 10861 10862 // List of package names for whom the suspended state has changed. 10863 List<String> changedPackages = new ArrayList<>(packageNames.length); 10864 // List of package names for whom the suspended state is not set as requested in this 10865 // method. 10866 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10867 for (int i = 0; i < packageNames.length; i++) { 10868 String packageName = packageNames[i]; 10869 long callingId = Binder.clearCallingIdentity(); 10870 try { 10871 boolean changed = false; 10872 final int appId; 10873 synchronized (mPackages) { 10874 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10875 if (pkgSetting == null) { 10876 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10877 + "\". Skipping suspending/un-suspending."); 10878 unactionedPackages.add(packageName); 10879 continue; 10880 } 10881 appId = pkgSetting.appId; 10882 if (pkgSetting.getSuspended(userId) != suspended) { 10883 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10884 unactionedPackages.add(packageName); 10885 continue; 10886 } 10887 pkgSetting.setSuspended(suspended, userId); 10888 mSettings.writePackageRestrictionsLPr(userId); 10889 changed = true; 10890 changedPackages.add(packageName); 10891 } 10892 } 10893 10894 if (changed && suspended) { 10895 killApplication(packageName, UserHandle.getUid(userId, appId), 10896 "suspending package"); 10897 } 10898 } finally { 10899 Binder.restoreCallingIdentity(callingId); 10900 } 10901 } 10902 10903 if (!changedPackages.isEmpty()) { 10904 sendPackagesSuspendedForUser(changedPackages.toArray( 10905 new String[changedPackages.size()]), userId, suspended); 10906 } 10907 10908 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10909 } 10910 10911 @Override 10912 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10913 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10914 true /* requireFullPermission */, false /* checkShell */, 10915 "isPackageSuspendedForUser for user " + userId); 10916 synchronized (mPackages) { 10917 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10918 return pkgSetting != null && pkgSetting.getSuspended(userId); 10919 } 10920 } 10921 10922 /** 10923 * TODO: cache and disallow blocking the active dialer. 10924 * 10925 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10926 */ 10927 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10928 if (isPackageDeviceAdmin(packageName, userId)) { 10929 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10930 + "\": has an active device admin"); 10931 return false; 10932 } 10933 10934 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10935 if (packageName.equals(activeLauncherPackageName)) { 10936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10937 + "\": contains the active launcher"); 10938 return false; 10939 } 10940 10941 if (packageName.equals(mRequiredInstallerPackage)) { 10942 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10943 + "\": required for package installation"); 10944 return false; 10945 } 10946 10947 if (packageName.equals(mRequiredVerifierPackage)) { 10948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10949 + "\": required for package verification"); 10950 return false; 10951 } 10952 10953 final PackageParser.Package pkg = mPackages.get(packageName); 10954 if (pkg != null && isPrivilegedApp(pkg)) { 10955 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10956 + "\": is a privileged app"); 10957 return false; 10958 } 10959 10960 return true; 10961 } 10962 10963 private String getActiveLauncherPackageName(int userId) { 10964 Intent intent = new Intent(Intent.ACTION_MAIN); 10965 intent.addCategory(Intent.CATEGORY_HOME); 10966 ResolveInfo resolveInfo = resolveIntent( 10967 intent, 10968 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10969 PackageManager.MATCH_DEFAULT_ONLY, 10970 userId); 10971 10972 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10973 } 10974 10975 @Override 10976 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10977 mContext.enforceCallingOrSelfPermission( 10978 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10979 "Only package verification agents can verify applications"); 10980 10981 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10982 final PackageVerificationResponse response = new PackageVerificationResponse( 10983 verificationCode, Binder.getCallingUid()); 10984 msg.arg1 = id; 10985 msg.obj = response; 10986 mHandler.sendMessage(msg); 10987 } 10988 10989 @Override 10990 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10991 long millisecondsToDelay) { 10992 mContext.enforceCallingOrSelfPermission( 10993 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10994 "Only package verification agents can extend verification timeouts"); 10995 10996 final PackageVerificationState state = mPendingVerification.get(id); 10997 final PackageVerificationResponse response = new PackageVerificationResponse( 10998 verificationCodeAtTimeout, Binder.getCallingUid()); 10999 11000 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11001 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11002 } 11003 if (millisecondsToDelay < 0) { 11004 millisecondsToDelay = 0; 11005 } 11006 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11007 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11008 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11009 } 11010 11011 if ((state != null) && !state.timeoutExtended()) { 11012 state.extendTimeout(); 11013 11014 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11015 msg.arg1 = id; 11016 msg.obj = response; 11017 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11018 } 11019 } 11020 11021 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11022 int verificationCode, UserHandle user) { 11023 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11024 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11025 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11026 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11027 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11028 11029 mContext.sendBroadcastAsUser(intent, user, 11030 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11031 } 11032 11033 private ComponentName matchComponentForVerifier(String packageName, 11034 List<ResolveInfo> receivers) { 11035 ActivityInfo targetReceiver = null; 11036 11037 final int NR = receivers.size(); 11038 for (int i = 0; i < NR; i++) { 11039 final ResolveInfo info = receivers.get(i); 11040 if (info.activityInfo == null) { 11041 continue; 11042 } 11043 11044 if (packageName.equals(info.activityInfo.packageName)) { 11045 targetReceiver = info.activityInfo; 11046 break; 11047 } 11048 } 11049 11050 if (targetReceiver == null) { 11051 return null; 11052 } 11053 11054 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11055 } 11056 11057 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11058 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11059 if (pkgInfo.verifiers.length == 0) { 11060 return null; 11061 } 11062 11063 final int N = pkgInfo.verifiers.length; 11064 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11065 for (int i = 0; i < N; i++) { 11066 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11067 11068 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11069 receivers); 11070 if (comp == null) { 11071 continue; 11072 } 11073 11074 final int verifierUid = getUidForVerifier(verifierInfo); 11075 if (verifierUid == -1) { 11076 continue; 11077 } 11078 11079 if (DEBUG_VERIFY) { 11080 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11081 + " with the correct signature"); 11082 } 11083 sufficientVerifiers.add(comp); 11084 verificationState.addSufficientVerifier(verifierUid); 11085 } 11086 11087 return sufficientVerifiers; 11088 } 11089 11090 private int getUidForVerifier(VerifierInfo verifierInfo) { 11091 synchronized (mPackages) { 11092 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11093 if (pkg == null) { 11094 return -1; 11095 } else if (pkg.mSignatures.length != 1) { 11096 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11097 + " has more than one signature; ignoring"); 11098 return -1; 11099 } 11100 11101 /* 11102 * If the public key of the package's signature does not match 11103 * our expected public key, then this is a different package and 11104 * we should skip. 11105 */ 11106 11107 final byte[] expectedPublicKey; 11108 try { 11109 final Signature verifierSig = pkg.mSignatures[0]; 11110 final PublicKey publicKey = verifierSig.getPublicKey(); 11111 expectedPublicKey = publicKey.getEncoded(); 11112 } catch (CertificateException e) { 11113 return -1; 11114 } 11115 11116 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11117 11118 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11119 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11120 + " does not have the expected public key; ignoring"); 11121 return -1; 11122 } 11123 11124 return pkg.applicationInfo.uid; 11125 } 11126 } 11127 11128 @Override 11129 public void finishPackageInstall(int token) { 11130 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11131 11132 if (DEBUG_INSTALL) { 11133 Slog.v(TAG, "BM finishing package install for " + token); 11134 } 11135 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11136 11137 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11138 mHandler.sendMessage(msg); 11139 } 11140 11141 /** 11142 * Get the verification agent timeout. 11143 * 11144 * @return verification timeout in milliseconds 11145 */ 11146 private long getVerificationTimeout() { 11147 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11148 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11149 DEFAULT_VERIFICATION_TIMEOUT); 11150 } 11151 11152 /** 11153 * Get the default verification agent response code. 11154 * 11155 * @return default verification response code 11156 */ 11157 private int getDefaultVerificationResponse() { 11158 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11159 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11160 DEFAULT_VERIFICATION_RESPONSE); 11161 } 11162 11163 /** 11164 * Check whether or not package verification has been enabled. 11165 * 11166 * @return true if verification should be performed 11167 */ 11168 private boolean isVerificationEnabled(int userId, int installFlags) { 11169 if (!DEFAULT_VERIFY_ENABLE) { 11170 return false; 11171 } 11172 // Ephemeral apps don't get the full verification treatment 11173 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11174 if (DEBUG_EPHEMERAL) { 11175 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11176 } 11177 return false; 11178 } 11179 11180 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11181 11182 // Check if installing from ADB 11183 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11184 // Do not run verification in a test harness environment 11185 if (ActivityManager.isRunningInTestHarness()) { 11186 return false; 11187 } 11188 if (ensureVerifyAppsEnabled) { 11189 return true; 11190 } 11191 // Check if the developer does not want package verification for ADB installs 11192 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11193 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11194 return false; 11195 } 11196 } 11197 11198 if (ensureVerifyAppsEnabled) { 11199 return true; 11200 } 11201 11202 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11203 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11204 } 11205 11206 @Override 11207 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11208 throws RemoteException { 11209 mContext.enforceCallingOrSelfPermission( 11210 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11211 "Only intentfilter verification agents can verify applications"); 11212 11213 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11214 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11215 Binder.getCallingUid(), verificationCode, failedDomains); 11216 msg.arg1 = id; 11217 msg.obj = response; 11218 mHandler.sendMessage(msg); 11219 } 11220 11221 @Override 11222 public int getIntentVerificationStatus(String packageName, int userId) { 11223 synchronized (mPackages) { 11224 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11225 } 11226 } 11227 11228 @Override 11229 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11230 mContext.enforceCallingOrSelfPermission( 11231 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11232 11233 boolean result = false; 11234 synchronized (mPackages) { 11235 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11236 } 11237 if (result) { 11238 scheduleWritePackageRestrictionsLocked(userId); 11239 } 11240 return result; 11241 } 11242 11243 @Override 11244 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11245 String packageName) { 11246 synchronized (mPackages) { 11247 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11248 } 11249 } 11250 11251 @Override 11252 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11253 if (TextUtils.isEmpty(packageName)) { 11254 return ParceledListSlice.emptyList(); 11255 } 11256 synchronized (mPackages) { 11257 PackageParser.Package pkg = mPackages.get(packageName); 11258 if (pkg == null || pkg.activities == null) { 11259 return ParceledListSlice.emptyList(); 11260 } 11261 final int count = pkg.activities.size(); 11262 ArrayList<IntentFilter> result = new ArrayList<>(); 11263 for (int n=0; n<count; n++) { 11264 PackageParser.Activity activity = pkg.activities.get(n); 11265 if (activity.intents != null && activity.intents.size() > 0) { 11266 result.addAll(activity.intents); 11267 } 11268 } 11269 return new ParceledListSlice<>(result); 11270 } 11271 } 11272 11273 @Override 11274 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11275 mContext.enforceCallingOrSelfPermission( 11276 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11277 11278 synchronized (mPackages) { 11279 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11280 if (packageName != null) { 11281 result |= updateIntentVerificationStatus(packageName, 11282 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11283 userId); 11284 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11285 packageName, userId); 11286 } 11287 return result; 11288 } 11289 } 11290 11291 @Override 11292 public String getDefaultBrowserPackageName(int userId) { 11293 synchronized (mPackages) { 11294 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11295 } 11296 } 11297 11298 /** 11299 * Get the "allow unknown sources" setting. 11300 * 11301 * @return the current "allow unknown sources" setting 11302 */ 11303 private int getUnknownSourcesSettings() { 11304 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11305 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11306 -1); 11307 } 11308 11309 @Override 11310 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11311 final int uid = Binder.getCallingUid(); 11312 // writer 11313 synchronized (mPackages) { 11314 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11315 if (targetPackageSetting == null) { 11316 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11317 } 11318 11319 PackageSetting installerPackageSetting; 11320 if (installerPackageName != null) { 11321 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11322 if (installerPackageSetting == null) { 11323 throw new IllegalArgumentException("Unknown installer package: " 11324 + installerPackageName); 11325 } 11326 } else { 11327 installerPackageSetting = null; 11328 } 11329 11330 Signature[] callerSignature; 11331 Object obj = mSettings.getUserIdLPr(uid); 11332 if (obj != null) { 11333 if (obj instanceof SharedUserSetting) { 11334 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11335 } else if (obj instanceof PackageSetting) { 11336 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11337 } else { 11338 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11339 } 11340 } else { 11341 throw new SecurityException("Unknown calling UID: " + uid); 11342 } 11343 11344 // Verify: can't set installerPackageName to a package that is 11345 // not signed with the same cert as the caller. 11346 if (installerPackageSetting != null) { 11347 if (compareSignatures(callerSignature, 11348 installerPackageSetting.signatures.mSignatures) 11349 != PackageManager.SIGNATURE_MATCH) { 11350 throw new SecurityException( 11351 "Caller does not have same cert as new installer package " 11352 + installerPackageName); 11353 } 11354 } 11355 11356 // Verify: if target already has an installer package, it must 11357 // be signed with the same cert as the caller. 11358 if (targetPackageSetting.installerPackageName != null) { 11359 PackageSetting setting = mSettings.mPackages.get( 11360 targetPackageSetting.installerPackageName); 11361 // If the currently set package isn't valid, then it's always 11362 // okay to change it. 11363 if (setting != null) { 11364 if (compareSignatures(callerSignature, 11365 setting.signatures.mSignatures) 11366 != PackageManager.SIGNATURE_MATCH) { 11367 throw new SecurityException( 11368 "Caller does not have same cert as old installer package " 11369 + targetPackageSetting.installerPackageName); 11370 } 11371 } 11372 } 11373 11374 // Okay! 11375 targetPackageSetting.installerPackageName = installerPackageName; 11376 scheduleWriteSettingsLocked(); 11377 } 11378 } 11379 11380 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11381 // Queue up an async operation since the package installation may take a little while. 11382 mHandler.post(new Runnable() { 11383 public void run() { 11384 mHandler.removeCallbacks(this); 11385 // Result object to be returned 11386 PackageInstalledInfo res = new PackageInstalledInfo(); 11387 res.setReturnCode(currentStatus); 11388 res.uid = -1; 11389 res.pkg = null; 11390 res.removedInfo = null; 11391 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11392 args.doPreInstall(res.returnCode); 11393 synchronized (mInstallLock) { 11394 installPackageTracedLI(args, res); 11395 } 11396 args.doPostInstall(res.returnCode, res.uid); 11397 } 11398 11399 // A restore should be performed at this point if (a) the install 11400 // succeeded, (b) the operation is not an update, and (c) the new 11401 // package has not opted out of backup participation. 11402 final boolean update = res.removedInfo != null 11403 && res.removedInfo.removedPackage != null; 11404 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11405 boolean doRestore = !update 11406 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11407 11408 // Set up the post-install work request bookkeeping. This will be used 11409 // and cleaned up by the post-install event handling regardless of whether 11410 // there's a restore pass performed. Token values are >= 1. 11411 int token; 11412 if (mNextInstallToken < 0) mNextInstallToken = 1; 11413 token = mNextInstallToken++; 11414 11415 PostInstallData data = new PostInstallData(args, res); 11416 mRunningInstalls.put(token, data); 11417 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11418 11419 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11420 // Pass responsibility to the Backup Manager. It will perform a 11421 // restore if appropriate, then pass responsibility back to the 11422 // Package Manager to run the post-install observer callbacks 11423 // and broadcasts. 11424 IBackupManager bm = IBackupManager.Stub.asInterface( 11425 ServiceManager.getService(Context.BACKUP_SERVICE)); 11426 if (bm != null) { 11427 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11428 + " to BM for possible restore"); 11429 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11430 try { 11431 // TODO: http://b/22388012 11432 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11433 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11434 } else { 11435 doRestore = false; 11436 } 11437 } catch (RemoteException e) { 11438 // can't happen; the backup manager is local 11439 } catch (Exception e) { 11440 Slog.e(TAG, "Exception trying to enqueue restore", e); 11441 doRestore = false; 11442 } 11443 } else { 11444 Slog.e(TAG, "Backup Manager not found!"); 11445 doRestore = false; 11446 } 11447 } 11448 11449 if (!doRestore) { 11450 // No restore possible, or the Backup Manager was mysteriously not 11451 // available -- just fire the post-install work request directly. 11452 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11453 11454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11455 11456 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11457 mHandler.sendMessage(msg); 11458 } 11459 } 11460 }); 11461 } 11462 11463 private abstract class HandlerParams { 11464 private static final int MAX_RETRIES = 4; 11465 11466 /** 11467 * Number of times startCopy() has been attempted and had a non-fatal 11468 * error. 11469 */ 11470 private int mRetries = 0; 11471 11472 /** User handle for the user requesting the information or installation. */ 11473 private final UserHandle mUser; 11474 String traceMethod; 11475 int traceCookie; 11476 11477 HandlerParams(UserHandle user) { 11478 mUser = user; 11479 } 11480 11481 UserHandle getUser() { 11482 return mUser; 11483 } 11484 11485 HandlerParams setTraceMethod(String traceMethod) { 11486 this.traceMethod = traceMethod; 11487 return this; 11488 } 11489 11490 HandlerParams setTraceCookie(int traceCookie) { 11491 this.traceCookie = traceCookie; 11492 return this; 11493 } 11494 11495 final boolean startCopy() { 11496 boolean res; 11497 try { 11498 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11499 11500 if (++mRetries > MAX_RETRIES) { 11501 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11502 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11503 handleServiceError(); 11504 return false; 11505 } else { 11506 handleStartCopy(); 11507 res = true; 11508 } 11509 } catch (RemoteException e) { 11510 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11511 mHandler.sendEmptyMessage(MCS_RECONNECT); 11512 res = false; 11513 } 11514 handleReturnCode(); 11515 return res; 11516 } 11517 11518 final void serviceError() { 11519 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11520 handleServiceError(); 11521 handleReturnCode(); 11522 } 11523 11524 abstract void handleStartCopy() throws RemoteException; 11525 abstract void handleServiceError(); 11526 abstract void handleReturnCode(); 11527 } 11528 11529 class MeasureParams extends HandlerParams { 11530 private final PackageStats mStats; 11531 private boolean mSuccess; 11532 11533 private final IPackageStatsObserver mObserver; 11534 11535 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11536 super(new UserHandle(stats.userHandle)); 11537 mObserver = observer; 11538 mStats = stats; 11539 } 11540 11541 @Override 11542 public String toString() { 11543 return "MeasureParams{" 11544 + Integer.toHexString(System.identityHashCode(this)) 11545 + " " + mStats.packageName + "}"; 11546 } 11547 11548 @Override 11549 void handleStartCopy() throws RemoteException { 11550 synchronized (mInstallLock) { 11551 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11552 } 11553 11554 if (mSuccess) { 11555 final boolean mounted; 11556 if (Environment.isExternalStorageEmulated()) { 11557 mounted = true; 11558 } else { 11559 final String status = Environment.getExternalStorageState(); 11560 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11561 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11562 } 11563 11564 if (mounted) { 11565 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11566 11567 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11568 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11569 11570 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11571 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11572 11573 // Always subtract cache size, since it's a subdirectory 11574 mStats.externalDataSize -= mStats.externalCacheSize; 11575 11576 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11577 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11578 11579 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11580 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11581 } 11582 } 11583 } 11584 11585 @Override 11586 void handleReturnCode() { 11587 if (mObserver != null) { 11588 try { 11589 mObserver.onGetStatsCompleted(mStats, mSuccess); 11590 } catch (RemoteException e) { 11591 Slog.i(TAG, "Observer no longer exists."); 11592 } 11593 } 11594 } 11595 11596 @Override 11597 void handleServiceError() { 11598 Slog.e(TAG, "Could not measure application " + mStats.packageName 11599 + " external storage"); 11600 } 11601 } 11602 11603 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11604 throws RemoteException { 11605 long result = 0; 11606 for (File path : paths) { 11607 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11608 } 11609 return result; 11610 } 11611 11612 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11613 for (File path : paths) { 11614 try { 11615 mcs.clearDirectory(path.getAbsolutePath()); 11616 } catch (RemoteException e) { 11617 } 11618 } 11619 } 11620 11621 static class OriginInfo { 11622 /** 11623 * Location where install is coming from, before it has been 11624 * copied/renamed into place. This could be a single monolithic APK 11625 * file, or a cluster directory. This location may be untrusted. 11626 */ 11627 final File file; 11628 final String cid; 11629 11630 /** 11631 * Flag indicating that {@link #file} or {@link #cid} has already been 11632 * staged, meaning downstream users don't need to defensively copy the 11633 * contents. 11634 */ 11635 final boolean staged; 11636 11637 /** 11638 * Flag indicating that {@link #file} or {@link #cid} is an already 11639 * installed app that is being moved. 11640 */ 11641 final boolean existing; 11642 11643 final String resolvedPath; 11644 final File resolvedFile; 11645 11646 static OriginInfo fromNothing() { 11647 return new OriginInfo(null, null, false, false); 11648 } 11649 11650 static OriginInfo fromUntrustedFile(File file) { 11651 return new OriginInfo(file, null, false, false); 11652 } 11653 11654 static OriginInfo fromExistingFile(File file) { 11655 return new OriginInfo(file, null, false, true); 11656 } 11657 11658 static OriginInfo fromStagedFile(File file) { 11659 return new OriginInfo(file, null, true, false); 11660 } 11661 11662 static OriginInfo fromStagedContainer(String cid) { 11663 return new OriginInfo(null, cid, true, false); 11664 } 11665 11666 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11667 this.file = file; 11668 this.cid = cid; 11669 this.staged = staged; 11670 this.existing = existing; 11671 11672 if (cid != null) { 11673 resolvedPath = PackageHelper.getSdDir(cid); 11674 resolvedFile = new File(resolvedPath); 11675 } else if (file != null) { 11676 resolvedPath = file.getAbsolutePath(); 11677 resolvedFile = file; 11678 } else { 11679 resolvedPath = null; 11680 resolvedFile = null; 11681 } 11682 } 11683 } 11684 11685 static class MoveInfo { 11686 final int moveId; 11687 final String fromUuid; 11688 final String toUuid; 11689 final String packageName; 11690 final String dataAppName; 11691 final int appId; 11692 final String seinfo; 11693 final int targetSdkVersion; 11694 11695 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11696 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11697 this.moveId = moveId; 11698 this.fromUuid = fromUuid; 11699 this.toUuid = toUuid; 11700 this.packageName = packageName; 11701 this.dataAppName = dataAppName; 11702 this.appId = appId; 11703 this.seinfo = seinfo; 11704 this.targetSdkVersion = targetSdkVersion; 11705 } 11706 } 11707 11708 static class VerificationInfo { 11709 /** A constant used to indicate that a uid value is not present. */ 11710 public static final int NO_UID = -1; 11711 11712 /** URI referencing where the package was downloaded from. */ 11713 final Uri originatingUri; 11714 11715 /** HTTP referrer URI associated with the originatingURI. */ 11716 final Uri referrer; 11717 11718 /** UID of the application that the install request originated from. */ 11719 final int originatingUid; 11720 11721 /** UID of application requesting the install */ 11722 final int installerUid; 11723 11724 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11725 this.originatingUri = originatingUri; 11726 this.referrer = referrer; 11727 this.originatingUid = originatingUid; 11728 this.installerUid = installerUid; 11729 } 11730 } 11731 11732 class InstallParams extends HandlerParams { 11733 final OriginInfo origin; 11734 final MoveInfo move; 11735 final IPackageInstallObserver2 observer; 11736 int installFlags; 11737 final String installerPackageName; 11738 final String volumeUuid; 11739 private InstallArgs mArgs; 11740 private int mRet; 11741 final String packageAbiOverride; 11742 final String[] grantedRuntimePermissions; 11743 final VerificationInfo verificationInfo; 11744 11745 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11746 int installFlags, String installerPackageName, String volumeUuid, 11747 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11748 String[] grantedPermissions) { 11749 super(user); 11750 this.origin = origin; 11751 this.move = move; 11752 this.observer = observer; 11753 this.installFlags = installFlags; 11754 this.installerPackageName = installerPackageName; 11755 this.volumeUuid = volumeUuid; 11756 this.verificationInfo = verificationInfo; 11757 this.packageAbiOverride = packageAbiOverride; 11758 this.grantedRuntimePermissions = grantedPermissions; 11759 } 11760 11761 @Override 11762 public String toString() { 11763 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11764 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11765 } 11766 11767 private int installLocationPolicy(PackageInfoLite pkgLite) { 11768 String packageName = pkgLite.packageName; 11769 int installLocation = pkgLite.installLocation; 11770 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11771 // reader 11772 synchronized (mPackages) { 11773 // Currently installed package which the new package is attempting to replace or 11774 // null if no such package is installed. 11775 PackageParser.Package installedPkg = mPackages.get(packageName); 11776 // Package which currently owns the data which the new package will own if installed. 11777 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11778 // will be null whereas dataOwnerPkg will contain information about the package 11779 // which was uninstalled while keeping its data. 11780 PackageParser.Package dataOwnerPkg = installedPkg; 11781 if (dataOwnerPkg == null) { 11782 PackageSetting ps = mSettings.mPackages.get(packageName); 11783 if (ps != null) { 11784 dataOwnerPkg = ps.pkg; 11785 } 11786 } 11787 11788 if (dataOwnerPkg != null) { 11789 // If installed, the package will get access to data left on the device by its 11790 // predecessor. As a security measure, this is permited only if this is not a 11791 // version downgrade or if the predecessor package is marked as debuggable and 11792 // a downgrade is explicitly requested. 11793 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11794 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11795 try { 11796 checkDowngrade(dataOwnerPkg, pkgLite); 11797 } catch (PackageManagerException e) { 11798 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11799 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11800 } 11801 } 11802 } 11803 11804 if (installedPkg != null) { 11805 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11806 // Check for updated system application. 11807 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11808 if (onSd) { 11809 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11810 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11811 } 11812 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11813 } else { 11814 if (onSd) { 11815 // Install flag overrides everything. 11816 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11817 } 11818 // If current upgrade specifies particular preference 11819 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11820 // Application explicitly specified internal. 11821 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11822 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11823 // App explictly prefers external. Let policy decide 11824 } else { 11825 // Prefer previous location 11826 if (isExternal(installedPkg)) { 11827 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11828 } 11829 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11830 } 11831 } 11832 } else { 11833 // Invalid install. Return error code 11834 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11835 } 11836 } 11837 } 11838 // All the special cases have been taken care of. 11839 // Return result based on recommended install location. 11840 if (onSd) { 11841 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11842 } 11843 return pkgLite.recommendedInstallLocation; 11844 } 11845 11846 /* 11847 * Invoke remote method to get package information and install 11848 * location values. Override install location based on default 11849 * policy if needed and then create install arguments based 11850 * on the install location. 11851 */ 11852 public void handleStartCopy() throws RemoteException { 11853 int ret = PackageManager.INSTALL_SUCCEEDED; 11854 11855 // If we're already staged, we've firmly committed to an install location 11856 if (origin.staged) { 11857 if (origin.file != null) { 11858 installFlags |= PackageManager.INSTALL_INTERNAL; 11859 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11860 } else if (origin.cid != null) { 11861 installFlags |= PackageManager.INSTALL_EXTERNAL; 11862 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11863 } else { 11864 throw new IllegalStateException("Invalid stage location"); 11865 } 11866 } 11867 11868 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11869 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11870 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11871 PackageInfoLite pkgLite = null; 11872 11873 if (onInt && onSd) { 11874 // Check if both bits are set. 11875 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11876 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11877 } else if (onSd && ephemeral) { 11878 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11879 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11880 } else { 11881 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11882 packageAbiOverride); 11883 11884 if (DEBUG_EPHEMERAL && ephemeral) { 11885 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11886 } 11887 11888 /* 11889 * If we have too little free space, try to free cache 11890 * before giving up. 11891 */ 11892 if (!origin.staged && pkgLite.recommendedInstallLocation 11893 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11894 // TODO: focus freeing disk space on the target device 11895 final StorageManager storage = StorageManager.from(mContext); 11896 final long lowThreshold = storage.getStorageLowBytes( 11897 Environment.getDataDirectory()); 11898 11899 final long sizeBytes = mContainerService.calculateInstalledSize( 11900 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11901 11902 try { 11903 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11904 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11905 installFlags, packageAbiOverride); 11906 } catch (InstallerException e) { 11907 Slog.w(TAG, "Failed to free cache", e); 11908 } 11909 11910 /* 11911 * The cache free must have deleted the file we 11912 * downloaded to install. 11913 * 11914 * TODO: fix the "freeCache" call to not delete 11915 * the file we care about. 11916 */ 11917 if (pkgLite.recommendedInstallLocation 11918 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11919 pkgLite.recommendedInstallLocation 11920 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11921 } 11922 } 11923 } 11924 11925 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11926 int loc = pkgLite.recommendedInstallLocation; 11927 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11928 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11929 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11930 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11931 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11932 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11933 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11934 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11935 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11936 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11937 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11938 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11939 } else { 11940 // Override with defaults if needed. 11941 loc = installLocationPolicy(pkgLite); 11942 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11943 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11944 } else if (!onSd && !onInt) { 11945 // Override install location with flags 11946 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11947 // Set the flag to install on external media. 11948 installFlags |= PackageManager.INSTALL_EXTERNAL; 11949 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11950 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11951 if (DEBUG_EPHEMERAL) { 11952 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11953 } 11954 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11955 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11956 |PackageManager.INSTALL_INTERNAL); 11957 } else { 11958 // Make sure the flag for installing on external 11959 // media is unset 11960 installFlags |= PackageManager.INSTALL_INTERNAL; 11961 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11962 } 11963 } 11964 } 11965 } 11966 11967 final InstallArgs args = createInstallArgs(this); 11968 mArgs = args; 11969 11970 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11971 // TODO: http://b/22976637 11972 // Apps installed for "all" users use the device owner to verify the app 11973 UserHandle verifierUser = getUser(); 11974 if (verifierUser == UserHandle.ALL) { 11975 verifierUser = UserHandle.SYSTEM; 11976 } 11977 11978 /* 11979 * Determine if we have any installed package verifiers. If we 11980 * do, then we'll defer to them to verify the packages. 11981 */ 11982 final int requiredUid = mRequiredVerifierPackage == null ? -1 11983 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11984 verifierUser.getIdentifier()); 11985 if (!origin.existing && requiredUid != -1 11986 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11987 final Intent verification = new Intent( 11988 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11989 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11990 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11991 PACKAGE_MIME_TYPE); 11992 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11993 11994 // Query all live verifiers based on current user state 11995 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11996 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11997 11998 if (DEBUG_VERIFY) { 11999 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12000 + verification.toString() + " with " + pkgLite.verifiers.length 12001 + " optional verifiers"); 12002 } 12003 12004 final int verificationId = mPendingVerificationToken++; 12005 12006 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12007 12008 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12009 installerPackageName); 12010 12011 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12012 installFlags); 12013 12014 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12015 pkgLite.packageName); 12016 12017 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12018 pkgLite.versionCode); 12019 12020 if (verificationInfo != null) { 12021 if (verificationInfo.originatingUri != null) { 12022 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12023 verificationInfo.originatingUri); 12024 } 12025 if (verificationInfo.referrer != null) { 12026 verification.putExtra(Intent.EXTRA_REFERRER, 12027 verificationInfo.referrer); 12028 } 12029 if (verificationInfo.originatingUid >= 0) { 12030 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12031 verificationInfo.originatingUid); 12032 } 12033 if (verificationInfo.installerUid >= 0) { 12034 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12035 verificationInfo.installerUid); 12036 } 12037 } 12038 12039 final PackageVerificationState verificationState = new PackageVerificationState( 12040 requiredUid, args); 12041 12042 mPendingVerification.append(verificationId, verificationState); 12043 12044 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12045 receivers, verificationState); 12046 12047 /* 12048 * If any sufficient verifiers were listed in the package 12049 * manifest, attempt to ask them. 12050 */ 12051 if (sufficientVerifiers != null) { 12052 final int N = sufficientVerifiers.size(); 12053 if (N == 0) { 12054 Slog.i(TAG, "Additional verifiers required, but none installed."); 12055 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12056 } else { 12057 for (int i = 0; i < N; i++) { 12058 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12059 12060 final Intent sufficientIntent = new Intent(verification); 12061 sufficientIntent.setComponent(verifierComponent); 12062 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12063 } 12064 } 12065 } 12066 12067 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12068 mRequiredVerifierPackage, receivers); 12069 if (ret == PackageManager.INSTALL_SUCCEEDED 12070 && mRequiredVerifierPackage != null) { 12071 Trace.asyncTraceBegin( 12072 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12073 /* 12074 * Send the intent to the required verification agent, 12075 * but only start the verification timeout after the 12076 * target BroadcastReceivers have run. 12077 */ 12078 verification.setComponent(requiredVerifierComponent); 12079 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12080 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12081 new BroadcastReceiver() { 12082 @Override 12083 public void onReceive(Context context, Intent intent) { 12084 final Message msg = mHandler 12085 .obtainMessage(CHECK_PENDING_VERIFICATION); 12086 msg.arg1 = verificationId; 12087 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12088 } 12089 }, null, 0, null, null); 12090 12091 /* 12092 * We don't want the copy to proceed until verification 12093 * succeeds, so null out this field. 12094 */ 12095 mArgs = null; 12096 } 12097 } else { 12098 /* 12099 * No package verification is enabled, so immediately start 12100 * the remote call to initiate copy using temporary file. 12101 */ 12102 ret = args.copyApk(mContainerService, true); 12103 } 12104 } 12105 12106 mRet = ret; 12107 } 12108 12109 @Override 12110 void handleReturnCode() { 12111 // If mArgs is null, then MCS couldn't be reached. When it 12112 // reconnects, it will try again to install. At that point, this 12113 // will succeed. 12114 if (mArgs != null) { 12115 processPendingInstall(mArgs, mRet); 12116 } 12117 } 12118 12119 @Override 12120 void handleServiceError() { 12121 mArgs = createInstallArgs(this); 12122 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12123 } 12124 12125 public boolean isForwardLocked() { 12126 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12127 } 12128 } 12129 12130 /** 12131 * Used during creation of InstallArgs 12132 * 12133 * @param installFlags package installation flags 12134 * @return true if should be installed on external storage 12135 */ 12136 private static boolean installOnExternalAsec(int installFlags) { 12137 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12138 return false; 12139 } 12140 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12141 return true; 12142 } 12143 return false; 12144 } 12145 12146 /** 12147 * Used during creation of InstallArgs 12148 * 12149 * @param installFlags package installation flags 12150 * @return true if should be installed as forward locked 12151 */ 12152 private static boolean installForwardLocked(int installFlags) { 12153 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12154 } 12155 12156 private InstallArgs createInstallArgs(InstallParams params) { 12157 if (params.move != null) { 12158 return new MoveInstallArgs(params); 12159 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12160 return new AsecInstallArgs(params); 12161 } else { 12162 return new FileInstallArgs(params); 12163 } 12164 } 12165 12166 /** 12167 * Create args that describe an existing installed package. Typically used 12168 * when cleaning up old installs, or used as a move source. 12169 */ 12170 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12171 String resourcePath, String[] instructionSets) { 12172 final boolean isInAsec; 12173 if (installOnExternalAsec(installFlags)) { 12174 /* Apps on SD card are always in ASEC containers. */ 12175 isInAsec = true; 12176 } else if (installForwardLocked(installFlags) 12177 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12178 /* 12179 * Forward-locked apps are only in ASEC containers if they're the 12180 * new style 12181 */ 12182 isInAsec = true; 12183 } else { 12184 isInAsec = false; 12185 } 12186 12187 if (isInAsec) { 12188 return new AsecInstallArgs(codePath, instructionSets, 12189 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12190 } else { 12191 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12192 } 12193 } 12194 12195 static abstract class InstallArgs { 12196 /** @see InstallParams#origin */ 12197 final OriginInfo origin; 12198 /** @see InstallParams#move */ 12199 final MoveInfo move; 12200 12201 final IPackageInstallObserver2 observer; 12202 // Always refers to PackageManager flags only 12203 final int installFlags; 12204 final String installerPackageName; 12205 final String volumeUuid; 12206 final UserHandle user; 12207 final String abiOverride; 12208 final String[] installGrantPermissions; 12209 /** If non-null, drop an async trace when the install completes */ 12210 final String traceMethod; 12211 final int traceCookie; 12212 12213 // The list of instruction sets supported by this app. This is currently 12214 // only used during the rmdex() phase to clean up resources. We can get rid of this 12215 // if we move dex files under the common app path. 12216 /* nullable */ String[] instructionSets; 12217 12218 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12219 int installFlags, String installerPackageName, String volumeUuid, 12220 UserHandle user, String[] instructionSets, 12221 String abiOverride, String[] installGrantPermissions, 12222 String traceMethod, int traceCookie) { 12223 this.origin = origin; 12224 this.move = move; 12225 this.installFlags = installFlags; 12226 this.observer = observer; 12227 this.installerPackageName = installerPackageName; 12228 this.volumeUuid = volumeUuid; 12229 this.user = user; 12230 this.instructionSets = instructionSets; 12231 this.abiOverride = abiOverride; 12232 this.installGrantPermissions = installGrantPermissions; 12233 this.traceMethod = traceMethod; 12234 this.traceCookie = traceCookie; 12235 } 12236 12237 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12238 abstract int doPreInstall(int status); 12239 12240 /** 12241 * Rename package into final resting place. All paths on the given 12242 * scanned package should be updated to reflect the rename. 12243 */ 12244 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12245 abstract int doPostInstall(int status, int uid); 12246 12247 /** @see PackageSettingBase#codePathString */ 12248 abstract String getCodePath(); 12249 /** @see PackageSettingBase#resourcePathString */ 12250 abstract String getResourcePath(); 12251 12252 // Need installer lock especially for dex file removal. 12253 abstract void cleanUpResourcesLI(); 12254 abstract boolean doPostDeleteLI(boolean delete); 12255 12256 /** 12257 * Called before the source arguments are copied. This is used mostly 12258 * for MoveParams when it needs to read the source file to put it in the 12259 * destination. 12260 */ 12261 int doPreCopy() { 12262 return PackageManager.INSTALL_SUCCEEDED; 12263 } 12264 12265 /** 12266 * Called after the source arguments are copied. This is used mostly for 12267 * MoveParams when it needs to read the source file to put it in the 12268 * destination. 12269 * 12270 * @return 12271 */ 12272 int doPostCopy(int uid) { 12273 return PackageManager.INSTALL_SUCCEEDED; 12274 } 12275 12276 protected boolean isFwdLocked() { 12277 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12278 } 12279 12280 protected boolean isExternalAsec() { 12281 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12282 } 12283 12284 protected boolean isEphemeral() { 12285 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12286 } 12287 12288 UserHandle getUser() { 12289 return user; 12290 } 12291 } 12292 12293 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12294 if (!allCodePaths.isEmpty()) { 12295 if (instructionSets == null) { 12296 throw new IllegalStateException("instructionSet == null"); 12297 } 12298 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12299 for (String codePath : allCodePaths) { 12300 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12301 try { 12302 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12303 } catch (InstallerException ignored) { 12304 } 12305 } 12306 } 12307 } 12308 } 12309 12310 /** 12311 * Logic to handle installation of non-ASEC applications, including copying 12312 * and renaming logic. 12313 */ 12314 class FileInstallArgs extends InstallArgs { 12315 private File codeFile; 12316 private File resourceFile; 12317 12318 // Example topology: 12319 // /data/app/com.example/base.apk 12320 // /data/app/com.example/split_foo.apk 12321 // /data/app/com.example/lib/arm/libfoo.so 12322 // /data/app/com.example/lib/arm64/libfoo.so 12323 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12324 12325 /** New install */ 12326 FileInstallArgs(InstallParams params) { 12327 super(params.origin, params.move, params.observer, params.installFlags, 12328 params.installerPackageName, params.volumeUuid, 12329 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12330 params.grantedRuntimePermissions, 12331 params.traceMethod, params.traceCookie); 12332 if (isFwdLocked()) { 12333 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12334 } 12335 } 12336 12337 /** Existing install */ 12338 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12339 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12340 null, null, null, 0); 12341 this.codeFile = (codePath != null) ? new File(codePath) : null; 12342 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12343 } 12344 12345 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12346 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12347 try { 12348 return doCopyApk(imcs, temp); 12349 } finally { 12350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12351 } 12352 } 12353 12354 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12355 if (origin.staged) { 12356 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12357 codeFile = origin.file; 12358 resourceFile = origin.file; 12359 return PackageManager.INSTALL_SUCCEEDED; 12360 } 12361 12362 try { 12363 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12364 final File tempDir = 12365 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12366 codeFile = tempDir; 12367 resourceFile = tempDir; 12368 } catch (IOException e) { 12369 Slog.w(TAG, "Failed to create copy file: " + e); 12370 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12371 } 12372 12373 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12374 @Override 12375 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12376 if (!FileUtils.isValidExtFilename(name)) { 12377 throw new IllegalArgumentException("Invalid filename: " + name); 12378 } 12379 try { 12380 final File file = new File(codeFile, name); 12381 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12382 O_RDWR | O_CREAT, 0644); 12383 Os.chmod(file.getAbsolutePath(), 0644); 12384 return new ParcelFileDescriptor(fd); 12385 } catch (ErrnoException e) { 12386 throw new RemoteException("Failed to open: " + e.getMessage()); 12387 } 12388 } 12389 }; 12390 12391 int ret = PackageManager.INSTALL_SUCCEEDED; 12392 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12393 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12394 Slog.e(TAG, "Failed to copy package"); 12395 return ret; 12396 } 12397 12398 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12399 NativeLibraryHelper.Handle handle = null; 12400 try { 12401 handle = NativeLibraryHelper.Handle.create(codeFile); 12402 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12403 abiOverride); 12404 } catch (IOException e) { 12405 Slog.e(TAG, "Copying native libraries failed", e); 12406 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12407 } finally { 12408 IoUtils.closeQuietly(handle); 12409 } 12410 12411 return ret; 12412 } 12413 12414 int doPreInstall(int status) { 12415 if (status != PackageManager.INSTALL_SUCCEEDED) { 12416 cleanUp(); 12417 } 12418 return status; 12419 } 12420 12421 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12422 if (status != PackageManager.INSTALL_SUCCEEDED) { 12423 cleanUp(); 12424 return false; 12425 } 12426 12427 final File targetDir = codeFile.getParentFile(); 12428 final File beforeCodeFile = codeFile; 12429 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12430 12431 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12432 try { 12433 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12434 } catch (ErrnoException e) { 12435 Slog.w(TAG, "Failed to rename", e); 12436 return false; 12437 } 12438 12439 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12440 Slog.w(TAG, "Failed to restorecon"); 12441 return false; 12442 } 12443 12444 // Reflect the rename internally 12445 codeFile = afterCodeFile; 12446 resourceFile = afterCodeFile; 12447 12448 // Reflect the rename in scanned details 12449 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12450 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12451 afterCodeFile, pkg.baseCodePath)); 12452 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12453 afterCodeFile, pkg.splitCodePaths)); 12454 12455 // Reflect the rename in app info 12456 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12457 pkg.setApplicationInfoCodePath(pkg.codePath); 12458 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12459 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12460 pkg.setApplicationInfoResourcePath(pkg.codePath); 12461 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12462 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12463 12464 return true; 12465 } 12466 12467 int doPostInstall(int status, int uid) { 12468 if (status != PackageManager.INSTALL_SUCCEEDED) { 12469 cleanUp(); 12470 } 12471 return status; 12472 } 12473 12474 @Override 12475 String getCodePath() { 12476 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12477 } 12478 12479 @Override 12480 String getResourcePath() { 12481 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12482 } 12483 12484 private boolean cleanUp() { 12485 if (codeFile == null || !codeFile.exists()) { 12486 return false; 12487 } 12488 12489 removeCodePathLI(codeFile); 12490 12491 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12492 resourceFile.delete(); 12493 } 12494 12495 return true; 12496 } 12497 12498 void cleanUpResourcesLI() { 12499 // Try enumerating all code paths before deleting 12500 List<String> allCodePaths = Collections.EMPTY_LIST; 12501 if (codeFile != null && codeFile.exists()) { 12502 try { 12503 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12504 allCodePaths = pkg.getAllCodePaths(); 12505 } catch (PackageParserException e) { 12506 // Ignored; we tried our best 12507 } 12508 } 12509 12510 cleanUp(); 12511 removeDexFiles(allCodePaths, instructionSets); 12512 } 12513 12514 boolean doPostDeleteLI(boolean delete) { 12515 // XXX err, shouldn't we respect the delete flag? 12516 cleanUpResourcesLI(); 12517 return true; 12518 } 12519 } 12520 12521 private boolean isAsecExternal(String cid) { 12522 final String asecPath = PackageHelper.getSdFilesystem(cid); 12523 return !asecPath.startsWith(mAsecInternalPath); 12524 } 12525 12526 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12527 PackageManagerException { 12528 if (copyRet < 0) { 12529 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12530 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12531 throw new PackageManagerException(copyRet, message); 12532 } 12533 } 12534 } 12535 12536 /** 12537 * Extract the MountService "container ID" from the full code path of an 12538 * .apk. 12539 */ 12540 static String cidFromCodePath(String fullCodePath) { 12541 int eidx = fullCodePath.lastIndexOf("/"); 12542 String subStr1 = fullCodePath.substring(0, eidx); 12543 int sidx = subStr1.lastIndexOf("/"); 12544 return subStr1.substring(sidx+1, eidx); 12545 } 12546 12547 /** 12548 * Logic to handle installation of ASEC applications, including copying and 12549 * renaming logic. 12550 */ 12551 class AsecInstallArgs extends InstallArgs { 12552 static final String RES_FILE_NAME = "pkg.apk"; 12553 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12554 12555 String cid; 12556 String packagePath; 12557 String resourcePath; 12558 12559 /** New install */ 12560 AsecInstallArgs(InstallParams params) { 12561 super(params.origin, params.move, params.observer, params.installFlags, 12562 params.installerPackageName, params.volumeUuid, 12563 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12564 params.grantedRuntimePermissions, 12565 params.traceMethod, params.traceCookie); 12566 } 12567 12568 /** Existing install */ 12569 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12570 boolean isExternal, boolean isForwardLocked) { 12571 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12572 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12573 instructionSets, null, null, null, 0); 12574 // Hackily pretend we're still looking at a full code path 12575 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12576 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12577 } 12578 12579 // Extract cid from fullCodePath 12580 int eidx = fullCodePath.lastIndexOf("/"); 12581 String subStr1 = fullCodePath.substring(0, eidx); 12582 int sidx = subStr1.lastIndexOf("/"); 12583 cid = subStr1.substring(sidx+1, eidx); 12584 setMountPath(subStr1); 12585 } 12586 12587 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12588 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12589 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12590 instructionSets, null, null, null, 0); 12591 this.cid = cid; 12592 setMountPath(PackageHelper.getSdDir(cid)); 12593 } 12594 12595 void createCopyFile() { 12596 cid = mInstallerService.allocateExternalStageCidLegacy(); 12597 } 12598 12599 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12600 if (origin.staged && origin.cid != null) { 12601 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12602 cid = origin.cid; 12603 setMountPath(PackageHelper.getSdDir(cid)); 12604 return PackageManager.INSTALL_SUCCEEDED; 12605 } 12606 12607 if (temp) { 12608 createCopyFile(); 12609 } else { 12610 /* 12611 * Pre-emptively destroy the container since it's destroyed if 12612 * copying fails due to it existing anyway. 12613 */ 12614 PackageHelper.destroySdDir(cid); 12615 } 12616 12617 final String newMountPath = imcs.copyPackageToContainer( 12618 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12619 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12620 12621 if (newMountPath != null) { 12622 setMountPath(newMountPath); 12623 return PackageManager.INSTALL_SUCCEEDED; 12624 } else { 12625 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12626 } 12627 } 12628 12629 @Override 12630 String getCodePath() { 12631 return packagePath; 12632 } 12633 12634 @Override 12635 String getResourcePath() { 12636 return resourcePath; 12637 } 12638 12639 int doPreInstall(int status) { 12640 if (status != PackageManager.INSTALL_SUCCEEDED) { 12641 // Destroy container 12642 PackageHelper.destroySdDir(cid); 12643 } else { 12644 boolean mounted = PackageHelper.isContainerMounted(cid); 12645 if (!mounted) { 12646 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12647 Process.SYSTEM_UID); 12648 if (newMountPath != null) { 12649 setMountPath(newMountPath); 12650 } else { 12651 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12652 } 12653 } 12654 } 12655 return status; 12656 } 12657 12658 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12659 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12660 String newMountPath = null; 12661 if (PackageHelper.isContainerMounted(cid)) { 12662 // Unmount the container 12663 if (!PackageHelper.unMountSdDir(cid)) { 12664 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12665 return false; 12666 } 12667 } 12668 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12669 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12670 " which might be stale. Will try to clean up."); 12671 // Clean up the stale container and proceed to recreate. 12672 if (!PackageHelper.destroySdDir(newCacheId)) { 12673 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12674 return false; 12675 } 12676 // Successfully cleaned up stale container. Try to rename again. 12677 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12678 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12679 + " inspite of cleaning it up."); 12680 return false; 12681 } 12682 } 12683 if (!PackageHelper.isContainerMounted(newCacheId)) { 12684 Slog.w(TAG, "Mounting container " + newCacheId); 12685 newMountPath = PackageHelper.mountSdDir(newCacheId, 12686 getEncryptKey(), Process.SYSTEM_UID); 12687 } else { 12688 newMountPath = PackageHelper.getSdDir(newCacheId); 12689 } 12690 if (newMountPath == null) { 12691 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12692 return false; 12693 } 12694 Log.i(TAG, "Succesfully renamed " + cid + 12695 " to " + newCacheId + 12696 " at new path: " + newMountPath); 12697 cid = newCacheId; 12698 12699 final File beforeCodeFile = new File(packagePath); 12700 setMountPath(newMountPath); 12701 final File afterCodeFile = new File(packagePath); 12702 12703 // Reflect the rename in scanned details 12704 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12705 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12706 afterCodeFile, pkg.baseCodePath)); 12707 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12708 afterCodeFile, pkg.splitCodePaths)); 12709 12710 // Reflect the rename in app info 12711 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12712 pkg.setApplicationInfoCodePath(pkg.codePath); 12713 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12714 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12715 pkg.setApplicationInfoResourcePath(pkg.codePath); 12716 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12717 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12718 12719 return true; 12720 } 12721 12722 private void setMountPath(String mountPath) { 12723 final File mountFile = new File(mountPath); 12724 12725 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12726 if (monolithicFile.exists()) { 12727 packagePath = monolithicFile.getAbsolutePath(); 12728 if (isFwdLocked()) { 12729 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12730 } else { 12731 resourcePath = packagePath; 12732 } 12733 } else { 12734 packagePath = mountFile.getAbsolutePath(); 12735 resourcePath = packagePath; 12736 } 12737 } 12738 12739 int doPostInstall(int status, int uid) { 12740 if (status != PackageManager.INSTALL_SUCCEEDED) { 12741 cleanUp(); 12742 } else { 12743 final int groupOwner; 12744 final String protectedFile; 12745 if (isFwdLocked()) { 12746 groupOwner = UserHandle.getSharedAppGid(uid); 12747 protectedFile = RES_FILE_NAME; 12748 } else { 12749 groupOwner = -1; 12750 protectedFile = null; 12751 } 12752 12753 if (uid < Process.FIRST_APPLICATION_UID 12754 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12755 Slog.e(TAG, "Failed to finalize " + cid); 12756 PackageHelper.destroySdDir(cid); 12757 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12758 } 12759 12760 boolean mounted = PackageHelper.isContainerMounted(cid); 12761 if (!mounted) { 12762 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12763 } 12764 } 12765 return status; 12766 } 12767 12768 private void cleanUp() { 12769 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12770 12771 // Destroy secure container 12772 PackageHelper.destroySdDir(cid); 12773 } 12774 12775 private List<String> getAllCodePaths() { 12776 final File codeFile = new File(getCodePath()); 12777 if (codeFile != null && codeFile.exists()) { 12778 try { 12779 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12780 return pkg.getAllCodePaths(); 12781 } catch (PackageParserException e) { 12782 // Ignored; we tried our best 12783 } 12784 } 12785 return Collections.EMPTY_LIST; 12786 } 12787 12788 void cleanUpResourcesLI() { 12789 // Enumerate all code paths before deleting 12790 cleanUpResourcesLI(getAllCodePaths()); 12791 } 12792 12793 private void cleanUpResourcesLI(List<String> allCodePaths) { 12794 cleanUp(); 12795 removeDexFiles(allCodePaths, instructionSets); 12796 } 12797 12798 String getPackageName() { 12799 return getAsecPackageName(cid); 12800 } 12801 12802 boolean doPostDeleteLI(boolean delete) { 12803 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12804 final List<String> allCodePaths = getAllCodePaths(); 12805 boolean mounted = PackageHelper.isContainerMounted(cid); 12806 if (mounted) { 12807 // Unmount first 12808 if (PackageHelper.unMountSdDir(cid)) { 12809 mounted = false; 12810 } 12811 } 12812 if (!mounted && delete) { 12813 cleanUpResourcesLI(allCodePaths); 12814 } 12815 return !mounted; 12816 } 12817 12818 @Override 12819 int doPreCopy() { 12820 if (isFwdLocked()) { 12821 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12822 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12824 } 12825 } 12826 12827 return PackageManager.INSTALL_SUCCEEDED; 12828 } 12829 12830 @Override 12831 int doPostCopy(int uid) { 12832 if (isFwdLocked()) { 12833 if (uid < Process.FIRST_APPLICATION_UID 12834 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12835 RES_FILE_NAME)) { 12836 Slog.e(TAG, "Failed to finalize " + cid); 12837 PackageHelper.destroySdDir(cid); 12838 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12839 } 12840 } 12841 12842 return PackageManager.INSTALL_SUCCEEDED; 12843 } 12844 } 12845 12846 /** 12847 * Logic to handle movement of existing installed applications. 12848 */ 12849 class MoveInstallArgs extends InstallArgs { 12850 private File codeFile; 12851 private File resourceFile; 12852 12853 /** New install */ 12854 MoveInstallArgs(InstallParams params) { 12855 super(params.origin, params.move, params.observer, params.installFlags, 12856 params.installerPackageName, params.volumeUuid, 12857 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12858 params.grantedRuntimePermissions, 12859 params.traceMethod, params.traceCookie); 12860 } 12861 12862 int copyApk(IMediaContainerService imcs, boolean temp) { 12863 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12864 + move.fromUuid + " to " + move.toUuid); 12865 synchronized (mInstaller) { 12866 try { 12867 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12868 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12869 } catch (InstallerException e) { 12870 Slog.w(TAG, "Failed to move app", e); 12871 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12872 } 12873 } 12874 12875 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12876 resourceFile = codeFile; 12877 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12878 12879 return PackageManager.INSTALL_SUCCEEDED; 12880 } 12881 12882 int doPreInstall(int status) { 12883 if (status != PackageManager.INSTALL_SUCCEEDED) { 12884 cleanUp(move.toUuid); 12885 } 12886 return status; 12887 } 12888 12889 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12890 if (status != PackageManager.INSTALL_SUCCEEDED) { 12891 cleanUp(move.toUuid); 12892 return false; 12893 } 12894 12895 // Reflect the move in app info 12896 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12897 pkg.setApplicationInfoCodePath(pkg.codePath); 12898 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12899 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12900 pkg.setApplicationInfoResourcePath(pkg.codePath); 12901 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12902 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12903 12904 return true; 12905 } 12906 12907 int doPostInstall(int status, int uid) { 12908 if (status == PackageManager.INSTALL_SUCCEEDED) { 12909 cleanUp(move.fromUuid); 12910 } else { 12911 cleanUp(move.toUuid); 12912 } 12913 return status; 12914 } 12915 12916 @Override 12917 String getCodePath() { 12918 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12919 } 12920 12921 @Override 12922 String getResourcePath() { 12923 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12924 } 12925 12926 private boolean cleanUp(String volumeUuid) { 12927 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12928 move.dataAppName); 12929 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12930 synchronized (mInstallLock) { 12931 // Clean up both app data and code 12932 removeDataDirsLI(volumeUuid, move.packageName); 12933 removeCodePathLI(codeFile); 12934 } 12935 return true; 12936 } 12937 12938 void cleanUpResourcesLI() { 12939 throw new UnsupportedOperationException(); 12940 } 12941 12942 boolean doPostDeleteLI(boolean delete) { 12943 throw new UnsupportedOperationException(); 12944 } 12945 } 12946 12947 static String getAsecPackageName(String packageCid) { 12948 int idx = packageCid.lastIndexOf("-"); 12949 if (idx == -1) { 12950 return packageCid; 12951 } 12952 return packageCid.substring(0, idx); 12953 } 12954 12955 // Utility method used to create code paths based on package name and available index. 12956 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12957 String idxStr = ""; 12958 int idx = 1; 12959 // Fall back to default value of idx=1 if prefix is not 12960 // part of oldCodePath 12961 if (oldCodePath != null) { 12962 String subStr = oldCodePath; 12963 // Drop the suffix right away 12964 if (suffix != null && subStr.endsWith(suffix)) { 12965 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12966 } 12967 // If oldCodePath already contains prefix find out the 12968 // ending index to either increment or decrement. 12969 int sidx = subStr.lastIndexOf(prefix); 12970 if (sidx != -1) { 12971 subStr = subStr.substring(sidx + prefix.length()); 12972 if (subStr != null) { 12973 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12974 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12975 } 12976 try { 12977 idx = Integer.parseInt(subStr); 12978 if (idx <= 1) { 12979 idx++; 12980 } else { 12981 idx--; 12982 } 12983 } catch(NumberFormatException e) { 12984 } 12985 } 12986 } 12987 } 12988 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12989 return prefix + idxStr; 12990 } 12991 12992 private File getNextCodePath(File targetDir, String packageName) { 12993 int suffix = 1; 12994 File result; 12995 do { 12996 result = new File(targetDir, packageName + "-" + suffix); 12997 suffix++; 12998 } while (result.exists()); 12999 return result; 13000 } 13001 13002 // Utility method that returns the relative package path with respect 13003 // to the installation directory. Like say for /data/data/com.test-1.apk 13004 // string com.test-1 is returned. 13005 static String deriveCodePathName(String codePath) { 13006 if (codePath == null) { 13007 return null; 13008 } 13009 final File codeFile = new File(codePath); 13010 final String name = codeFile.getName(); 13011 if (codeFile.isDirectory()) { 13012 return name; 13013 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13014 final int lastDot = name.lastIndexOf('.'); 13015 return name.substring(0, lastDot); 13016 } else { 13017 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13018 return null; 13019 } 13020 } 13021 13022 static class PackageInstalledInfo { 13023 String name; 13024 int uid; 13025 // The set of users that originally had this package installed. 13026 int[] origUsers; 13027 // The set of users that now have this package installed. 13028 int[] newUsers; 13029 PackageParser.Package pkg; 13030 int returnCode; 13031 String returnMsg; 13032 PackageRemovedInfo removedInfo; 13033 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13034 13035 public void setError(int code, String msg) { 13036 setReturnCode(code); 13037 setReturnMessage(msg); 13038 Slog.w(TAG, msg); 13039 } 13040 13041 public void setError(String msg, PackageParserException e) { 13042 setReturnCode(e.error); 13043 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13044 Slog.w(TAG, msg, e); 13045 } 13046 13047 public void setError(String msg, PackageManagerException e) { 13048 returnCode = e.error; 13049 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13050 Slog.w(TAG, msg, e); 13051 } 13052 13053 public void setReturnCode(int returnCode) { 13054 this.returnCode = returnCode; 13055 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13056 for (int i = 0; i < childCount; i++) { 13057 addedChildPackages.valueAt(i).returnCode = returnCode; 13058 } 13059 } 13060 13061 private void setReturnMessage(String returnMsg) { 13062 this.returnMsg = returnMsg; 13063 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13064 for (int i = 0; i < childCount; i++) { 13065 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13066 } 13067 } 13068 13069 // In some error cases we want to convey more info back to the observer 13070 String origPackage; 13071 String origPermission; 13072 } 13073 13074 /* 13075 * Install a non-existing package. 13076 */ 13077 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13078 UserHandle user, String installerPackageName, String volumeUuid, 13079 PackageInstalledInfo res) { 13080 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13081 13082 // Remember this for later, in case we need to rollback this install 13083 String pkgName = pkg.packageName; 13084 13085 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13086 13087 synchronized(mPackages) { 13088 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13089 // A package with the same name is already installed, though 13090 // it has been renamed to an older name. The package we 13091 // are trying to install should be installed as an update to 13092 // the existing one, but that has not been requested, so bail. 13093 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13094 + " without first uninstalling package running as " 13095 + mSettings.mRenamedPackages.get(pkgName)); 13096 return; 13097 } 13098 if (mPackages.containsKey(pkgName)) { 13099 // Don't allow installation over an existing package with the same name. 13100 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13101 + " without first uninstalling."); 13102 return; 13103 } 13104 } 13105 13106 try { 13107 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13108 System.currentTimeMillis(), user); 13109 13110 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13111 13112 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13113 prepareAppDataAfterInstall(newPackage); 13114 13115 } else { 13116 // Remove package from internal structures, but keep around any 13117 // data that might have already existed 13118 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13119 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13120 } 13121 } catch (PackageManagerException e) { 13122 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13123 } 13124 13125 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13126 } 13127 13128 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13129 // Can't rotate keys during boot or if sharedUser. 13130 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13131 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13132 return false; 13133 } 13134 // app is using upgradeKeySets; make sure all are valid 13135 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13136 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13137 for (int i = 0; i < upgradeKeySets.length; i++) { 13138 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13139 Slog.wtf(TAG, "Package " 13140 + (oldPs.name != null ? oldPs.name : "<null>") 13141 + " contains upgrade-key-set reference to unknown key-set: " 13142 + upgradeKeySets[i] 13143 + " reverting to signatures check."); 13144 return false; 13145 } 13146 } 13147 return true; 13148 } 13149 13150 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13151 // Upgrade keysets are being used. Determine if new package has a superset of the 13152 // required keys. 13153 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13154 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13155 for (int i = 0; i < upgradeKeySets.length; i++) { 13156 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13157 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13158 return true; 13159 } 13160 } 13161 return false; 13162 } 13163 13164 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13165 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13166 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13167 13168 final PackageParser.Package oldPackage; 13169 final String pkgName = pkg.packageName; 13170 final int[] allUsers; 13171 final boolean weFroze; 13172 13173 // First find the old package info and check signatures 13174 synchronized(mPackages) { 13175 oldPackage = mPackages.get(pkgName); 13176 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13177 if (isEphemeral && !oldIsEphemeral) { 13178 // can't downgrade from full to ephemeral 13179 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13180 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13181 return; 13182 } 13183 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13184 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13185 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13186 if (!checkUpgradeKeySetLP(ps, pkg)) { 13187 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13188 "New package not signed by keys specified by upgrade-keysets: " 13189 + pkgName); 13190 return; 13191 } 13192 } else { 13193 // default to original signature matching 13194 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13195 != PackageManager.SIGNATURE_MATCH) { 13196 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13197 "New package has a different signature: " + pkgName); 13198 return; 13199 } 13200 } 13201 13202 // In case of rollback, remember per-user/profile install state 13203 allUsers = sUserManager.getUserIds(); 13204 13205 // Mark the app as frozen to prevent launching during the upgrade 13206 // process, and then kill all running instances 13207 if (!ps.frozen) { 13208 ps.frozen = true; 13209 weFroze = true; 13210 } else { 13211 weFroze = false; 13212 } 13213 } 13214 13215 try { 13216 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13217 installerPackageName, res); 13218 } finally { 13219 // Regardless of success or failure of upgrade steps above, always 13220 // unfreeze the package if we froze it 13221 if (weFroze) { 13222 unfreezePackage(pkgName); 13223 } 13224 } 13225 } 13226 13227 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13228 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13229 String installerPackageName, PackageInstalledInfo res) { 13230 // Update what is removed 13231 res.removedInfo = new PackageRemovedInfo(); 13232 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13233 res.removedInfo.removedPackage = oldPackage.packageName; 13234 res.removedInfo.isUpdate = true; 13235 final int childCount = (oldPackage.childPackages != null) 13236 ? oldPackage.childPackages.size() : 0; 13237 for (int i = 0; i < childCount; i++) { 13238 boolean childPackageUpdated = false; 13239 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13240 if (res.addedChildPackages != null) { 13241 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13242 if (childRes != null) { 13243 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13244 childRes.removedInfo.removedPackage = childPkg.packageName; 13245 childRes.removedInfo.isUpdate = true; 13246 childPackageUpdated = true; 13247 } 13248 } 13249 if (!childPackageUpdated) { 13250 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13251 childRemovedRes.removedPackage = childPkg.packageName; 13252 childRemovedRes.isUpdate = false; 13253 childRemovedRes.dataRemoved = true; 13254 synchronized (mPackages) { 13255 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13256 if (childPs != null) { 13257 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13258 } 13259 } 13260 if (res.removedInfo.removedChildPackages == null) { 13261 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13262 } 13263 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13264 } 13265 } 13266 13267 boolean sysPkg = (isSystemApp(oldPackage)); 13268 if (sysPkg) { 13269 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13270 user, allUsers, installerPackageName, res); 13271 } else { 13272 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13273 user, allUsers, installerPackageName, res); 13274 } 13275 } 13276 13277 public List<String> getPreviousCodePaths(String packageName) { 13278 final PackageSetting ps = mSettings.mPackages.get(packageName); 13279 final List<String> result = new ArrayList<String>(); 13280 if (ps != null && ps.oldCodePaths != null) { 13281 result.addAll(ps.oldCodePaths); 13282 } 13283 return result; 13284 } 13285 13286 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13287 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13288 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13289 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13290 + deletedPackage); 13291 13292 String pkgName = deletedPackage.packageName; 13293 boolean deletedPkg = true; 13294 boolean addedPkg = false; 13295 boolean updatedSettings = false; 13296 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13297 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13298 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13299 13300 final long origUpdateTime = (pkg.mExtras != null) 13301 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13302 13303 // First delete the existing package while retaining the data directory 13304 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13305 res.removedInfo, true, pkg)) { 13306 // If the existing package wasn't successfully deleted 13307 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13308 deletedPkg = false; 13309 } else { 13310 // Successfully deleted the old package; proceed with replace. 13311 13312 // If deleted package lived in a container, give users a chance to 13313 // relinquish resources before killing. 13314 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13315 if (DEBUG_INSTALL) { 13316 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13317 } 13318 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13319 final ArrayList<String> pkgList = new ArrayList<String>(1); 13320 pkgList.add(deletedPackage.applicationInfo.packageName); 13321 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13322 } 13323 13324 deleteCodeCacheDirsLI(pkg); 13325 deleteProfilesLI(pkg, /*destroy*/ false); 13326 13327 try { 13328 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13329 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13330 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13331 13332 // Update the in-memory copy of the previous code paths. 13333 PackageSetting ps = mSettings.mPackages.get(pkgName); 13334 if (!killApp) { 13335 if (ps.oldCodePaths == null) { 13336 ps.oldCodePaths = new ArraySet<>(); 13337 } 13338 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13339 if (deletedPackage.splitCodePaths != null) { 13340 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13341 } 13342 } else { 13343 ps.oldCodePaths = null; 13344 } 13345 if (ps.childPackageNames != null) { 13346 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13347 final String childPkgName = ps.childPackageNames.get(i); 13348 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13349 childPs.oldCodePaths = ps.oldCodePaths; 13350 } 13351 } 13352 prepareAppDataAfterInstall(newPackage); 13353 addedPkg = true; 13354 } catch (PackageManagerException e) { 13355 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13356 } 13357 } 13358 13359 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13360 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13361 13362 // Revert all internal state mutations and added folders for the failed install 13363 if (addedPkg) { 13364 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13365 res.removedInfo, true, null); 13366 } 13367 13368 // Restore the old package 13369 if (deletedPkg) { 13370 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13371 File restoreFile = new File(deletedPackage.codePath); 13372 // Parse old package 13373 boolean oldExternal = isExternal(deletedPackage); 13374 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13375 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13376 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13377 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13378 try { 13379 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13380 null); 13381 } catch (PackageManagerException e) { 13382 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13383 + e.getMessage()); 13384 return; 13385 } 13386 13387 synchronized (mPackages) { 13388 // Ensure the installer package name up to date 13389 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13390 13391 // Update permissions for restored package 13392 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13393 13394 mSettings.writeLPr(); 13395 } 13396 13397 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13398 } 13399 } else { 13400 synchronized (mPackages) { 13401 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13402 if (ps != null) { 13403 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13404 if (res.removedInfo.removedChildPackages != null) { 13405 final int childCount = res.removedInfo.removedChildPackages.size(); 13406 // Iterate in reverse as we may modify the collection 13407 for (int i = childCount - 1; i >= 0; i--) { 13408 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13409 if (res.addedChildPackages.containsKey(childPackageName)) { 13410 res.removedInfo.removedChildPackages.removeAt(i); 13411 } else { 13412 PackageRemovedInfo childInfo = res.removedInfo 13413 .removedChildPackages.valueAt(i); 13414 childInfo.removedForAllUsers = mPackages.get( 13415 childInfo.removedPackage) == null; 13416 } 13417 } 13418 } 13419 } 13420 } 13421 } 13422 } 13423 13424 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13425 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13426 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13427 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13428 + ", old=" + deletedPackage); 13429 13430 final boolean disabledSystem; 13431 13432 // Set the system/privileged flags as needed 13433 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13434 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13435 != 0) { 13436 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13437 } 13438 13439 // Kill package processes including services, providers, etc. 13440 killPackage(deletedPackage, "replace sys pkg"); 13441 13442 // Remove existing system package 13443 removePackageLI(deletedPackage, true); 13444 13445 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13446 if (!disabledSystem) { 13447 // We didn't need to disable the .apk as a current system package, 13448 // which means we are replacing another update that is already 13449 // installed. We need to make sure to delete the older one's .apk. 13450 res.removedInfo.args = createInstallArgsForExisting(0, 13451 deletedPackage.applicationInfo.getCodePath(), 13452 deletedPackage.applicationInfo.getResourcePath(), 13453 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13454 } else { 13455 res.removedInfo.args = null; 13456 } 13457 13458 // Successfully disabled the old package. Now proceed with re-installation 13459 deleteCodeCacheDirsLI(pkg); 13460 deleteProfilesLI(pkg, /*destroy*/ false); 13461 13462 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13463 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13464 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13465 13466 PackageParser.Package newPackage = null; 13467 try { 13468 // Add the package to the internal data structures 13469 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13470 13471 // Set the update and install times 13472 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13473 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13474 System.currentTimeMillis()); 13475 13476 // Check for shared user id changes 13477 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13478 deletedPackage, newPackage); 13479 if (invalidPackageName != null) { 13480 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13481 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13482 + " to " + invalidPackageName); 13483 } 13484 13485 // Update the package dynamic state if succeeded 13486 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13487 // Now that the install succeeded make sure we remove data 13488 // directories for any child package the update removed. 13489 final int deletedChildCount = (deletedPackage.childPackages != null) 13490 ? deletedPackage.childPackages.size() : 0; 13491 final int newChildCount = (newPackage.childPackages != null) 13492 ? newPackage.childPackages.size() : 0; 13493 for (int i = 0; i < deletedChildCount; i++) { 13494 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13495 boolean childPackageDeleted = true; 13496 for (int j = 0; j < newChildCount; j++) { 13497 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13498 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13499 childPackageDeleted = false; 13500 break; 13501 } 13502 } 13503 if (childPackageDeleted) { 13504 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13505 deletedChildPkg.packageName); 13506 if (ps != null && res.removedInfo.removedChildPackages != null) { 13507 PackageRemovedInfo removedChildRes = res.removedInfo 13508 .removedChildPackages.get(deletedChildPkg.packageName); 13509 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13510 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13511 } 13512 } 13513 } 13514 13515 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13516 prepareAppDataAfterInstall(newPackage); 13517 } 13518 } catch (PackageManagerException e) { 13519 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13520 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13521 } 13522 13523 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13524 // Re installation failed. Restore old information 13525 // Remove new pkg information 13526 if (newPackage != null) { 13527 removeInstalledPackageLI(newPackage, true); 13528 } 13529 // Add back the old system package 13530 try { 13531 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13532 } catch (PackageManagerException e) { 13533 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13534 } 13535 13536 synchronized (mPackages) { 13537 if (disabledSystem) { 13538 enableSystemPackageLPw(deletedPackage); 13539 } 13540 13541 // Ensure the installer package name up to date 13542 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13543 13544 // Update permissions for restored package 13545 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13546 13547 mSettings.writeLPr(); 13548 } 13549 13550 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13551 + " after failed upgrade"); 13552 } 13553 } 13554 13555 /** 13556 * Checks whether the parent or any of the child packages have a change shared 13557 * user. For a package to be a valid update the shred users of the parent and 13558 * the children should match. We may later support changing child shared users. 13559 * @param oldPkg The updated package. 13560 * @param newPkg The update package. 13561 * @return The shared user that change between the versions. 13562 */ 13563 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13564 PackageParser.Package newPkg) { 13565 // Check parent shared user 13566 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13567 return newPkg.packageName; 13568 } 13569 // Check child shared users 13570 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13571 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13572 for (int i = 0; i < newChildCount; i++) { 13573 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13574 // If this child was present, did it have the same shared user? 13575 for (int j = 0; j < oldChildCount; j++) { 13576 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13577 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13578 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13579 return newChildPkg.packageName; 13580 } 13581 } 13582 } 13583 return null; 13584 } 13585 13586 private void removeNativeBinariesLI(PackageSetting ps) { 13587 // Remove the lib path for the parent package 13588 if (ps != null) { 13589 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13590 // Remove the lib path for the child packages 13591 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13592 for (int i = 0; i < childCount; i++) { 13593 PackageSetting childPs = null; 13594 synchronized (mPackages) { 13595 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13596 } 13597 if (childPs != null) { 13598 NativeLibraryHelper.removeNativeBinariesLI(childPs 13599 .legacyNativeLibraryPathString); 13600 } 13601 } 13602 } 13603 } 13604 13605 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13606 // Enable the parent package 13607 mSettings.enableSystemPackageLPw(pkg.packageName); 13608 // Enable the child packages 13609 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13610 for (int i = 0; i < childCount; i++) { 13611 PackageParser.Package childPkg = pkg.childPackages.get(i); 13612 mSettings.enableSystemPackageLPw(childPkg.packageName); 13613 } 13614 } 13615 13616 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13617 PackageParser.Package newPkg) { 13618 // Disable the parent package (parent always replaced) 13619 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13620 // Disable the child packages 13621 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13622 for (int i = 0; i < childCount; i++) { 13623 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13624 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13625 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13626 } 13627 return disabled; 13628 } 13629 13630 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13631 String installerPackageName) { 13632 // Enable the parent package 13633 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13634 // Enable the child packages 13635 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13636 for (int i = 0; i < childCount; i++) { 13637 PackageParser.Package childPkg = pkg.childPackages.get(i); 13638 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13639 } 13640 } 13641 13642 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13643 // Collect all used permissions in the UID 13644 ArraySet<String> usedPermissions = new ArraySet<>(); 13645 final int packageCount = su.packages.size(); 13646 for (int i = 0; i < packageCount; i++) { 13647 PackageSetting ps = su.packages.valueAt(i); 13648 if (ps.pkg == null) { 13649 continue; 13650 } 13651 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13652 for (int j = 0; j < requestedPermCount; j++) { 13653 String permission = ps.pkg.requestedPermissions.get(j); 13654 BasePermission bp = mSettings.mPermissions.get(permission); 13655 if (bp != null) { 13656 usedPermissions.add(permission); 13657 } 13658 } 13659 } 13660 13661 PermissionsState permissionsState = su.getPermissionsState(); 13662 // Prune install permissions 13663 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13664 final int installPermCount = installPermStates.size(); 13665 for (int i = installPermCount - 1; i >= 0; i--) { 13666 PermissionState permissionState = installPermStates.get(i); 13667 if (!usedPermissions.contains(permissionState.getName())) { 13668 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13669 if (bp != null) { 13670 permissionsState.revokeInstallPermission(bp); 13671 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13672 PackageManager.MASK_PERMISSION_FLAGS, 0); 13673 } 13674 } 13675 } 13676 13677 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13678 13679 // Prune runtime permissions 13680 for (int userId : allUserIds) { 13681 List<PermissionState> runtimePermStates = permissionsState 13682 .getRuntimePermissionStates(userId); 13683 final int runtimePermCount = runtimePermStates.size(); 13684 for (int i = runtimePermCount - 1; i >= 0; i--) { 13685 PermissionState permissionState = runtimePermStates.get(i); 13686 if (!usedPermissions.contains(permissionState.getName())) { 13687 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13688 if (bp != null) { 13689 permissionsState.revokeRuntimePermission(bp, userId); 13690 permissionsState.updatePermissionFlags(bp, userId, 13691 PackageManager.MASK_PERMISSION_FLAGS, 0); 13692 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13693 runtimePermissionChangedUserIds, userId); 13694 } 13695 } 13696 } 13697 } 13698 13699 return runtimePermissionChangedUserIds; 13700 } 13701 13702 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13703 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13704 // Update the parent package setting 13705 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13706 res, user); 13707 // Update the child packages setting 13708 final int childCount = (newPackage.childPackages != null) 13709 ? newPackage.childPackages.size() : 0; 13710 for (int i = 0; i < childCount; i++) { 13711 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13712 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13713 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13714 childRes.origUsers, childRes, user); 13715 } 13716 } 13717 13718 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13719 String installerPackageName, int[] allUsers, int[] installedForUsers, 13720 PackageInstalledInfo res, UserHandle user) { 13721 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13722 13723 String pkgName = newPackage.packageName; 13724 synchronized (mPackages) { 13725 //write settings. the installStatus will be incomplete at this stage. 13726 //note that the new package setting would have already been 13727 //added to mPackages. It hasn't been persisted yet. 13728 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13730 mSettings.writeLPr(); 13731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13732 } 13733 13734 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13735 synchronized (mPackages) { 13736 updatePermissionsLPw(newPackage.packageName, newPackage, 13737 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13738 ? UPDATE_PERMISSIONS_ALL : 0)); 13739 // For system-bundled packages, we assume that installing an upgraded version 13740 // of the package implies that the user actually wants to run that new code, 13741 // so we enable the package. 13742 PackageSetting ps = mSettings.mPackages.get(pkgName); 13743 final int userId = user.getIdentifier(); 13744 if (ps != null) { 13745 if (isSystemApp(newPackage)) { 13746 if (DEBUG_INSTALL) { 13747 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13748 } 13749 // Enable system package for requested users 13750 if (res.origUsers != null) { 13751 for (int origUserId : res.origUsers) { 13752 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13753 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13754 origUserId, installerPackageName); 13755 } 13756 } 13757 } 13758 // Also convey the prior install/uninstall state 13759 if (allUsers != null && installedForUsers != null) { 13760 for (int currentUserId : allUsers) { 13761 final boolean installed = ArrayUtils.contains( 13762 installedForUsers, currentUserId); 13763 if (DEBUG_INSTALL) { 13764 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13765 } 13766 ps.setInstalled(installed, currentUserId); 13767 } 13768 // these install state changes will be persisted in the 13769 // upcoming call to mSettings.writeLPr(). 13770 } 13771 } 13772 // It's implied that when a user requests installation, they want the app to be 13773 // installed and enabled. 13774 if (userId != UserHandle.USER_ALL) { 13775 ps.setInstalled(true, userId); 13776 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13777 } 13778 } 13779 res.name = pkgName; 13780 res.uid = newPackage.applicationInfo.uid; 13781 res.pkg = newPackage; 13782 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13783 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13784 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13785 //to update install status 13786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13787 mSettings.writeLPr(); 13788 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13789 } 13790 13791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13792 } 13793 13794 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13795 try { 13796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13797 installPackageLI(args, res); 13798 } finally { 13799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13800 } 13801 } 13802 13803 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13804 final int installFlags = args.installFlags; 13805 final String installerPackageName = args.installerPackageName; 13806 final String volumeUuid = args.volumeUuid; 13807 final File tmpPackageFile = new File(args.getCodePath()); 13808 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13809 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13810 || (args.volumeUuid != null)); 13811 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13812 boolean replace = false; 13813 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13814 if (args.move != null) { 13815 // moving a complete application; perform an initial scan on the new install location 13816 scanFlags |= SCAN_INITIAL; 13817 } 13818 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13819 scanFlags |= SCAN_DONT_KILL_APP; 13820 } 13821 13822 // Result object to be returned 13823 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13824 13825 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13826 13827 // Sanity check 13828 if (ephemeral && (forwardLocked || onExternal)) { 13829 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13830 + " external=" + onExternal); 13831 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13832 return; 13833 } 13834 13835 // Retrieve PackageSettings and parse package 13836 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13837 | PackageParser.PARSE_ENFORCE_CODE 13838 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13839 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13840 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13841 PackageParser pp = new PackageParser(); 13842 pp.setSeparateProcesses(mSeparateProcesses); 13843 pp.setDisplayMetrics(mMetrics); 13844 13845 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13846 final PackageParser.Package pkg; 13847 try { 13848 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13849 } catch (PackageParserException e) { 13850 res.setError("Failed parse during installPackageLI", e); 13851 return; 13852 } finally { 13853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13854 } 13855 13856 // If we are installing a clustered package add results for the children 13857 if (pkg.childPackages != null) { 13858 synchronized (mPackages) { 13859 final int childCount = pkg.childPackages.size(); 13860 for (int i = 0; i < childCount; i++) { 13861 PackageParser.Package childPkg = pkg.childPackages.get(i); 13862 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13863 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13864 childRes.pkg = childPkg; 13865 childRes.name = childPkg.packageName; 13866 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13867 if (childPs != null) { 13868 childRes.origUsers = childPs.queryInstalledUsers( 13869 sUserManager.getUserIds(), true); 13870 } 13871 if ((mPackages.containsKey(childPkg.packageName))) { 13872 childRes.removedInfo = new PackageRemovedInfo(); 13873 childRes.removedInfo.removedPackage = childPkg.packageName; 13874 } 13875 if (res.addedChildPackages == null) { 13876 res.addedChildPackages = new ArrayMap<>(); 13877 } 13878 res.addedChildPackages.put(childPkg.packageName, childRes); 13879 } 13880 } 13881 } 13882 13883 // If package doesn't declare API override, mark that we have an install 13884 // time CPU ABI override. 13885 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13886 pkg.cpuAbiOverride = args.abiOverride; 13887 } 13888 13889 String pkgName = res.name = pkg.packageName; 13890 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13891 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13892 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13893 return; 13894 } 13895 } 13896 13897 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13898 try { 13899 PackageParser.collectCertificates(pkg, parseFlags); 13900 } catch (PackageParserException e) { 13901 res.setError("Failed collect during installPackageLI", e); 13902 return; 13903 } finally { 13904 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13905 } 13906 13907 // Get rid of all references to package scan path via parser. 13908 pp = null; 13909 String oldCodePath = null; 13910 boolean systemApp = false; 13911 synchronized (mPackages) { 13912 // Check if installing already existing package 13913 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13914 String oldName = mSettings.mRenamedPackages.get(pkgName); 13915 if (pkg.mOriginalPackages != null 13916 && pkg.mOriginalPackages.contains(oldName) 13917 && mPackages.containsKey(oldName)) { 13918 // This package is derived from an original package, 13919 // and this device has been updating from that original 13920 // name. We must continue using the original name, so 13921 // rename the new package here. 13922 pkg.setPackageName(oldName); 13923 pkgName = pkg.packageName; 13924 replace = true; 13925 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13926 + oldName + " pkgName=" + pkgName); 13927 } else if (mPackages.containsKey(pkgName)) { 13928 // This package, under its official name, already exists 13929 // on the device; we should replace it. 13930 replace = true; 13931 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13932 } 13933 13934 // Child packages are installed through the parent package 13935 if (pkg.parentPackage != null) { 13936 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13937 "Package " + pkg.packageName + " is child of package " 13938 + pkg.parentPackage.parentPackage + ". Child packages " 13939 + "can be updated only through the parent package."); 13940 return; 13941 } 13942 13943 if (replace) { 13944 // Prevent apps opting out from runtime permissions 13945 PackageParser.Package oldPackage = mPackages.get(pkgName); 13946 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13947 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13948 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13949 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13950 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13951 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13952 + " doesn't support runtime permissions but the old" 13953 + " target SDK " + oldTargetSdk + " does."); 13954 return; 13955 } 13956 13957 // Prevent installing of child packages 13958 if (oldPackage.parentPackage != null) { 13959 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13960 "Package " + pkg.packageName + " is child of package " 13961 + oldPackage.parentPackage + ". Child packages " 13962 + "can be updated only through the parent package."); 13963 return; 13964 } 13965 } 13966 } 13967 13968 PackageSetting ps = mSettings.mPackages.get(pkgName); 13969 if (ps != null) { 13970 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13971 13972 // Quick sanity check that we're signed correctly if updating; 13973 // we'll check this again later when scanning, but we want to 13974 // bail early here before tripping over redefined permissions. 13975 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13976 if (!checkUpgradeKeySetLP(ps, pkg)) { 13977 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13978 + pkg.packageName + " upgrade keys do not match the " 13979 + "previously installed version"); 13980 return; 13981 } 13982 } else { 13983 try { 13984 verifySignaturesLP(ps, pkg); 13985 } catch (PackageManagerException e) { 13986 res.setError(e.error, e.getMessage()); 13987 return; 13988 } 13989 } 13990 13991 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13992 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13993 systemApp = (ps.pkg.applicationInfo.flags & 13994 ApplicationInfo.FLAG_SYSTEM) != 0; 13995 } 13996 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13997 } 13998 13999 // Check whether the newly-scanned package wants to define an already-defined perm 14000 int N = pkg.permissions.size(); 14001 for (int i = N-1; i >= 0; i--) { 14002 PackageParser.Permission perm = pkg.permissions.get(i); 14003 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14004 if (bp != null) { 14005 // If the defining package is signed with our cert, it's okay. This 14006 // also includes the "updating the same package" case, of course. 14007 // "updating same package" could also involve key-rotation. 14008 final boolean sigsOk; 14009 if (bp.sourcePackage.equals(pkg.packageName) 14010 && (bp.packageSetting instanceof PackageSetting) 14011 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14012 scanFlags))) { 14013 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14014 } else { 14015 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14016 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14017 } 14018 if (!sigsOk) { 14019 // If the owning package is the system itself, we log but allow 14020 // install to proceed; we fail the install on all other permission 14021 // redefinitions. 14022 if (!bp.sourcePackage.equals("android")) { 14023 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14024 + pkg.packageName + " attempting to redeclare permission " 14025 + perm.info.name + " already owned by " + bp.sourcePackage); 14026 res.origPermission = perm.info.name; 14027 res.origPackage = bp.sourcePackage; 14028 return; 14029 } else { 14030 Slog.w(TAG, "Package " + pkg.packageName 14031 + " attempting to redeclare system permission " 14032 + perm.info.name + "; ignoring new declaration"); 14033 pkg.permissions.remove(i); 14034 } 14035 } 14036 } 14037 } 14038 } 14039 14040 if (systemApp) { 14041 if (onExternal) { 14042 // Abort update; system app can't be replaced with app on sdcard 14043 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14044 "Cannot install updates to system apps on sdcard"); 14045 return; 14046 } else if (ephemeral) { 14047 // Abort update; system app can't be replaced with an ephemeral app 14048 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14049 "Cannot update a system app with an ephemeral app"); 14050 return; 14051 } 14052 } 14053 14054 if (args.move != null) { 14055 // We did an in-place move, so dex is ready to roll 14056 scanFlags |= SCAN_NO_DEX; 14057 scanFlags |= SCAN_MOVE; 14058 14059 synchronized (mPackages) { 14060 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14061 if (ps == null) { 14062 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14063 "Missing settings for moved package " + pkgName); 14064 } 14065 14066 // We moved the entire application as-is, so bring over the 14067 // previously derived ABI information. 14068 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14069 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14070 } 14071 14072 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14073 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14074 scanFlags |= SCAN_NO_DEX; 14075 14076 try { 14077 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14078 args.abiOverride : pkg.cpuAbiOverride); 14079 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14080 true /* extract libs */); 14081 } catch (PackageManagerException pme) { 14082 Slog.e(TAG, "Error deriving application ABI", pme); 14083 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14084 return; 14085 } 14086 14087 14088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14089 // Do not run PackageDexOptimizer through the local performDexOpt 14090 // method because `pkg` is not in `mPackages` yet. 14091 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14092 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14093 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14094 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14095 String msg = "Extracking package failed for " + pkgName; 14096 res.setError(INSTALL_FAILED_DEXOPT, msg); 14097 return; 14098 } 14099 } 14100 14101 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14102 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14103 return; 14104 } 14105 14106 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14107 14108 if (replace) { 14109 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14110 installerPackageName, res); 14111 } else { 14112 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14113 args.user, installerPackageName, volumeUuid, res); 14114 } 14115 synchronized (mPackages) { 14116 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14117 if (ps != null) { 14118 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14119 } 14120 14121 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14122 for (int i = 0; i < childCount; i++) { 14123 PackageParser.Package childPkg = pkg.childPackages.get(i); 14124 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14125 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14126 if (childPs != null) { 14127 childRes.newUsers = childPs.queryInstalledUsers( 14128 sUserManager.getUserIds(), true); 14129 } 14130 } 14131 } 14132 } 14133 14134 private void startIntentFilterVerifications(int userId, boolean replacing, 14135 PackageParser.Package pkg) { 14136 if (mIntentFilterVerifierComponent == null) { 14137 Slog.w(TAG, "No IntentFilter verification will not be done as " 14138 + "there is no IntentFilterVerifier available!"); 14139 return; 14140 } 14141 14142 final int verifierUid = getPackageUid( 14143 mIntentFilterVerifierComponent.getPackageName(), 14144 MATCH_DEBUG_TRIAGED_MISSING, 14145 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14146 14147 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14148 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14149 mHandler.sendMessage(msg); 14150 14151 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14152 for (int i = 0; i < childCount; i++) { 14153 PackageParser.Package childPkg = pkg.childPackages.get(i); 14154 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14155 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14156 mHandler.sendMessage(msg); 14157 } 14158 } 14159 14160 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14161 PackageParser.Package pkg) { 14162 int size = pkg.activities.size(); 14163 if (size == 0) { 14164 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14165 "No activity, so no need to verify any IntentFilter!"); 14166 return; 14167 } 14168 14169 final boolean hasDomainURLs = hasDomainURLs(pkg); 14170 if (!hasDomainURLs) { 14171 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14172 "No domain URLs, so no need to verify any IntentFilter!"); 14173 return; 14174 } 14175 14176 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14177 + " if any IntentFilter from the " + size 14178 + " Activities needs verification ..."); 14179 14180 int count = 0; 14181 final String packageName = pkg.packageName; 14182 14183 synchronized (mPackages) { 14184 // If this is a new install and we see that we've already run verification for this 14185 // package, we have nothing to do: it means the state was restored from backup. 14186 if (!replacing) { 14187 IntentFilterVerificationInfo ivi = 14188 mSettings.getIntentFilterVerificationLPr(packageName); 14189 if (ivi != null) { 14190 if (DEBUG_DOMAIN_VERIFICATION) { 14191 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14192 + ivi.getStatusString()); 14193 } 14194 return; 14195 } 14196 } 14197 14198 // If any filters need to be verified, then all need to be. 14199 boolean needToVerify = false; 14200 for (PackageParser.Activity a : pkg.activities) { 14201 for (ActivityIntentInfo filter : a.intents) { 14202 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14203 if (DEBUG_DOMAIN_VERIFICATION) { 14204 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14205 } 14206 needToVerify = true; 14207 break; 14208 } 14209 } 14210 } 14211 14212 if (needToVerify) { 14213 final int verificationId = mIntentFilterVerificationToken++; 14214 for (PackageParser.Activity a : pkg.activities) { 14215 for (ActivityIntentInfo filter : a.intents) { 14216 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14217 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14218 "Verification needed for IntentFilter:" + filter.toString()); 14219 mIntentFilterVerifier.addOneIntentFilterVerification( 14220 verifierUid, userId, verificationId, filter, packageName); 14221 count++; 14222 } 14223 } 14224 } 14225 } 14226 } 14227 14228 if (count > 0) { 14229 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14230 + " IntentFilter verification" + (count > 1 ? "s" : "") 14231 + " for userId:" + userId); 14232 mIntentFilterVerifier.startVerifications(userId); 14233 } else { 14234 if (DEBUG_DOMAIN_VERIFICATION) { 14235 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14236 } 14237 } 14238 } 14239 14240 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14241 final ComponentName cn = filter.activity.getComponentName(); 14242 final String packageName = cn.getPackageName(); 14243 14244 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14245 packageName); 14246 if (ivi == null) { 14247 return true; 14248 } 14249 int status = ivi.getStatus(); 14250 switch (status) { 14251 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14252 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14253 return true; 14254 14255 default: 14256 // Nothing to do 14257 return false; 14258 } 14259 } 14260 14261 private static boolean isMultiArch(ApplicationInfo info) { 14262 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14263 } 14264 14265 private static boolean isExternal(PackageParser.Package pkg) { 14266 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14267 } 14268 14269 private static boolean isExternal(PackageSetting ps) { 14270 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14271 } 14272 14273 private static boolean isEphemeral(PackageParser.Package pkg) { 14274 return pkg.applicationInfo.isEphemeralApp(); 14275 } 14276 14277 private static boolean isEphemeral(PackageSetting ps) { 14278 return ps.pkg != null && isEphemeral(ps.pkg); 14279 } 14280 14281 private static boolean isSystemApp(PackageParser.Package pkg) { 14282 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14283 } 14284 14285 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14286 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14287 } 14288 14289 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14290 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14291 } 14292 14293 private static boolean isSystemApp(PackageSetting ps) { 14294 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14295 } 14296 14297 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14298 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14299 } 14300 14301 private int packageFlagsToInstallFlags(PackageSetting ps) { 14302 int installFlags = 0; 14303 if (isEphemeral(ps)) { 14304 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14305 } 14306 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14307 // This existing package was an external ASEC install when we have 14308 // the external flag without a UUID 14309 installFlags |= PackageManager.INSTALL_EXTERNAL; 14310 } 14311 if (ps.isForwardLocked()) { 14312 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14313 } 14314 return installFlags; 14315 } 14316 14317 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14318 if (isExternal(pkg)) { 14319 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14320 return StorageManager.UUID_PRIMARY_PHYSICAL; 14321 } else { 14322 return pkg.volumeUuid; 14323 } 14324 } else { 14325 return StorageManager.UUID_PRIVATE_INTERNAL; 14326 } 14327 } 14328 14329 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14330 if (isExternal(pkg)) { 14331 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14332 return mSettings.getExternalVersion(); 14333 } else { 14334 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14335 } 14336 } else { 14337 return mSettings.getInternalVersion(); 14338 } 14339 } 14340 14341 private void deleteTempPackageFiles() { 14342 final FilenameFilter filter = new FilenameFilter() { 14343 public boolean accept(File dir, String name) { 14344 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14345 } 14346 }; 14347 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14348 file.delete(); 14349 } 14350 } 14351 14352 @Override 14353 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14354 int flags) { 14355 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14356 flags); 14357 } 14358 14359 @Override 14360 public void deletePackage(final String packageName, 14361 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14362 mContext.enforceCallingOrSelfPermission( 14363 android.Manifest.permission.DELETE_PACKAGES, null); 14364 Preconditions.checkNotNull(packageName); 14365 Preconditions.checkNotNull(observer); 14366 final int uid = Binder.getCallingUid(); 14367 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14368 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14369 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14370 mContext.enforceCallingOrSelfPermission( 14371 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14372 "deletePackage for user " + userId); 14373 } 14374 14375 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14376 try { 14377 observer.onPackageDeleted(packageName, 14378 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14379 } catch (RemoteException re) { 14380 } 14381 return; 14382 } 14383 14384 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14385 try { 14386 observer.onPackageDeleted(packageName, 14387 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14388 } catch (RemoteException re) { 14389 } 14390 return; 14391 } 14392 14393 if (DEBUG_REMOVE) { 14394 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14395 + " deleteAllUsers: " + deleteAllUsers ); 14396 } 14397 // Queue up an async operation since the package deletion may take a little while. 14398 mHandler.post(new Runnable() { 14399 public void run() { 14400 mHandler.removeCallbacks(this); 14401 int returnCode; 14402 if (!deleteAllUsers) { 14403 returnCode = deletePackageX(packageName, userId, flags); 14404 } else { 14405 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14406 // If nobody is blocking uninstall, proceed with delete for all users 14407 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14408 returnCode = deletePackageX(packageName, userId, flags); 14409 } else { 14410 // Otherwise uninstall individually for users with blockUninstalls=false 14411 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14412 for (int userId : users) { 14413 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14414 returnCode = deletePackageX(packageName, userId, userFlags); 14415 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14416 Slog.w(TAG, "Package delete failed for user " + userId 14417 + ", returnCode " + returnCode); 14418 } 14419 } 14420 } 14421 // The app has only been marked uninstalled for certain users. 14422 // We still need to report that delete was blocked 14423 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14424 } 14425 } 14426 try { 14427 observer.onPackageDeleted(packageName, returnCode, null); 14428 } catch (RemoteException e) { 14429 Log.i(TAG, "Observer no longer exists."); 14430 } //end catch 14431 } //end run 14432 }); 14433 } 14434 14435 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14436 int[] result = EMPTY_INT_ARRAY; 14437 for (int userId : userIds) { 14438 if (getBlockUninstallForUser(packageName, userId)) { 14439 result = ArrayUtils.appendInt(result, userId); 14440 } 14441 } 14442 return result; 14443 } 14444 14445 @Override 14446 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14447 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14448 } 14449 14450 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14451 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14452 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14453 try { 14454 if (dpm != null) { 14455 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14456 /* callingUserOnly =*/ false); 14457 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14458 : deviceOwnerComponentName.getPackageName(); 14459 // Does the package contains the device owner? 14460 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14461 // this check is probably not needed, since DO should be registered as a device 14462 // admin on some user too. (Original bug for this: b/17657954) 14463 if (packageName.equals(deviceOwnerPackageName)) { 14464 return true; 14465 } 14466 // Does it contain a device admin for any user? 14467 int[] users; 14468 if (userId == UserHandle.USER_ALL) { 14469 users = sUserManager.getUserIds(); 14470 } else { 14471 users = new int[]{userId}; 14472 } 14473 for (int i = 0; i < users.length; ++i) { 14474 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14475 return true; 14476 } 14477 } 14478 } 14479 } catch (RemoteException e) { 14480 } 14481 return false; 14482 } 14483 14484 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14485 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14486 } 14487 14488 /** 14489 * This method is an internal method that could be get invoked either 14490 * to delete an installed package or to clean up a failed installation. 14491 * After deleting an installed package, a broadcast is sent to notify any 14492 * listeners that the package has been installed. For cleaning up a failed 14493 * installation, the broadcast is not necessary since the package's 14494 * installation wouldn't have sent the initial broadcast either 14495 * The key steps in deleting a package are 14496 * deleting the package information in internal structures like mPackages, 14497 * deleting the packages base directories through installd 14498 * updating mSettings to reflect current status 14499 * persisting settings for later use 14500 * sending a broadcast if necessary 14501 */ 14502 private int deletePackageX(String packageName, int userId, int flags) { 14503 final PackageRemovedInfo info = new PackageRemovedInfo(); 14504 final boolean res; 14505 14506 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14507 ? UserHandle.ALL : new UserHandle(userId); 14508 14509 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14510 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14511 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14512 } 14513 14514 PackageSetting uninstalledPs = null; 14515 14516 // for the uninstall-updates case and restricted profiles, remember the per- 14517 // user handle installed state 14518 int[] allUsers; 14519 synchronized (mPackages) { 14520 uninstalledPs = mSettings.mPackages.get(packageName); 14521 if (uninstalledPs == null) { 14522 Slog.w(TAG, "Not removing non-existent package " + packageName); 14523 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14524 } 14525 allUsers = sUserManager.getUserIds(); 14526 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14527 } 14528 14529 synchronized (mInstallLock) { 14530 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14531 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14532 flags | REMOVE_CHATTY, info, true, null); 14533 synchronized (mPackages) { 14534 if (res) { 14535 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14536 } 14537 } 14538 } 14539 14540 if (res) { 14541 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14542 info.sendPackageRemovedBroadcasts(killApp); 14543 info.sendSystemPackageUpdatedBroadcasts(); 14544 info.sendSystemPackageAppearedBroadcasts(); 14545 } 14546 // Force a gc here. 14547 Runtime.getRuntime().gc(); 14548 // Delete the resources here after sending the broadcast to let 14549 // other processes clean up before deleting resources. 14550 if (info.args != null) { 14551 synchronized (mInstallLock) { 14552 info.args.doPostDeleteLI(true); 14553 } 14554 } 14555 14556 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14557 } 14558 14559 class PackageRemovedInfo { 14560 String removedPackage; 14561 int uid = -1; 14562 int removedAppId = -1; 14563 int[] origUsers; 14564 int[] removedUsers = null; 14565 boolean isRemovedPackageSystemUpdate = false; 14566 boolean isUpdate; 14567 boolean dataRemoved; 14568 boolean removedForAllUsers; 14569 // Clean up resources deleted packages. 14570 InstallArgs args = null; 14571 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14572 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14573 14574 void sendPackageRemovedBroadcasts(boolean killApp) { 14575 sendPackageRemovedBroadcastInternal(killApp); 14576 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14577 for (int i = 0; i < childCount; i++) { 14578 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14579 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14580 } 14581 } 14582 14583 void sendSystemPackageUpdatedBroadcasts() { 14584 if (isRemovedPackageSystemUpdate) { 14585 sendSystemPackageUpdatedBroadcastsInternal(); 14586 final int childCount = (removedChildPackages != null) 14587 ? removedChildPackages.size() : 0; 14588 for (int i = 0; i < childCount; i++) { 14589 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14590 if (childInfo.isRemovedPackageSystemUpdate) { 14591 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14592 } 14593 } 14594 } 14595 } 14596 14597 void sendSystemPackageAppearedBroadcasts() { 14598 final int packageCount = (appearedChildPackages != null) 14599 ? appearedChildPackages.size() : 0; 14600 for (int i = 0; i < packageCount; i++) { 14601 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14602 for (int userId : installedInfo.newUsers) { 14603 sendPackageAddedForUser(installedInfo.name, true, 14604 UserHandle.getAppId(installedInfo.uid), userId); 14605 } 14606 } 14607 } 14608 14609 private void sendSystemPackageUpdatedBroadcastsInternal() { 14610 Bundle extras = new Bundle(2); 14611 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14612 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14613 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14614 extras, 0, null, null, null); 14615 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14616 extras, 0, null, null, null); 14617 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14618 null, 0, removedPackage, null, null); 14619 } 14620 14621 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14622 Bundle extras = new Bundle(2); 14623 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14624 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14625 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14626 if (isUpdate || isRemovedPackageSystemUpdate) { 14627 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14628 } 14629 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14630 if (removedPackage != null) { 14631 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14632 extras, 0, null, null, removedUsers); 14633 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14634 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14635 removedPackage, extras, 0, null, null, removedUsers); 14636 } 14637 } 14638 if (removedAppId >= 0) { 14639 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14640 removedUsers); 14641 } 14642 } 14643 } 14644 14645 /* 14646 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14647 * flag is not set, the data directory is removed as well. 14648 * make sure this flag is set for partially installed apps. If not its meaningless to 14649 * delete a partially installed application. 14650 */ 14651 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14652 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14653 String packageName = ps.name; 14654 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14655 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14656 // Retrieve object to delete permissions for shared user later on 14657 final PackageSetting deletedPs; 14658 // reader 14659 synchronized (mPackages) { 14660 deletedPs = mSettings.mPackages.get(packageName); 14661 if (outInfo != null) { 14662 outInfo.removedPackage = packageName; 14663 outInfo.removedUsers = deletedPs != null 14664 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14665 : null; 14666 } 14667 } 14668 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14669 removeDataDirsLI(ps.volumeUuid, packageName); 14670 if (outInfo != null) { 14671 outInfo.dataRemoved = true; 14672 } 14673 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14674 } 14675 // writer 14676 synchronized (mPackages) { 14677 if (deletedPs != null) { 14678 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14679 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14680 clearDefaultBrowserIfNeeded(packageName); 14681 if (outInfo != null) { 14682 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14683 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14684 } 14685 updatePermissionsLPw(deletedPs.name, null, 0); 14686 if (deletedPs.sharedUser != null) { 14687 // Remove permissions associated with package. Since runtime 14688 // permissions are per user we have to kill the removed package 14689 // or packages running under the shared user of the removed 14690 // package if revoking the permissions requested only by the removed 14691 // package is successful and this causes a change in gids. 14692 for (int userId : UserManagerService.getInstance().getUserIds()) { 14693 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14694 userId); 14695 if (userIdToKill == UserHandle.USER_ALL 14696 || userIdToKill >= UserHandle.USER_SYSTEM) { 14697 // If gids changed for this user, kill all affected packages. 14698 mHandler.post(new Runnable() { 14699 @Override 14700 public void run() { 14701 // This has to happen with no lock held. 14702 killApplication(deletedPs.name, deletedPs.appId, 14703 KILL_APP_REASON_GIDS_CHANGED); 14704 } 14705 }); 14706 break; 14707 } 14708 } 14709 } 14710 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14711 } 14712 // make sure to preserve per-user disabled state if this removal was just 14713 // a downgrade of a system app to the factory package 14714 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14715 if (DEBUG_REMOVE) { 14716 Slog.d(TAG, "Propagating install state across downgrade"); 14717 } 14718 for (int userId : allUserHandles) { 14719 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14720 if (DEBUG_REMOVE) { 14721 Slog.d(TAG, " user " + userId + " => " + installed); 14722 } 14723 ps.setInstalled(installed, userId); 14724 } 14725 } 14726 } 14727 // can downgrade to reader 14728 if (writeSettings) { 14729 // Save settings now 14730 mSettings.writeLPr(); 14731 } 14732 } 14733 if (outInfo != null) { 14734 // A user ID was deleted here. Go through all users and remove it 14735 // from KeyStore. 14736 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14737 } 14738 } 14739 14740 static boolean locationIsPrivileged(File path) { 14741 try { 14742 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14743 .getCanonicalPath(); 14744 return path.getCanonicalPath().startsWith(privilegedAppDir); 14745 } catch (IOException e) { 14746 Slog.e(TAG, "Unable to access code path " + path); 14747 } 14748 return false; 14749 } 14750 14751 /* 14752 * Tries to delete system package. 14753 */ 14754 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14755 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14756 boolean writeSettings) { 14757 if (deletedPs.parentPackageName != null) { 14758 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14759 return false; 14760 } 14761 14762 final boolean applyUserRestrictions 14763 = (allUserHandles != null) && (outInfo.origUsers != null); 14764 final PackageSetting disabledPs; 14765 // Confirm if the system package has been updated 14766 // An updated system app can be deleted. This will also have to restore 14767 // the system pkg from system partition 14768 // reader 14769 synchronized (mPackages) { 14770 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14771 } 14772 14773 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14774 + " disabledPs=" + disabledPs); 14775 14776 if (disabledPs == null) { 14777 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14778 return false; 14779 } else if (DEBUG_REMOVE) { 14780 Slog.d(TAG, "Deleting system pkg from data partition"); 14781 } 14782 14783 if (DEBUG_REMOVE) { 14784 if (applyUserRestrictions) { 14785 Slog.d(TAG, "Remembering install states:"); 14786 for (int userId : allUserHandles) { 14787 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14788 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14789 } 14790 } 14791 } 14792 14793 // Delete the updated package 14794 outInfo.isRemovedPackageSystemUpdate = true; 14795 if (outInfo.removedChildPackages != null) { 14796 final int childCount = (deletedPs.childPackageNames != null) 14797 ? deletedPs.childPackageNames.size() : 0; 14798 for (int i = 0; i < childCount; i++) { 14799 String childPackageName = deletedPs.childPackageNames.get(i); 14800 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14801 .contains(childPackageName)) { 14802 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14803 childPackageName); 14804 if (childInfo != null) { 14805 childInfo.isRemovedPackageSystemUpdate = true; 14806 } 14807 } 14808 } 14809 } 14810 14811 if (disabledPs.versionCode < deletedPs.versionCode) { 14812 // Delete data for downgrades 14813 flags &= ~PackageManager.DELETE_KEEP_DATA; 14814 } else { 14815 // Preserve data by setting flag 14816 flags |= PackageManager.DELETE_KEEP_DATA; 14817 } 14818 14819 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14820 outInfo, writeSettings, disabledPs.pkg); 14821 if (!ret) { 14822 return false; 14823 } 14824 14825 // writer 14826 synchronized (mPackages) { 14827 // Reinstate the old system package 14828 enableSystemPackageLPw(disabledPs.pkg); 14829 // Remove any native libraries from the upgraded package. 14830 removeNativeBinariesLI(deletedPs); 14831 } 14832 14833 // Install the system package 14834 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14835 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14836 if (locationIsPrivileged(disabledPs.codePath)) { 14837 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14838 } 14839 14840 final PackageParser.Package newPkg; 14841 try { 14842 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14843 } catch (PackageManagerException e) { 14844 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14845 + e.getMessage()); 14846 return false; 14847 } 14848 14849 prepareAppDataAfterInstall(newPkg); 14850 14851 // writer 14852 synchronized (mPackages) { 14853 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14854 14855 // Propagate the permissions state as we do not want to drop on the floor 14856 // runtime permissions. The update permissions method below will take 14857 // care of removing obsolete permissions and grant install permissions. 14858 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14859 updatePermissionsLPw(newPkg.packageName, newPkg, 14860 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14861 14862 if (applyUserRestrictions) { 14863 if (DEBUG_REMOVE) { 14864 Slog.d(TAG, "Propagating install state across reinstall"); 14865 } 14866 for (int userId : allUserHandles) { 14867 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14868 if (DEBUG_REMOVE) { 14869 Slog.d(TAG, " user " + userId + " => " + installed); 14870 } 14871 ps.setInstalled(installed, userId); 14872 14873 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14874 } 14875 // Regardless of writeSettings we need to ensure that this restriction 14876 // state propagation is persisted 14877 mSettings.writeAllUsersPackageRestrictionsLPr(); 14878 } 14879 // can downgrade to reader here 14880 if (writeSettings) { 14881 mSettings.writeLPr(); 14882 } 14883 } 14884 return true; 14885 } 14886 14887 private boolean deleteInstalledPackageLI(PackageSetting ps, 14888 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14889 PackageRemovedInfo outInfo, boolean writeSettings, 14890 PackageParser.Package replacingPackage) { 14891 synchronized (mPackages) { 14892 if (outInfo != null) { 14893 outInfo.uid = ps.appId; 14894 } 14895 14896 if (outInfo != null && outInfo.removedChildPackages != null) { 14897 final int childCount = (ps.childPackageNames != null) 14898 ? ps.childPackageNames.size() : 0; 14899 for (int i = 0; i < childCount; i++) { 14900 String childPackageName = ps.childPackageNames.get(i); 14901 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14902 if (childPs == null) { 14903 return false; 14904 } 14905 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14906 childPackageName); 14907 if (childInfo != null) { 14908 childInfo.uid = childPs.appId; 14909 } 14910 } 14911 } 14912 } 14913 14914 // Delete package data from internal structures and also remove data if flag is set 14915 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14916 14917 // Delete the child packages data 14918 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14919 for (int i = 0; i < childCount; i++) { 14920 PackageSetting childPs; 14921 synchronized (mPackages) { 14922 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14923 } 14924 if (childPs != null) { 14925 PackageRemovedInfo childOutInfo = (outInfo != null 14926 && outInfo.removedChildPackages != null) 14927 ? outInfo.removedChildPackages.get(childPs.name) : null; 14928 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14929 && (replacingPackage != null 14930 && !replacingPackage.hasChildPackage(childPs.name)) 14931 ? flags & ~DELETE_KEEP_DATA : flags; 14932 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14933 deleteFlags, writeSettings); 14934 } 14935 } 14936 14937 // Delete application code and resources only for parent packages 14938 if (ps.parentPackageName == null) { 14939 if (deleteCodeAndResources && (outInfo != null)) { 14940 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14941 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14942 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14943 } 14944 } 14945 14946 return true; 14947 } 14948 14949 @Override 14950 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14951 int userId) { 14952 mContext.enforceCallingOrSelfPermission( 14953 android.Manifest.permission.DELETE_PACKAGES, null); 14954 synchronized (mPackages) { 14955 PackageSetting ps = mSettings.mPackages.get(packageName); 14956 if (ps == null) { 14957 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14958 return false; 14959 } 14960 if (!ps.getInstalled(userId)) { 14961 // Can't block uninstall for an app that is not installed or enabled. 14962 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14963 return false; 14964 } 14965 ps.setBlockUninstall(blockUninstall, userId); 14966 mSettings.writePackageRestrictionsLPr(userId); 14967 } 14968 return true; 14969 } 14970 14971 @Override 14972 public boolean getBlockUninstallForUser(String packageName, int userId) { 14973 synchronized (mPackages) { 14974 PackageSetting ps = mSettings.mPackages.get(packageName); 14975 if (ps == null) { 14976 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14977 return false; 14978 } 14979 return ps.getBlockUninstall(userId); 14980 } 14981 } 14982 14983 @Override 14984 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14985 int callingUid = Binder.getCallingUid(); 14986 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14987 throw new SecurityException( 14988 "setRequiredForSystemUser can only be run by the system or root"); 14989 } 14990 synchronized (mPackages) { 14991 PackageSetting ps = mSettings.mPackages.get(packageName); 14992 if (ps == null) { 14993 Log.w(TAG, "Package doesn't exist: " + packageName); 14994 return false; 14995 } 14996 if (systemUserApp) { 14997 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14998 } else { 14999 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15000 } 15001 mSettings.writeLPr(); 15002 } 15003 return true; 15004 } 15005 15006 /* 15007 * This method handles package deletion in general 15008 */ 15009 private boolean deletePackageLI(String packageName, UserHandle user, 15010 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15011 PackageRemovedInfo outInfo, boolean writeSettings, 15012 PackageParser.Package replacingPackage) { 15013 if (packageName == null) { 15014 Slog.w(TAG, "Attempt to delete null packageName."); 15015 return false; 15016 } 15017 15018 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15019 15020 PackageSetting ps; 15021 15022 synchronized (mPackages) { 15023 ps = mSettings.mPackages.get(packageName); 15024 if (ps == null) { 15025 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15026 return false; 15027 } 15028 15029 if (ps.parentPackageName != null && (!isSystemApp(ps) 15030 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15031 if (DEBUG_REMOVE) { 15032 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15033 + ((user == null) ? UserHandle.USER_ALL : user)); 15034 } 15035 final int removedUserId = (user != null) ? user.getIdentifier() 15036 : UserHandle.USER_ALL; 15037 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15038 return false; 15039 } 15040 markPackageUninstalledForUserLPw(ps, user); 15041 scheduleWritePackageRestrictionsLocked(user); 15042 return true; 15043 } 15044 } 15045 15046 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15047 && user.getIdentifier() != UserHandle.USER_ALL)) { 15048 // The caller is asking that the package only be deleted for a single 15049 // user. To do this, we just mark its uninstalled state and delete 15050 // its data. If this is a system app, we only allow this to happen if 15051 // they have set the special DELETE_SYSTEM_APP which requests different 15052 // semantics than normal for uninstalling system apps. 15053 markPackageUninstalledForUserLPw(ps, user); 15054 15055 if (!isSystemApp(ps)) { 15056 // Do not uninstall the APK if an app should be cached 15057 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15058 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15059 // Other user still have this package installed, so all 15060 // we need to do is clear this user's data and save that 15061 // it is uninstalled. 15062 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15063 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15064 return false; 15065 } 15066 scheduleWritePackageRestrictionsLocked(user); 15067 return true; 15068 } else { 15069 // We need to set it back to 'installed' so the uninstall 15070 // broadcasts will be sent correctly. 15071 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15072 ps.setInstalled(true, user.getIdentifier()); 15073 } 15074 } else { 15075 // This is a system app, so we assume that the 15076 // other users still have this package installed, so all 15077 // we need to do is clear this user's data and save that 15078 // it is uninstalled. 15079 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15080 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15081 return false; 15082 } 15083 scheduleWritePackageRestrictionsLocked(user); 15084 return true; 15085 } 15086 } 15087 15088 // If we are deleting a composite package for all users, keep track 15089 // of result for each child. 15090 if (ps.childPackageNames != null && outInfo != null) { 15091 synchronized (mPackages) { 15092 final int childCount = ps.childPackageNames.size(); 15093 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15094 for (int i = 0; i < childCount; i++) { 15095 String childPackageName = ps.childPackageNames.get(i); 15096 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15097 childInfo.removedPackage = childPackageName; 15098 outInfo.removedChildPackages.put(childPackageName, childInfo); 15099 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15100 if (childPs != null) { 15101 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15102 } 15103 } 15104 } 15105 } 15106 15107 boolean ret = false; 15108 if (isSystemApp(ps)) { 15109 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15110 // When an updated system application is deleted we delete the existing resources 15111 // as well and fall back to existing code in system partition 15112 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15113 } else { 15114 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15115 // Kill application pre-emptively especially for apps on sd. 15116 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15117 if (killApp) { 15118 killApplication(packageName, ps.appId, "uninstall pkg"); 15119 } 15120 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15121 outInfo, writeSettings, replacingPackage); 15122 } 15123 15124 // Take a note whether we deleted the package for all users 15125 if (outInfo != null) { 15126 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15127 if (outInfo.removedChildPackages != null) { 15128 synchronized (mPackages) { 15129 final int childCount = outInfo.removedChildPackages.size(); 15130 for (int i = 0; i < childCount; i++) { 15131 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15132 if (childInfo != null) { 15133 childInfo.removedForAllUsers = mPackages.get( 15134 childInfo.removedPackage) == null; 15135 } 15136 } 15137 } 15138 } 15139 // If we uninstalled an update to a system app there may be some 15140 // child packages that appeared as they are declared in the system 15141 // app but were not declared in the update. 15142 if (isSystemApp(ps)) { 15143 synchronized (mPackages) { 15144 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15145 final int childCount = (updatedPs.childPackageNames != null) 15146 ? updatedPs.childPackageNames.size() : 0; 15147 for (int i = 0; i < childCount; i++) { 15148 String childPackageName = updatedPs.childPackageNames.get(i); 15149 if (outInfo.removedChildPackages == null 15150 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15151 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15152 if (childPs == null) { 15153 continue; 15154 } 15155 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15156 installRes.name = childPackageName; 15157 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15158 installRes.pkg = mPackages.get(childPackageName); 15159 installRes.uid = childPs.pkg.applicationInfo.uid; 15160 if (outInfo.appearedChildPackages == null) { 15161 outInfo.appearedChildPackages = new ArrayMap<>(); 15162 } 15163 outInfo.appearedChildPackages.put(childPackageName, installRes); 15164 } 15165 } 15166 } 15167 } 15168 } 15169 15170 return ret; 15171 } 15172 15173 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15174 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15175 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15176 for (int nextUserId : userIds) { 15177 if (DEBUG_REMOVE) { 15178 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15179 } 15180 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15181 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15182 false /*hidden*/, false /*suspended*/, null, null, null, 15183 false /*blockUninstall*/, 15184 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15185 } 15186 } 15187 15188 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15189 PackageRemovedInfo outInfo) { 15190 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15191 : new int[] {userId}; 15192 for (int nextUserId : userIds) { 15193 if (DEBUG_REMOVE) { 15194 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15195 + nextUserId); 15196 } 15197 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15198 try { 15199 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15200 } catch (InstallerException e) { 15201 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15202 return false; 15203 } 15204 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15205 schedulePackageCleaning(ps.name, nextUserId, false); 15206 synchronized (mPackages) { 15207 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15208 scheduleWritePackageRestrictionsLocked(nextUserId); 15209 } 15210 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15211 } 15212 } 15213 15214 if (outInfo != null) { 15215 outInfo.removedPackage = ps.name; 15216 outInfo.removedAppId = ps.appId; 15217 outInfo.removedUsers = userIds; 15218 } 15219 15220 return true; 15221 } 15222 15223 private final class ClearStorageConnection implements ServiceConnection { 15224 IMediaContainerService mContainerService; 15225 15226 @Override 15227 public void onServiceConnected(ComponentName name, IBinder service) { 15228 synchronized (this) { 15229 mContainerService = IMediaContainerService.Stub.asInterface(service); 15230 notifyAll(); 15231 } 15232 } 15233 15234 @Override 15235 public void onServiceDisconnected(ComponentName name) { 15236 } 15237 } 15238 15239 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15240 final boolean mounted; 15241 if (Environment.isExternalStorageEmulated()) { 15242 mounted = true; 15243 } else { 15244 final String status = Environment.getExternalStorageState(); 15245 15246 mounted = status.equals(Environment.MEDIA_MOUNTED) 15247 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15248 } 15249 15250 if (!mounted) { 15251 return; 15252 } 15253 15254 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15255 int[] users; 15256 if (userId == UserHandle.USER_ALL) { 15257 users = sUserManager.getUserIds(); 15258 } else { 15259 users = new int[] { userId }; 15260 } 15261 final ClearStorageConnection conn = new ClearStorageConnection(); 15262 if (mContext.bindServiceAsUser( 15263 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15264 try { 15265 for (int curUser : users) { 15266 long timeout = SystemClock.uptimeMillis() + 5000; 15267 synchronized (conn) { 15268 long now = SystemClock.uptimeMillis(); 15269 while (conn.mContainerService == null && now < timeout) { 15270 try { 15271 conn.wait(timeout - now); 15272 } catch (InterruptedException e) { 15273 } 15274 } 15275 } 15276 if (conn.mContainerService == null) { 15277 return; 15278 } 15279 15280 final UserEnvironment userEnv = new UserEnvironment(curUser); 15281 clearDirectory(conn.mContainerService, 15282 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15283 if (allData) { 15284 clearDirectory(conn.mContainerService, 15285 userEnv.buildExternalStorageAppDataDirs(packageName)); 15286 clearDirectory(conn.mContainerService, 15287 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15288 } 15289 } 15290 } finally { 15291 mContext.unbindService(conn); 15292 } 15293 } 15294 } 15295 15296 @Override 15297 public void clearApplicationProfileData(String packageName) { 15298 enforceSystemOrRoot("Only the system can clear all profile data"); 15299 try { 15300 mInstaller.clearAppProfiles(packageName); 15301 } catch (InstallerException ex) { 15302 Log.e(TAG, "Could not clear profile data of package " + packageName); 15303 } 15304 } 15305 15306 @Override 15307 public void clearApplicationUserData(final String packageName, 15308 final IPackageDataObserver observer, final int userId) { 15309 mContext.enforceCallingOrSelfPermission( 15310 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15311 15312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15313 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15314 15315 final DevicePolicyManagerInternal dpmi = LocalServices 15316 .getService(DevicePolicyManagerInternal.class); 15317 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15318 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15319 } 15320 // Queue up an async operation since the package deletion may take a little while. 15321 mHandler.post(new Runnable() { 15322 public void run() { 15323 mHandler.removeCallbacks(this); 15324 final boolean succeeded; 15325 synchronized (mInstallLock) { 15326 succeeded = clearApplicationUserDataLI(packageName, userId); 15327 } 15328 clearExternalStorageDataSync(packageName, userId, true); 15329 if (succeeded) { 15330 // invoke DeviceStorageMonitor's update method to clear any notifications 15331 DeviceStorageMonitorInternal dsm = LocalServices 15332 .getService(DeviceStorageMonitorInternal.class); 15333 if (dsm != null) { 15334 dsm.checkMemory(); 15335 } 15336 } 15337 if(observer != null) { 15338 try { 15339 observer.onRemoveCompleted(packageName, succeeded); 15340 } catch (RemoteException e) { 15341 Log.i(TAG, "Observer no longer exists."); 15342 } 15343 } //end if observer 15344 } //end run 15345 }); 15346 } 15347 15348 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15349 if (packageName == null) { 15350 Slog.w(TAG, "Attempt to delete null packageName."); 15351 return false; 15352 } 15353 15354 // Try finding details about the requested package 15355 PackageParser.Package pkg; 15356 synchronized (mPackages) { 15357 pkg = mPackages.get(packageName); 15358 if (pkg == null) { 15359 final PackageSetting ps = mSettings.mPackages.get(packageName); 15360 if (ps != null) { 15361 pkg = ps.pkg; 15362 } 15363 } 15364 15365 if (pkg == null) { 15366 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15367 return false; 15368 } 15369 15370 PackageSetting ps = (PackageSetting) pkg.mExtras; 15371 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15372 } 15373 15374 // Always delete data directories for package, even if we found no other 15375 // record of app. This helps users recover from UID mismatches without 15376 // resorting to a full data wipe. 15377 // TODO: triage flags as part of 26466827 15378 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15379 try { 15380 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15381 } catch (InstallerException e) { 15382 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15383 return false; 15384 } 15385 15386 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15387 removeKeystoreDataIfNeeded(userId, appId); 15388 15389 // Create a native library symlink only if we have native libraries 15390 // and if the native libraries are 32 bit libraries. We do not provide 15391 // this symlink for 64 bit libraries. 15392 if (pkg.applicationInfo.primaryCpuAbi != null && 15393 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15394 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15395 try { 15396 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15397 nativeLibPath, userId); 15398 } catch (InstallerException e) { 15399 Slog.w(TAG, "Failed linking native library dir", e); 15400 return false; 15401 } 15402 } 15403 15404 return true; 15405 } 15406 15407 /** 15408 * Reverts user permission state changes (permissions and flags) in 15409 * all packages for a given user. 15410 * 15411 * @param userId The device user for which to do a reset. 15412 */ 15413 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15414 final int packageCount = mPackages.size(); 15415 for (int i = 0; i < packageCount; i++) { 15416 PackageParser.Package pkg = mPackages.valueAt(i); 15417 PackageSetting ps = (PackageSetting) pkg.mExtras; 15418 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15419 } 15420 } 15421 15422 /** 15423 * Reverts user permission state changes (permissions and flags). 15424 * 15425 * @param ps The package for which to reset. 15426 * @param userId The device user for which to do a reset. 15427 */ 15428 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15429 final PackageSetting ps, final int userId) { 15430 if (ps.pkg == null) { 15431 return; 15432 } 15433 15434 // These are flags that can change base on user actions. 15435 final int userSettableMask = FLAG_PERMISSION_USER_SET 15436 | FLAG_PERMISSION_USER_FIXED 15437 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15438 | FLAG_PERMISSION_REVIEW_REQUIRED; 15439 15440 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15441 | FLAG_PERMISSION_POLICY_FIXED; 15442 15443 boolean writeInstallPermissions = false; 15444 boolean writeRuntimePermissions = false; 15445 15446 final int permissionCount = ps.pkg.requestedPermissions.size(); 15447 for (int i = 0; i < permissionCount; i++) { 15448 String permission = ps.pkg.requestedPermissions.get(i); 15449 15450 BasePermission bp = mSettings.mPermissions.get(permission); 15451 if (bp == null) { 15452 continue; 15453 } 15454 15455 // If shared user we just reset the state to which only this app contributed. 15456 if (ps.sharedUser != null) { 15457 boolean used = false; 15458 final int packageCount = ps.sharedUser.packages.size(); 15459 for (int j = 0; j < packageCount; j++) { 15460 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15461 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15462 && pkg.pkg.requestedPermissions.contains(permission)) { 15463 used = true; 15464 break; 15465 } 15466 } 15467 if (used) { 15468 continue; 15469 } 15470 } 15471 15472 PermissionsState permissionsState = ps.getPermissionsState(); 15473 15474 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15475 15476 // Always clear the user settable flags. 15477 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15478 bp.name) != null; 15479 // If permission review is enabled and this is a legacy app, mark the 15480 // permission as requiring a review as this is the initial state. 15481 int flags = 0; 15482 if (Build.PERMISSIONS_REVIEW_REQUIRED 15483 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15484 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15485 } 15486 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15487 if (hasInstallState) { 15488 writeInstallPermissions = true; 15489 } else { 15490 writeRuntimePermissions = true; 15491 } 15492 } 15493 15494 // Below is only runtime permission handling. 15495 if (!bp.isRuntime()) { 15496 continue; 15497 } 15498 15499 // Never clobber system or policy. 15500 if ((oldFlags & policyOrSystemFlags) != 0) { 15501 continue; 15502 } 15503 15504 // If this permission was granted by default, make sure it is. 15505 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15506 if (permissionsState.grantRuntimePermission(bp, userId) 15507 != PERMISSION_OPERATION_FAILURE) { 15508 writeRuntimePermissions = true; 15509 } 15510 // If permission review is enabled the permissions for a legacy apps 15511 // are represented as constantly granted runtime ones, so don't revoke. 15512 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15513 // Otherwise, reset the permission. 15514 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15515 switch (revokeResult) { 15516 case PERMISSION_OPERATION_SUCCESS: { 15517 writeRuntimePermissions = true; 15518 } break; 15519 15520 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15521 writeRuntimePermissions = true; 15522 final int appId = ps.appId; 15523 mHandler.post(new Runnable() { 15524 @Override 15525 public void run() { 15526 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15527 } 15528 }); 15529 } break; 15530 } 15531 } 15532 } 15533 15534 // Synchronously write as we are taking permissions away. 15535 if (writeRuntimePermissions) { 15536 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15537 } 15538 15539 // Synchronously write as we are taking permissions away. 15540 if (writeInstallPermissions) { 15541 mSettings.writeLPr(); 15542 } 15543 } 15544 15545 /** 15546 * Remove entries from the keystore daemon. Will only remove it if the 15547 * {@code appId} is valid. 15548 */ 15549 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15550 if (appId < 0) { 15551 return; 15552 } 15553 15554 final KeyStore keyStore = KeyStore.getInstance(); 15555 if (keyStore != null) { 15556 if (userId == UserHandle.USER_ALL) { 15557 for (final int individual : sUserManager.getUserIds()) { 15558 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15559 } 15560 } else { 15561 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15562 } 15563 } else { 15564 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15565 } 15566 } 15567 15568 @Override 15569 public void deleteApplicationCacheFiles(final String packageName, 15570 final IPackageDataObserver observer) { 15571 mContext.enforceCallingOrSelfPermission( 15572 android.Manifest.permission.DELETE_CACHE_FILES, null); 15573 // Queue up an async operation since the package deletion may take a little while. 15574 final int userId = UserHandle.getCallingUserId(); 15575 mHandler.post(new Runnable() { 15576 public void run() { 15577 mHandler.removeCallbacks(this); 15578 final boolean succeded; 15579 synchronized (mInstallLock) { 15580 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15581 } 15582 clearExternalStorageDataSync(packageName, userId, false); 15583 if (observer != null) { 15584 try { 15585 observer.onRemoveCompleted(packageName, succeded); 15586 } catch (RemoteException e) { 15587 Log.i(TAG, "Observer no longer exists."); 15588 } 15589 } //end if observer 15590 } //end run 15591 }); 15592 } 15593 15594 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15595 if (packageName == null) { 15596 Slog.w(TAG, "Attempt to delete null packageName."); 15597 return false; 15598 } 15599 PackageParser.Package p; 15600 synchronized (mPackages) { 15601 p = mPackages.get(packageName); 15602 } 15603 if (p == null) { 15604 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15605 return false; 15606 } 15607 final ApplicationInfo applicationInfo = p.applicationInfo; 15608 if (applicationInfo == null) { 15609 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15610 return false; 15611 } 15612 // TODO: triage flags as part of 26466827 15613 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15614 try { 15615 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15616 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15617 } catch (InstallerException e) { 15618 Slog.w(TAG, "Couldn't remove cache files for package " 15619 + packageName + " u" + userId, e); 15620 return false; 15621 } 15622 return true; 15623 } 15624 15625 @Override 15626 public void getPackageSizeInfo(final String packageName, int userHandle, 15627 final IPackageStatsObserver observer) { 15628 mContext.enforceCallingOrSelfPermission( 15629 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15630 if (packageName == null) { 15631 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15632 } 15633 15634 PackageStats stats = new PackageStats(packageName, userHandle); 15635 15636 /* 15637 * Queue up an async operation since the package measurement may take a 15638 * little while. 15639 */ 15640 Message msg = mHandler.obtainMessage(INIT_COPY); 15641 msg.obj = new MeasureParams(stats, observer); 15642 mHandler.sendMessage(msg); 15643 } 15644 15645 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15646 PackageStats pStats) { 15647 if (packageName == null) { 15648 Slog.w(TAG, "Attempt to get size of null packageName."); 15649 return false; 15650 } 15651 PackageParser.Package p; 15652 boolean dataOnly = false; 15653 String libDirRoot = null; 15654 String asecPath = null; 15655 PackageSetting ps = null; 15656 synchronized (mPackages) { 15657 p = mPackages.get(packageName); 15658 ps = mSettings.mPackages.get(packageName); 15659 if(p == null) { 15660 dataOnly = true; 15661 if((ps == null) || (ps.pkg == null)) { 15662 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15663 return false; 15664 } 15665 p = ps.pkg; 15666 } 15667 if (ps != null) { 15668 libDirRoot = ps.legacyNativeLibraryPathString; 15669 } 15670 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15671 final long token = Binder.clearCallingIdentity(); 15672 try { 15673 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15674 if (secureContainerId != null) { 15675 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15676 } 15677 } finally { 15678 Binder.restoreCallingIdentity(token); 15679 } 15680 } 15681 } 15682 String publicSrcDir = null; 15683 if(!dataOnly) { 15684 final ApplicationInfo applicationInfo = p.applicationInfo; 15685 if (applicationInfo == null) { 15686 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15687 return false; 15688 } 15689 if (p.isForwardLocked()) { 15690 publicSrcDir = applicationInfo.getBaseResourcePath(); 15691 } 15692 } 15693 // TODO: extend to measure size of split APKs 15694 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15695 // not just the first level. 15696 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15697 // just the primary. 15698 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15699 15700 String apkPath; 15701 File packageDir = new File(p.codePath); 15702 15703 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15704 apkPath = packageDir.getAbsolutePath(); 15705 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15706 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15707 libDirRoot = null; 15708 } 15709 } else { 15710 apkPath = p.baseCodePath; 15711 } 15712 15713 // TODO: triage flags as part of 26466827 15714 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15715 try { 15716 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15717 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15718 } catch (InstallerException e) { 15719 return false; 15720 } 15721 15722 // Fix-up for forward-locked applications in ASEC containers. 15723 if (!isExternal(p)) { 15724 pStats.codeSize += pStats.externalCodeSize; 15725 pStats.externalCodeSize = 0L; 15726 } 15727 15728 return true; 15729 } 15730 15731 private int getUidTargetSdkVersionLockedLPr(int uid) { 15732 Object obj = mSettings.getUserIdLPr(uid); 15733 if (obj instanceof SharedUserSetting) { 15734 final SharedUserSetting sus = (SharedUserSetting) obj; 15735 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15736 final Iterator<PackageSetting> it = sus.packages.iterator(); 15737 while (it.hasNext()) { 15738 final PackageSetting ps = it.next(); 15739 if (ps.pkg != null) { 15740 int v = ps.pkg.applicationInfo.targetSdkVersion; 15741 if (v < vers) vers = v; 15742 } 15743 } 15744 return vers; 15745 } else if (obj instanceof PackageSetting) { 15746 final PackageSetting ps = (PackageSetting) obj; 15747 if (ps.pkg != null) { 15748 return ps.pkg.applicationInfo.targetSdkVersion; 15749 } 15750 } 15751 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15752 } 15753 15754 @Override 15755 public void addPreferredActivity(IntentFilter filter, int match, 15756 ComponentName[] set, ComponentName activity, int userId) { 15757 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15758 "Adding preferred"); 15759 } 15760 15761 private void addPreferredActivityInternal(IntentFilter filter, int match, 15762 ComponentName[] set, ComponentName activity, boolean always, int userId, 15763 String opname) { 15764 // writer 15765 int callingUid = Binder.getCallingUid(); 15766 enforceCrossUserPermission(callingUid, userId, 15767 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15768 if (filter.countActions() == 0) { 15769 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15770 return; 15771 } 15772 synchronized (mPackages) { 15773 if (mContext.checkCallingOrSelfPermission( 15774 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15775 != PackageManager.PERMISSION_GRANTED) { 15776 if (getUidTargetSdkVersionLockedLPr(callingUid) 15777 < Build.VERSION_CODES.FROYO) { 15778 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15779 + callingUid); 15780 return; 15781 } 15782 mContext.enforceCallingOrSelfPermission( 15783 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15784 } 15785 15786 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15787 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15788 + userId + ":"); 15789 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15790 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15791 scheduleWritePackageRestrictionsLocked(userId); 15792 } 15793 } 15794 15795 @Override 15796 public void replacePreferredActivity(IntentFilter filter, int match, 15797 ComponentName[] set, ComponentName activity, int userId) { 15798 if (filter.countActions() != 1) { 15799 throw new IllegalArgumentException( 15800 "replacePreferredActivity expects filter to have only 1 action."); 15801 } 15802 if (filter.countDataAuthorities() != 0 15803 || filter.countDataPaths() != 0 15804 || filter.countDataSchemes() > 1 15805 || filter.countDataTypes() != 0) { 15806 throw new IllegalArgumentException( 15807 "replacePreferredActivity expects filter to have no data authorities, " + 15808 "paths, or types; and at most one scheme."); 15809 } 15810 15811 final int callingUid = Binder.getCallingUid(); 15812 enforceCrossUserPermission(callingUid, userId, 15813 true /* requireFullPermission */, false /* checkShell */, 15814 "replace preferred activity"); 15815 synchronized (mPackages) { 15816 if (mContext.checkCallingOrSelfPermission( 15817 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15818 != PackageManager.PERMISSION_GRANTED) { 15819 if (getUidTargetSdkVersionLockedLPr(callingUid) 15820 < Build.VERSION_CODES.FROYO) { 15821 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15822 + Binder.getCallingUid()); 15823 return; 15824 } 15825 mContext.enforceCallingOrSelfPermission( 15826 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15827 } 15828 15829 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15830 if (pir != null) { 15831 // Get all of the existing entries that exactly match this filter. 15832 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15833 if (existing != null && existing.size() == 1) { 15834 PreferredActivity cur = existing.get(0); 15835 if (DEBUG_PREFERRED) { 15836 Slog.i(TAG, "Checking replace of preferred:"); 15837 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15838 if (!cur.mPref.mAlways) { 15839 Slog.i(TAG, " -- CUR; not mAlways!"); 15840 } else { 15841 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15842 Slog.i(TAG, " -- CUR: mSet=" 15843 + Arrays.toString(cur.mPref.mSetComponents)); 15844 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15845 Slog.i(TAG, " -- NEW: mMatch=" 15846 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15847 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15848 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15849 } 15850 } 15851 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15852 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15853 && cur.mPref.sameSet(set)) { 15854 // Setting the preferred activity to what it happens to be already 15855 if (DEBUG_PREFERRED) { 15856 Slog.i(TAG, "Replacing with same preferred activity " 15857 + cur.mPref.mShortComponent + " for user " 15858 + userId + ":"); 15859 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15860 } 15861 return; 15862 } 15863 } 15864 15865 if (existing != null) { 15866 if (DEBUG_PREFERRED) { 15867 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15868 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15869 } 15870 for (int i = 0; i < existing.size(); i++) { 15871 PreferredActivity pa = existing.get(i); 15872 if (DEBUG_PREFERRED) { 15873 Slog.i(TAG, "Removing existing preferred activity " 15874 + pa.mPref.mComponent + ":"); 15875 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15876 } 15877 pir.removeFilter(pa); 15878 } 15879 } 15880 } 15881 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15882 "Replacing preferred"); 15883 } 15884 } 15885 15886 @Override 15887 public void clearPackagePreferredActivities(String packageName) { 15888 final int uid = Binder.getCallingUid(); 15889 // writer 15890 synchronized (mPackages) { 15891 PackageParser.Package pkg = mPackages.get(packageName); 15892 if (pkg == null || pkg.applicationInfo.uid != uid) { 15893 if (mContext.checkCallingOrSelfPermission( 15894 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15895 != PackageManager.PERMISSION_GRANTED) { 15896 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15897 < Build.VERSION_CODES.FROYO) { 15898 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15899 + Binder.getCallingUid()); 15900 return; 15901 } 15902 mContext.enforceCallingOrSelfPermission( 15903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15904 } 15905 } 15906 15907 int user = UserHandle.getCallingUserId(); 15908 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15909 scheduleWritePackageRestrictionsLocked(user); 15910 } 15911 } 15912 } 15913 15914 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15915 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15916 ArrayList<PreferredActivity> removed = null; 15917 boolean changed = false; 15918 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15919 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15920 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15921 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15922 continue; 15923 } 15924 Iterator<PreferredActivity> it = pir.filterIterator(); 15925 while (it.hasNext()) { 15926 PreferredActivity pa = it.next(); 15927 // Mark entry for removal only if it matches the package name 15928 // and the entry is of type "always". 15929 if (packageName == null || 15930 (pa.mPref.mComponent.getPackageName().equals(packageName) 15931 && pa.mPref.mAlways)) { 15932 if (removed == null) { 15933 removed = new ArrayList<PreferredActivity>(); 15934 } 15935 removed.add(pa); 15936 } 15937 } 15938 if (removed != null) { 15939 for (int j=0; j<removed.size(); j++) { 15940 PreferredActivity pa = removed.get(j); 15941 pir.removeFilter(pa); 15942 } 15943 changed = true; 15944 } 15945 } 15946 return changed; 15947 } 15948 15949 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15950 private void clearIntentFilterVerificationsLPw(int userId) { 15951 final int packageCount = mPackages.size(); 15952 for (int i = 0; i < packageCount; i++) { 15953 PackageParser.Package pkg = mPackages.valueAt(i); 15954 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15955 } 15956 } 15957 15958 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15959 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15960 if (userId == UserHandle.USER_ALL) { 15961 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15962 sUserManager.getUserIds())) { 15963 for (int oneUserId : sUserManager.getUserIds()) { 15964 scheduleWritePackageRestrictionsLocked(oneUserId); 15965 } 15966 } 15967 } else { 15968 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15969 scheduleWritePackageRestrictionsLocked(userId); 15970 } 15971 } 15972 } 15973 15974 void clearDefaultBrowserIfNeeded(String packageName) { 15975 for (int oneUserId : sUserManager.getUserIds()) { 15976 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15977 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15978 if (packageName.equals(defaultBrowserPackageName)) { 15979 setDefaultBrowserPackageName(null, oneUserId); 15980 } 15981 } 15982 } 15983 15984 @Override 15985 public void resetApplicationPreferences(int userId) { 15986 mContext.enforceCallingOrSelfPermission( 15987 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15988 // writer 15989 synchronized (mPackages) { 15990 final long identity = Binder.clearCallingIdentity(); 15991 try { 15992 clearPackagePreferredActivitiesLPw(null, userId); 15993 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15994 // TODO: We have to reset the default SMS and Phone. This requires 15995 // significant refactoring to keep all default apps in the package 15996 // manager (cleaner but more work) or have the services provide 15997 // callbacks to the package manager to request a default app reset. 15998 applyFactoryDefaultBrowserLPw(userId); 15999 clearIntentFilterVerificationsLPw(userId); 16000 primeDomainVerificationsLPw(userId); 16001 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16002 scheduleWritePackageRestrictionsLocked(userId); 16003 } finally { 16004 Binder.restoreCallingIdentity(identity); 16005 } 16006 } 16007 } 16008 16009 @Override 16010 public int getPreferredActivities(List<IntentFilter> outFilters, 16011 List<ComponentName> outActivities, String packageName) { 16012 16013 int num = 0; 16014 final int userId = UserHandle.getCallingUserId(); 16015 // reader 16016 synchronized (mPackages) { 16017 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16018 if (pir != null) { 16019 final Iterator<PreferredActivity> it = pir.filterIterator(); 16020 while (it.hasNext()) { 16021 final PreferredActivity pa = it.next(); 16022 if (packageName == null 16023 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16024 && pa.mPref.mAlways)) { 16025 if (outFilters != null) { 16026 outFilters.add(new IntentFilter(pa)); 16027 } 16028 if (outActivities != null) { 16029 outActivities.add(pa.mPref.mComponent); 16030 } 16031 } 16032 } 16033 } 16034 } 16035 16036 return num; 16037 } 16038 16039 @Override 16040 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16041 int userId) { 16042 int callingUid = Binder.getCallingUid(); 16043 if (callingUid != Process.SYSTEM_UID) { 16044 throw new SecurityException( 16045 "addPersistentPreferredActivity can only be run by the system"); 16046 } 16047 if (filter.countActions() == 0) { 16048 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16049 return; 16050 } 16051 synchronized (mPackages) { 16052 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16053 ":"); 16054 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16055 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16056 new PersistentPreferredActivity(filter, activity)); 16057 scheduleWritePackageRestrictionsLocked(userId); 16058 } 16059 } 16060 16061 @Override 16062 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16063 int callingUid = Binder.getCallingUid(); 16064 if (callingUid != Process.SYSTEM_UID) { 16065 throw new SecurityException( 16066 "clearPackagePersistentPreferredActivities can only be run by the system"); 16067 } 16068 ArrayList<PersistentPreferredActivity> removed = null; 16069 boolean changed = false; 16070 synchronized (mPackages) { 16071 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16072 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16073 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16074 .valueAt(i); 16075 if (userId != thisUserId) { 16076 continue; 16077 } 16078 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16079 while (it.hasNext()) { 16080 PersistentPreferredActivity ppa = it.next(); 16081 // Mark entry for removal only if it matches the package name. 16082 if (ppa.mComponent.getPackageName().equals(packageName)) { 16083 if (removed == null) { 16084 removed = new ArrayList<PersistentPreferredActivity>(); 16085 } 16086 removed.add(ppa); 16087 } 16088 } 16089 if (removed != null) { 16090 for (int j=0; j<removed.size(); j++) { 16091 PersistentPreferredActivity ppa = removed.get(j); 16092 ppir.removeFilter(ppa); 16093 } 16094 changed = true; 16095 } 16096 } 16097 16098 if (changed) { 16099 scheduleWritePackageRestrictionsLocked(userId); 16100 } 16101 } 16102 } 16103 16104 /** 16105 * Common machinery for picking apart a restored XML blob and passing 16106 * it to a caller-supplied functor to be applied to the running system. 16107 */ 16108 private void restoreFromXml(XmlPullParser parser, int userId, 16109 String expectedStartTag, BlobXmlRestorer functor) 16110 throws IOException, XmlPullParserException { 16111 int type; 16112 while ((type = parser.next()) != XmlPullParser.START_TAG 16113 && type != XmlPullParser.END_DOCUMENT) { 16114 } 16115 if (type != XmlPullParser.START_TAG) { 16116 // oops didn't find a start tag?! 16117 if (DEBUG_BACKUP) { 16118 Slog.e(TAG, "Didn't find start tag during restore"); 16119 } 16120 return; 16121 } 16122Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16123 // this is supposed to be TAG_PREFERRED_BACKUP 16124 if (!expectedStartTag.equals(parser.getName())) { 16125 if (DEBUG_BACKUP) { 16126 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16127 } 16128 return; 16129 } 16130 16131 // skip interfering stuff, then we're aligned with the backing implementation 16132 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16133Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16134 functor.apply(parser, userId); 16135 } 16136 16137 private interface BlobXmlRestorer { 16138 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16139 } 16140 16141 /** 16142 * Non-Binder method, support for the backup/restore mechanism: write the 16143 * full set of preferred activities in its canonical XML format. Returns the 16144 * XML output as a byte array, or null if there is none. 16145 */ 16146 @Override 16147 public byte[] getPreferredActivityBackup(int userId) { 16148 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16149 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16150 } 16151 16152 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16153 try { 16154 final XmlSerializer serializer = new FastXmlSerializer(); 16155 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16156 serializer.startDocument(null, true); 16157 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16158 16159 synchronized (mPackages) { 16160 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16161 } 16162 16163 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16164 serializer.endDocument(); 16165 serializer.flush(); 16166 } catch (Exception e) { 16167 if (DEBUG_BACKUP) { 16168 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16169 } 16170 return null; 16171 } 16172 16173 return dataStream.toByteArray(); 16174 } 16175 16176 @Override 16177 public void restorePreferredActivities(byte[] backup, int userId) { 16178 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16179 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16180 } 16181 16182 try { 16183 final XmlPullParser parser = Xml.newPullParser(); 16184 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16185 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16186 new BlobXmlRestorer() { 16187 @Override 16188 public void apply(XmlPullParser parser, int userId) 16189 throws XmlPullParserException, IOException { 16190 synchronized (mPackages) { 16191 mSettings.readPreferredActivitiesLPw(parser, userId); 16192 } 16193 } 16194 } ); 16195 } catch (Exception e) { 16196 if (DEBUG_BACKUP) { 16197 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16198 } 16199 } 16200 } 16201 16202 /** 16203 * Non-Binder method, support for the backup/restore mechanism: write the 16204 * default browser (etc) settings in its canonical XML format. Returns the default 16205 * browser XML representation as a byte array, or null if there is none. 16206 */ 16207 @Override 16208 public byte[] getDefaultAppsBackup(int userId) { 16209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16210 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16211 } 16212 16213 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16214 try { 16215 final XmlSerializer serializer = new FastXmlSerializer(); 16216 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16217 serializer.startDocument(null, true); 16218 serializer.startTag(null, TAG_DEFAULT_APPS); 16219 16220 synchronized (mPackages) { 16221 mSettings.writeDefaultAppsLPr(serializer, userId); 16222 } 16223 16224 serializer.endTag(null, TAG_DEFAULT_APPS); 16225 serializer.endDocument(); 16226 serializer.flush(); 16227 } catch (Exception e) { 16228 if (DEBUG_BACKUP) { 16229 Slog.e(TAG, "Unable to write default apps for backup", e); 16230 } 16231 return null; 16232 } 16233 16234 return dataStream.toByteArray(); 16235 } 16236 16237 @Override 16238 public void restoreDefaultApps(byte[] backup, int userId) { 16239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16240 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16241 } 16242 16243 try { 16244 final XmlPullParser parser = Xml.newPullParser(); 16245 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16246 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16247 new BlobXmlRestorer() { 16248 @Override 16249 public void apply(XmlPullParser parser, int userId) 16250 throws XmlPullParserException, IOException { 16251 synchronized (mPackages) { 16252 mSettings.readDefaultAppsLPw(parser, userId); 16253 } 16254 } 16255 } ); 16256 } catch (Exception e) { 16257 if (DEBUG_BACKUP) { 16258 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16259 } 16260 } 16261 } 16262 16263 @Override 16264 public byte[] getIntentFilterVerificationBackup(int userId) { 16265 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16266 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16267 } 16268 16269 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16270 try { 16271 final XmlSerializer serializer = new FastXmlSerializer(); 16272 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16273 serializer.startDocument(null, true); 16274 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16275 16276 synchronized (mPackages) { 16277 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16278 } 16279 16280 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16281 serializer.endDocument(); 16282 serializer.flush(); 16283 } catch (Exception e) { 16284 if (DEBUG_BACKUP) { 16285 Slog.e(TAG, "Unable to write default apps for backup", e); 16286 } 16287 return null; 16288 } 16289 16290 return dataStream.toByteArray(); 16291 } 16292 16293 @Override 16294 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16295 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16296 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16297 } 16298 16299 try { 16300 final XmlPullParser parser = Xml.newPullParser(); 16301 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16302 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16303 new BlobXmlRestorer() { 16304 @Override 16305 public void apply(XmlPullParser parser, int userId) 16306 throws XmlPullParserException, IOException { 16307 synchronized (mPackages) { 16308 mSettings.readAllDomainVerificationsLPr(parser, userId); 16309 mSettings.writeLPr(); 16310 } 16311 } 16312 } ); 16313 } catch (Exception e) { 16314 if (DEBUG_BACKUP) { 16315 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16316 } 16317 } 16318 } 16319 16320 @Override 16321 public byte[] getPermissionGrantBackup(int userId) { 16322 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16323 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16324 } 16325 16326 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16327 try { 16328 final XmlSerializer serializer = new FastXmlSerializer(); 16329 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16330 serializer.startDocument(null, true); 16331 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16332 16333 synchronized (mPackages) { 16334 serializeRuntimePermissionGrantsLPr(serializer, userId); 16335 } 16336 16337 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16338 serializer.endDocument(); 16339 serializer.flush(); 16340 } catch (Exception e) { 16341 if (DEBUG_BACKUP) { 16342 Slog.e(TAG, "Unable to write default apps for backup", e); 16343 } 16344 return null; 16345 } 16346 16347 return dataStream.toByteArray(); 16348 } 16349 16350 @Override 16351 public void restorePermissionGrants(byte[] backup, int userId) { 16352 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16353 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16354 } 16355 16356 try { 16357 final XmlPullParser parser = Xml.newPullParser(); 16358 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16359 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16360 new BlobXmlRestorer() { 16361 @Override 16362 public void apply(XmlPullParser parser, int userId) 16363 throws XmlPullParserException, IOException { 16364 synchronized (mPackages) { 16365 processRestoredPermissionGrantsLPr(parser, userId); 16366 } 16367 } 16368 } ); 16369 } catch (Exception e) { 16370 if (DEBUG_BACKUP) { 16371 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16372 } 16373 } 16374 } 16375 16376 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16377 throws IOException { 16378 serializer.startTag(null, TAG_ALL_GRANTS); 16379 16380 final int N = mSettings.mPackages.size(); 16381 for (int i = 0; i < N; i++) { 16382 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16383 boolean pkgGrantsKnown = false; 16384 16385 PermissionsState packagePerms = ps.getPermissionsState(); 16386 16387 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16388 final int grantFlags = state.getFlags(); 16389 // only look at grants that are not system/policy fixed 16390 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16391 final boolean isGranted = state.isGranted(); 16392 // And only back up the user-twiddled state bits 16393 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16394 final String packageName = mSettings.mPackages.keyAt(i); 16395 if (!pkgGrantsKnown) { 16396 serializer.startTag(null, TAG_GRANT); 16397 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16398 pkgGrantsKnown = true; 16399 } 16400 16401 final boolean userSet = 16402 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16403 final boolean userFixed = 16404 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16405 final boolean revoke = 16406 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16407 16408 serializer.startTag(null, TAG_PERMISSION); 16409 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16410 if (isGranted) { 16411 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16412 } 16413 if (userSet) { 16414 serializer.attribute(null, ATTR_USER_SET, "true"); 16415 } 16416 if (userFixed) { 16417 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16418 } 16419 if (revoke) { 16420 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16421 } 16422 serializer.endTag(null, TAG_PERMISSION); 16423 } 16424 } 16425 } 16426 16427 if (pkgGrantsKnown) { 16428 serializer.endTag(null, TAG_GRANT); 16429 } 16430 } 16431 16432 serializer.endTag(null, TAG_ALL_GRANTS); 16433 } 16434 16435 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16436 throws XmlPullParserException, IOException { 16437 String pkgName = null; 16438 int outerDepth = parser.getDepth(); 16439 int type; 16440 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16441 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16442 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16443 continue; 16444 } 16445 16446 final String tagName = parser.getName(); 16447 if (tagName.equals(TAG_GRANT)) { 16448 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16449 if (DEBUG_BACKUP) { 16450 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16451 } 16452 } else if (tagName.equals(TAG_PERMISSION)) { 16453 16454 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16455 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16456 16457 int newFlagSet = 0; 16458 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16459 newFlagSet |= FLAG_PERMISSION_USER_SET; 16460 } 16461 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16462 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16463 } 16464 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16465 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16466 } 16467 if (DEBUG_BACKUP) { 16468 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16469 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16470 } 16471 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16472 if (ps != null) { 16473 // Already installed so we apply the grant immediately 16474 if (DEBUG_BACKUP) { 16475 Slog.v(TAG, " + already installed; applying"); 16476 } 16477 PermissionsState perms = ps.getPermissionsState(); 16478 BasePermission bp = mSettings.mPermissions.get(permName); 16479 if (bp != null) { 16480 if (isGranted) { 16481 perms.grantRuntimePermission(bp, userId); 16482 } 16483 if (newFlagSet != 0) { 16484 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16485 } 16486 } 16487 } else { 16488 // Need to wait for post-restore install to apply the grant 16489 if (DEBUG_BACKUP) { 16490 Slog.v(TAG, " - not yet installed; saving for later"); 16491 } 16492 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16493 isGranted, newFlagSet, userId); 16494 } 16495 } else { 16496 PackageManagerService.reportSettingsProblem(Log.WARN, 16497 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16498 XmlUtils.skipCurrentTag(parser); 16499 } 16500 } 16501 16502 scheduleWriteSettingsLocked(); 16503 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16504 } 16505 16506 @Override 16507 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16508 int sourceUserId, int targetUserId, int flags) { 16509 mContext.enforceCallingOrSelfPermission( 16510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16511 int callingUid = Binder.getCallingUid(); 16512 enforceOwnerRights(ownerPackage, callingUid); 16513 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16514 if (intentFilter.countActions() == 0) { 16515 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16516 return; 16517 } 16518 synchronized (mPackages) { 16519 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16520 ownerPackage, targetUserId, flags); 16521 CrossProfileIntentResolver resolver = 16522 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16523 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16524 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16525 if (existing != null) { 16526 int size = existing.size(); 16527 for (int i = 0; i < size; i++) { 16528 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16529 return; 16530 } 16531 } 16532 } 16533 resolver.addFilter(newFilter); 16534 scheduleWritePackageRestrictionsLocked(sourceUserId); 16535 } 16536 } 16537 16538 @Override 16539 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16540 mContext.enforceCallingOrSelfPermission( 16541 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16542 int callingUid = Binder.getCallingUid(); 16543 enforceOwnerRights(ownerPackage, callingUid); 16544 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16545 synchronized (mPackages) { 16546 CrossProfileIntentResolver resolver = 16547 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16548 ArraySet<CrossProfileIntentFilter> set = 16549 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16550 for (CrossProfileIntentFilter filter : set) { 16551 if (filter.getOwnerPackage().equals(ownerPackage)) { 16552 resolver.removeFilter(filter); 16553 } 16554 } 16555 scheduleWritePackageRestrictionsLocked(sourceUserId); 16556 } 16557 } 16558 16559 // Enforcing that callingUid is owning pkg on userId 16560 private void enforceOwnerRights(String pkg, int callingUid) { 16561 // The system owns everything. 16562 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16563 return; 16564 } 16565 int callingUserId = UserHandle.getUserId(callingUid); 16566 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16567 if (pi == null) { 16568 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16569 + callingUserId); 16570 } 16571 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16572 throw new SecurityException("Calling uid " + callingUid 16573 + " does not own package " + pkg); 16574 } 16575 } 16576 16577 @Override 16578 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16579 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16580 } 16581 16582 private Intent getHomeIntent() { 16583 Intent intent = new Intent(Intent.ACTION_MAIN); 16584 intent.addCategory(Intent.CATEGORY_HOME); 16585 return intent; 16586 } 16587 16588 private IntentFilter getHomeFilter() { 16589 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16590 filter.addCategory(Intent.CATEGORY_HOME); 16591 filter.addCategory(Intent.CATEGORY_DEFAULT); 16592 return filter; 16593 } 16594 16595 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16596 int userId) { 16597 Intent intent = getHomeIntent(); 16598 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16599 PackageManager.GET_META_DATA, userId); 16600 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16601 true, false, false, userId); 16602 16603 allHomeCandidates.clear(); 16604 if (list != null) { 16605 for (ResolveInfo ri : list) { 16606 allHomeCandidates.add(ri); 16607 } 16608 } 16609 return (preferred == null || preferred.activityInfo == null) 16610 ? null 16611 : new ComponentName(preferred.activityInfo.packageName, 16612 preferred.activityInfo.name); 16613 } 16614 16615 @Override 16616 public void setHomeActivity(ComponentName comp, int userId) { 16617 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16618 getHomeActivitiesAsUser(homeActivities, userId); 16619 16620 boolean found = false; 16621 16622 final int size = homeActivities.size(); 16623 final ComponentName[] set = new ComponentName[size]; 16624 for (int i = 0; i < size; i++) { 16625 final ResolveInfo candidate = homeActivities.get(i); 16626 final ActivityInfo info = candidate.activityInfo; 16627 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16628 set[i] = activityName; 16629 if (!found && activityName.equals(comp)) { 16630 found = true; 16631 } 16632 } 16633 if (!found) { 16634 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16635 + userId); 16636 } 16637 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16638 set, comp, userId); 16639 } 16640 16641 @Override 16642 public void setApplicationEnabledSetting(String appPackageName, 16643 int newState, int flags, int userId, String callingPackage) { 16644 if (!sUserManager.exists(userId)) return; 16645 if (callingPackage == null) { 16646 callingPackage = Integer.toString(Binder.getCallingUid()); 16647 } 16648 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16649 } 16650 16651 @Override 16652 public void setComponentEnabledSetting(ComponentName componentName, 16653 int newState, int flags, int userId) { 16654 if (!sUserManager.exists(userId)) return; 16655 setEnabledSetting(componentName.getPackageName(), 16656 componentName.getClassName(), newState, flags, userId, null); 16657 } 16658 16659 private void setEnabledSetting(final String packageName, String className, int newState, 16660 final int flags, int userId, String callingPackage) { 16661 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16662 || newState == COMPONENT_ENABLED_STATE_ENABLED 16663 || newState == COMPONENT_ENABLED_STATE_DISABLED 16664 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16665 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16666 throw new IllegalArgumentException("Invalid new component state: " 16667 + newState); 16668 } 16669 PackageSetting pkgSetting; 16670 final int uid = Binder.getCallingUid(); 16671 final int permission = mContext.checkCallingOrSelfPermission( 16672 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16673 enforceCrossUserPermission(uid, userId, 16674 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16675 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16676 boolean sendNow = false; 16677 boolean isApp = (className == null); 16678 String componentName = isApp ? packageName : className; 16679 int packageUid = -1; 16680 ArrayList<String> components; 16681 16682 // writer 16683 synchronized (mPackages) { 16684 pkgSetting = mSettings.mPackages.get(packageName); 16685 if (pkgSetting == null) { 16686 if (className == null) { 16687 throw new IllegalArgumentException("Unknown package: " + packageName); 16688 } 16689 throw new IllegalArgumentException( 16690 "Unknown component: " + packageName + "/" + className); 16691 } 16692 // Allow root and verify that userId is not being specified by a different user 16693 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16694 throw new SecurityException( 16695 "Permission Denial: attempt to change component state from pid=" 16696 + Binder.getCallingPid() 16697 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16698 } 16699 if (className == null) { 16700 // We're dealing with an application/package level state change 16701 if (pkgSetting.getEnabled(userId) == newState) { 16702 // Nothing to do 16703 return; 16704 } 16705 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16706 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16707 // Don't care about who enables an app. 16708 callingPackage = null; 16709 } 16710 pkgSetting.setEnabled(newState, userId, callingPackage); 16711 // pkgSetting.pkg.mSetEnabled = newState; 16712 } else { 16713 // We're dealing with a component level state change 16714 // First, verify that this is a valid class name. 16715 PackageParser.Package pkg = pkgSetting.pkg; 16716 if (pkg == null || !pkg.hasComponentClassName(className)) { 16717 if (pkg != null && 16718 pkg.applicationInfo.targetSdkVersion >= 16719 Build.VERSION_CODES.JELLY_BEAN) { 16720 throw new IllegalArgumentException("Component class " + className 16721 + " does not exist in " + packageName); 16722 } else { 16723 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16724 + className + " does not exist in " + packageName); 16725 } 16726 } 16727 switch (newState) { 16728 case COMPONENT_ENABLED_STATE_ENABLED: 16729 if (!pkgSetting.enableComponentLPw(className, userId)) { 16730 return; 16731 } 16732 break; 16733 case COMPONENT_ENABLED_STATE_DISABLED: 16734 if (!pkgSetting.disableComponentLPw(className, userId)) { 16735 return; 16736 } 16737 break; 16738 case COMPONENT_ENABLED_STATE_DEFAULT: 16739 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16740 return; 16741 } 16742 break; 16743 default: 16744 Slog.e(TAG, "Invalid new component state: " + newState); 16745 return; 16746 } 16747 } 16748 scheduleWritePackageRestrictionsLocked(userId); 16749 components = mPendingBroadcasts.get(userId, packageName); 16750 final boolean newPackage = components == null; 16751 if (newPackage) { 16752 components = new ArrayList<String>(); 16753 } 16754 if (!components.contains(componentName)) { 16755 components.add(componentName); 16756 } 16757 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16758 sendNow = true; 16759 // Purge entry from pending broadcast list if another one exists already 16760 // since we are sending one right away. 16761 mPendingBroadcasts.remove(userId, packageName); 16762 } else { 16763 if (newPackage) { 16764 mPendingBroadcasts.put(userId, packageName, components); 16765 } 16766 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16767 // Schedule a message 16768 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16769 } 16770 } 16771 } 16772 16773 long callingId = Binder.clearCallingIdentity(); 16774 try { 16775 if (sendNow) { 16776 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16777 sendPackageChangedBroadcast(packageName, 16778 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16779 } 16780 } finally { 16781 Binder.restoreCallingIdentity(callingId); 16782 } 16783 } 16784 16785 @Override 16786 public void flushPackageRestrictionsAsUser(int userId) { 16787 if (!sUserManager.exists(userId)) { 16788 return; 16789 } 16790 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16791 false /* checkShell */, "flushPackageRestrictions"); 16792 synchronized (mPackages) { 16793 mSettings.writePackageRestrictionsLPr(userId); 16794 mDirtyUsers.remove(userId); 16795 if (mDirtyUsers.isEmpty()) { 16796 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16797 } 16798 } 16799 } 16800 16801 private void sendPackageChangedBroadcast(String packageName, 16802 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16803 if (DEBUG_INSTALL) 16804 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16805 + componentNames); 16806 Bundle extras = new Bundle(4); 16807 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16808 String nameList[] = new String[componentNames.size()]; 16809 componentNames.toArray(nameList); 16810 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16811 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16812 extras.putInt(Intent.EXTRA_UID, packageUid); 16813 // If this is not reporting a change of the overall package, then only send it 16814 // to registered receivers. We don't want to launch a swath of apps for every 16815 // little component state change. 16816 final int flags = !componentNames.contains(packageName) 16817 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16818 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16819 new int[] {UserHandle.getUserId(packageUid)}); 16820 } 16821 16822 @Override 16823 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16824 if (!sUserManager.exists(userId)) return; 16825 final int uid = Binder.getCallingUid(); 16826 final int permission = mContext.checkCallingOrSelfPermission( 16827 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16828 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16829 enforceCrossUserPermission(uid, userId, 16830 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16831 // writer 16832 synchronized (mPackages) { 16833 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16834 allowedByPermission, uid, userId)) { 16835 scheduleWritePackageRestrictionsLocked(userId); 16836 } 16837 } 16838 } 16839 16840 @Override 16841 public String getInstallerPackageName(String packageName) { 16842 // reader 16843 synchronized (mPackages) { 16844 return mSettings.getInstallerPackageNameLPr(packageName); 16845 } 16846 } 16847 16848 @Override 16849 public int getApplicationEnabledSetting(String packageName, int userId) { 16850 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16851 int uid = Binder.getCallingUid(); 16852 enforceCrossUserPermission(uid, userId, 16853 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16854 // reader 16855 synchronized (mPackages) { 16856 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16857 } 16858 } 16859 16860 @Override 16861 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16862 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16863 int uid = Binder.getCallingUid(); 16864 enforceCrossUserPermission(uid, userId, 16865 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16866 // reader 16867 synchronized (mPackages) { 16868 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16869 } 16870 } 16871 16872 @Override 16873 public void enterSafeMode() { 16874 enforceSystemOrRoot("Only the system can request entering safe mode"); 16875 16876 if (!mSystemReady) { 16877 mSafeMode = true; 16878 } 16879 } 16880 16881 @Override 16882 public void systemReady() { 16883 mSystemReady = true; 16884 16885 // Read the compatibilty setting when the system is ready. 16886 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16887 mContext.getContentResolver(), 16888 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16889 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16890 if (DEBUG_SETTINGS) { 16891 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16892 } 16893 16894 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16895 16896 synchronized (mPackages) { 16897 // Verify that all of the preferred activity components actually 16898 // exist. It is possible for applications to be updated and at 16899 // that point remove a previously declared activity component that 16900 // had been set as a preferred activity. We try to clean this up 16901 // the next time we encounter that preferred activity, but it is 16902 // possible for the user flow to never be able to return to that 16903 // situation so here we do a sanity check to make sure we haven't 16904 // left any junk around. 16905 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16906 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16907 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16908 removed.clear(); 16909 for (PreferredActivity pa : pir.filterSet()) { 16910 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16911 removed.add(pa); 16912 } 16913 } 16914 if (removed.size() > 0) { 16915 for (int r=0; r<removed.size(); r++) { 16916 PreferredActivity pa = removed.get(r); 16917 Slog.w(TAG, "Removing dangling preferred activity: " 16918 + pa.mPref.mComponent); 16919 pir.removeFilter(pa); 16920 } 16921 mSettings.writePackageRestrictionsLPr( 16922 mSettings.mPreferredActivities.keyAt(i)); 16923 } 16924 } 16925 16926 for (int userId : UserManagerService.getInstance().getUserIds()) { 16927 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16928 grantPermissionsUserIds = ArrayUtils.appendInt( 16929 grantPermissionsUserIds, userId); 16930 } 16931 } 16932 } 16933 sUserManager.systemReady(); 16934 16935 // If we upgraded grant all default permissions before kicking off. 16936 for (int userId : grantPermissionsUserIds) { 16937 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16938 } 16939 16940 // Kick off any messages waiting for system ready 16941 if (mPostSystemReadyMessages != null) { 16942 for (Message msg : mPostSystemReadyMessages) { 16943 msg.sendToTarget(); 16944 } 16945 mPostSystemReadyMessages = null; 16946 } 16947 16948 // Watch for external volumes that come and go over time 16949 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16950 storage.registerListener(mStorageListener); 16951 16952 mInstallerService.systemReady(); 16953 mPackageDexOptimizer.systemReady(); 16954 16955 MountServiceInternal mountServiceInternal = LocalServices.getService( 16956 MountServiceInternal.class); 16957 mountServiceInternal.addExternalStoragePolicy( 16958 new MountServiceInternal.ExternalStorageMountPolicy() { 16959 @Override 16960 public int getMountMode(int uid, String packageName) { 16961 if (Process.isIsolated(uid)) { 16962 return Zygote.MOUNT_EXTERNAL_NONE; 16963 } 16964 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16965 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16966 } 16967 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16968 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16969 } 16970 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16971 return Zygote.MOUNT_EXTERNAL_READ; 16972 } 16973 return Zygote.MOUNT_EXTERNAL_WRITE; 16974 } 16975 16976 @Override 16977 public boolean hasExternalStorage(int uid, String packageName) { 16978 return true; 16979 } 16980 }); 16981 } 16982 16983 @Override 16984 public boolean isSafeMode() { 16985 return mSafeMode; 16986 } 16987 16988 @Override 16989 public boolean hasSystemUidErrors() { 16990 return mHasSystemUidErrors; 16991 } 16992 16993 static String arrayToString(int[] array) { 16994 StringBuffer buf = new StringBuffer(128); 16995 buf.append('['); 16996 if (array != null) { 16997 for (int i=0; i<array.length; i++) { 16998 if (i > 0) buf.append(", "); 16999 buf.append(array[i]); 17000 } 17001 } 17002 buf.append(']'); 17003 return buf.toString(); 17004 } 17005 17006 static class DumpState { 17007 public static final int DUMP_LIBS = 1 << 0; 17008 public static final int DUMP_FEATURES = 1 << 1; 17009 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17010 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17011 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17012 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17013 public static final int DUMP_PERMISSIONS = 1 << 6; 17014 public static final int DUMP_PACKAGES = 1 << 7; 17015 public static final int DUMP_SHARED_USERS = 1 << 8; 17016 public static final int DUMP_MESSAGES = 1 << 9; 17017 public static final int DUMP_PROVIDERS = 1 << 10; 17018 public static final int DUMP_VERIFIERS = 1 << 11; 17019 public static final int DUMP_PREFERRED = 1 << 12; 17020 public static final int DUMP_PREFERRED_XML = 1 << 13; 17021 public static final int DUMP_KEYSETS = 1 << 14; 17022 public static final int DUMP_VERSION = 1 << 15; 17023 public static final int DUMP_INSTALLS = 1 << 16; 17024 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17025 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17026 17027 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17028 17029 private int mTypes; 17030 17031 private int mOptions; 17032 17033 private boolean mTitlePrinted; 17034 17035 private SharedUserSetting mSharedUser; 17036 17037 public boolean isDumping(int type) { 17038 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17039 return true; 17040 } 17041 17042 return (mTypes & type) != 0; 17043 } 17044 17045 public void setDump(int type) { 17046 mTypes |= type; 17047 } 17048 17049 public boolean isOptionEnabled(int option) { 17050 return (mOptions & option) != 0; 17051 } 17052 17053 public void setOptionEnabled(int option) { 17054 mOptions |= option; 17055 } 17056 17057 public boolean onTitlePrinted() { 17058 final boolean printed = mTitlePrinted; 17059 mTitlePrinted = true; 17060 return printed; 17061 } 17062 17063 public boolean getTitlePrinted() { 17064 return mTitlePrinted; 17065 } 17066 17067 public void setTitlePrinted(boolean enabled) { 17068 mTitlePrinted = enabled; 17069 } 17070 17071 public SharedUserSetting getSharedUser() { 17072 return mSharedUser; 17073 } 17074 17075 public void setSharedUser(SharedUserSetting user) { 17076 mSharedUser = user; 17077 } 17078 } 17079 17080 @Override 17081 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17082 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17083 (new PackageManagerShellCommand(this)).exec( 17084 this, in, out, err, args, resultReceiver); 17085 } 17086 17087 @Override 17088 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17089 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17090 != PackageManager.PERMISSION_GRANTED) { 17091 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17092 + Binder.getCallingPid() 17093 + ", uid=" + Binder.getCallingUid() 17094 + " without permission " 17095 + android.Manifest.permission.DUMP); 17096 return; 17097 } 17098 17099 DumpState dumpState = new DumpState(); 17100 boolean fullPreferred = false; 17101 boolean checkin = false; 17102 17103 String packageName = null; 17104 ArraySet<String> permissionNames = null; 17105 17106 int opti = 0; 17107 while (opti < args.length) { 17108 String opt = args[opti]; 17109 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17110 break; 17111 } 17112 opti++; 17113 17114 if ("-a".equals(opt)) { 17115 // Right now we only know how to print all. 17116 } else if ("-h".equals(opt)) { 17117 pw.println("Package manager dump options:"); 17118 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17119 pw.println(" --checkin: dump for a checkin"); 17120 pw.println(" -f: print details of intent filters"); 17121 pw.println(" -h: print this help"); 17122 pw.println(" cmd may be one of:"); 17123 pw.println(" l[ibraries]: list known shared libraries"); 17124 pw.println(" f[eatures]: list device features"); 17125 pw.println(" k[eysets]: print known keysets"); 17126 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17127 pw.println(" perm[issions]: dump permissions"); 17128 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17129 pw.println(" pref[erred]: print preferred package settings"); 17130 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17131 pw.println(" prov[iders]: dump content providers"); 17132 pw.println(" p[ackages]: dump installed packages"); 17133 pw.println(" s[hared-users]: dump shared user IDs"); 17134 pw.println(" m[essages]: print collected runtime messages"); 17135 pw.println(" v[erifiers]: print package verifier info"); 17136 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17137 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17138 pw.println(" version: print database version info"); 17139 pw.println(" write: write current settings now"); 17140 pw.println(" installs: details about install sessions"); 17141 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17142 pw.println(" <package.name>: info about given package"); 17143 return; 17144 } else if ("--checkin".equals(opt)) { 17145 checkin = true; 17146 } else if ("-f".equals(opt)) { 17147 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17148 } else { 17149 pw.println("Unknown argument: " + opt + "; use -h for help"); 17150 } 17151 } 17152 17153 // Is the caller requesting to dump a particular piece of data? 17154 if (opti < args.length) { 17155 String cmd = args[opti]; 17156 opti++; 17157 // Is this a package name? 17158 if ("android".equals(cmd) || cmd.contains(".")) { 17159 packageName = cmd; 17160 // When dumping a single package, we always dump all of its 17161 // filter information since the amount of data will be reasonable. 17162 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17163 } else if ("check-permission".equals(cmd)) { 17164 if (opti >= args.length) { 17165 pw.println("Error: check-permission missing permission argument"); 17166 return; 17167 } 17168 String perm = args[opti]; 17169 opti++; 17170 if (opti >= args.length) { 17171 pw.println("Error: check-permission missing package argument"); 17172 return; 17173 } 17174 String pkg = args[opti]; 17175 opti++; 17176 int user = UserHandle.getUserId(Binder.getCallingUid()); 17177 if (opti < args.length) { 17178 try { 17179 user = Integer.parseInt(args[opti]); 17180 } catch (NumberFormatException e) { 17181 pw.println("Error: check-permission user argument is not a number: " 17182 + args[opti]); 17183 return; 17184 } 17185 } 17186 pw.println(checkPermission(perm, pkg, user)); 17187 return; 17188 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17189 dumpState.setDump(DumpState.DUMP_LIBS); 17190 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17191 dumpState.setDump(DumpState.DUMP_FEATURES); 17192 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17193 if (opti >= args.length) { 17194 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17195 | DumpState.DUMP_SERVICE_RESOLVERS 17196 | DumpState.DUMP_RECEIVER_RESOLVERS 17197 | DumpState.DUMP_CONTENT_RESOLVERS); 17198 } else { 17199 while (opti < args.length) { 17200 String name = args[opti]; 17201 if ("a".equals(name) || "activity".equals(name)) { 17202 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17203 } else if ("s".equals(name) || "service".equals(name)) { 17204 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17205 } else if ("r".equals(name) || "receiver".equals(name)) { 17206 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17207 } else if ("c".equals(name) || "content".equals(name)) { 17208 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17209 } else { 17210 pw.println("Error: unknown resolver table type: " + name); 17211 return; 17212 } 17213 opti++; 17214 } 17215 } 17216 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17217 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17218 } else if ("permission".equals(cmd)) { 17219 if (opti >= args.length) { 17220 pw.println("Error: permission requires permission name"); 17221 return; 17222 } 17223 permissionNames = new ArraySet<>(); 17224 while (opti < args.length) { 17225 permissionNames.add(args[opti]); 17226 opti++; 17227 } 17228 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17229 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17230 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17231 dumpState.setDump(DumpState.DUMP_PREFERRED); 17232 } else if ("preferred-xml".equals(cmd)) { 17233 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17234 if (opti < args.length && "--full".equals(args[opti])) { 17235 fullPreferred = true; 17236 opti++; 17237 } 17238 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17239 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17240 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17241 dumpState.setDump(DumpState.DUMP_PACKAGES); 17242 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17243 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17244 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17245 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17246 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17247 dumpState.setDump(DumpState.DUMP_MESSAGES); 17248 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17249 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17250 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17251 || "intent-filter-verifiers".equals(cmd)) { 17252 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17253 } else if ("version".equals(cmd)) { 17254 dumpState.setDump(DumpState.DUMP_VERSION); 17255 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17256 dumpState.setDump(DumpState.DUMP_KEYSETS); 17257 } else if ("installs".equals(cmd)) { 17258 dumpState.setDump(DumpState.DUMP_INSTALLS); 17259 } else if ("write".equals(cmd)) { 17260 synchronized (mPackages) { 17261 mSettings.writeLPr(); 17262 pw.println("Settings written."); 17263 return; 17264 } 17265 } 17266 } 17267 17268 if (checkin) { 17269 pw.println("vers,1"); 17270 } 17271 17272 // reader 17273 synchronized (mPackages) { 17274 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17275 if (!checkin) { 17276 if (dumpState.onTitlePrinted()) 17277 pw.println(); 17278 pw.println("Database versions:"); 17279 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17280 } 17281 } 17282 17283 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17284 if (!checkin) { 17285 if (dumpState.onTitlePrinted()) 17286 pw.println(); 17287 pw.println("Verifiers:"); 17288 pw.print(" Required: "); 17289 pw.print(mRequiredVerifierPackage); 17290 pw.print(" (uid="); 17291 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17292 UserHandle.USER_SYSTEM)); 17293 pw.println(")"); 17294 } else if (mRequiredVerifierPackage != null) { 17295 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17296 pw.print(","); 17297 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17298 UserHandle.USER_SYSTEM)); 17299 } 17300 } 17301 17302 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17303 packageName == null) { 17304 if (mIntentFilterVerifierComponent != null) { 17305 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17306 if (!checkin) { 17307 if (dumpState.onTitlePrinted()) 17308 pw.println(); 17309 pw.println("Intent Filter Verifier:"); 17310 pw.print(" Using: "); 17311 pw.print(verifierPackageName); 17312 pw.print(" (uid="); 17313 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17314 UserHandle.USER_SYSTEM)); 17315 pw.println(")"); 17316 } else if (verifierPackageName != null) { 17317 pw.print("ifv,"); pw.print(verifierPackageName); 17318 pw.print(","); 17319 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17320 UserHandle.USER_SYSTEM)); 17321 } 17322 } else { 17323 pw.println(); 17324 pw.println("No Intent Filter Verifier available!"); 17325 } 17326 } 17327 17328 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17329 boolean printedHeader = false; 17330 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17331 while (it.hasNext()) { 17332 String name = it.next(); 17333 SharedLibraryEntry ent = mSharedLibraries.get(name); 17334 if (!checkin) { 17335 if (!printedHeader) { 17336 if (dumpState.onTitlePrinted()) 17337 pw.println(); 17338 pw.println("Libraries:"); 17339 printedHeader = true; 17340 } 17341 pw.print(" "); 17342 } else { 17343 pw.print("lib,"); 17344 } 17345 pw.print(name); 17346 if (!checkin) { 17347 pw.print(" -> "); 17348 } 17349 if (ent.path != null) { 17350 if (!checkin) { 17351 pw.print("(jar) "); 17352 pw.print(ent.path); 17353 } else { 17354 pw.print(",jar,"); 17355 pw.print(ent.path); 17356 } 17357 } else { 17358 if (!checkin) { 17359 pw.print("(apk) "); 17360 pw.print(ent.apk); 17361 } else { 17362 pw.print(",apk,"); 17363 pw.print(ent.apk); 17364 } 17365 } 17366 pw.println(); 17367 } 17368 } 17369 17370 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17371 if (dumpState.onTitlePrinted()) 17372 pw.println(); 17373 if (!checkin) { 17374 pw.println("Features:"); 17375 } 17376 17377 for (FeatureInfo feat : mAvailableFeatures.values()) { 17378 if (checkin) { 17379 pw.print("feat,"); 17380 pw.print(feat.name); 17381 pw.print(","); 17382 pw.println(feat.version); 17383 } else { 17384 pw.print(" "); 17385 pw.print(feat.name); 17386 if (feat.version > 0) { 17387 pw.print(" version="); 17388 pw.print(feat.version); 17389 } 17390 pw.println(); 17391 } 17392 } 17393 } 17394 17395 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17396 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17397 : "Activity Resolver Table:", " ", packageName, 17398 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17399 dumpState.setTitlePrinted(true); 17400 } 17401 } 17402 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17403 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17404 : "Receiver Resolver Table:", " ", packageName, 17405 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17406 dumpState.setTitlePrinted(true); 17407 } 17408 } 17409 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17410 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17411 : "Service Resolver Table:", " ", packageName, 17412 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17413 dumpState.setTitlePrinted(true); 17414 } 17415 } 17416 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17417 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17418 : "Provider Resolver Table:", " ", packageName, 17419 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17420 dumpState.setTitlePrinted(true); 17421 } 17422 } 17423 17424 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17425 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17426 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17427 int user = mSettings.mPreferredActivities.keyAt(i); 17428 if (pir.dump(pw, 17429 dumpState.getTitlePrinted() 17430 ? "\nPreferred Activities User " + user + ":" 17431 : "Preferred Activities User " + user + ":", " ", 17432 packageName, true, false)) { 17433 dumpState.setTitlePrinted(true); 17434 } 17435 } 17436 } 17437 17438 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17439 pw.flush(); 17440 FileOutputStream fout = new FileOutputStream(fd); 17441 BufferedOutputStream str = new BufferedOutputStream(fout); 17442 XmlSerializer serializer = new FastXmlSerializer(); 17443 try { 17444 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17445 serializer.startDocument(null, true); 17446 serializer.setFeature( 17447 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17448 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17449 serializer.endDocument(); 17450 serializer.flush(); 17451 } catch (IllegalArgumentException e) { 17452 pw.println("Failed writing: " + e); 17453 } catch (IllegalStateException e) { 17454 pw.println("Failed writing: " + e); 17455 } catch (IOException e) { 17456 pw.println("Failed writing: " + e); 17457 } 17458 } 17459 17460 if (!checkin 17461 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17462 && packageName == null) { 17463 pw.println(); 17464 int count = mSettings.mPackages.size(); 17465 if (count == 0) { 17466 pw.println("No applications!"); 17467 pw.println(); 17468 } else { 17469 final String prefix = " "; 17470 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17471 if (allPackageSettings.size() == 0) { 17472 pw.println("No domain preferred apps!"); 17473 pw.println(); 17474 } else { 17475 pw.println("App verification status:"); 17476 pw.println(); 17477 count = 0; 17478 for (PackageSetting ps : allPackageSettings) { 17479 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17480 if (ivi == null || ivi.getPackageName() == null) continue; 17481 pw.println(prefix + "Package: " + ivi.getPackageName()); 17482 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17483 pw.println(prefix + "Status: " + ivi.getStatusString()); 17484 pw.println(); 17485 count++; 17486 } 17487 if (count == 0) { 17488 pw.println(prefix + "No app verification established."); 17489 pw.println(); 17490 } 17491 for (int userId : sUserManager.getUserIds()) { 17492 pw.println("App linkages for user " + userId + ":"); 17493 pw.println(); 17494 count = 0; 17495 for (PackageSetting ps : allPackageSettings) { 17496 final long status = ps.getDomainVerificationStatusForUser(userId); 17497 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17498 continue; 17499 } 17500 pw.println(prefix + "Package: " + ps.name); 17501 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17502 String statusStr = IntentFilterVerificationInfo. 17503 getStatusStringFromValue(status); 17504 pw.println(prefix + "Status: " + statusStr); 17505 pw.println(); 17506 count++; 17507 } 17508 if (count == 0) { 17509 pw.println(prefix + "No configured app linkages."); 17510 pw.println(); 17511 } 17512 } 17513 } 17514 } 17515 } 17516 17517 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17518 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17519 if (packageName == null && permissionNames == null) { 17520 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17521 if (iperm == 0) { 17522 if (dumpState.onTitlePrinted()) 17523 pw.println(); 17524 pw.println("AppOp Permissions:"); 17525 } 17526 pw.print(" AppOp Permission "); 17527 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17528 pw.println(":"); 17529 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17530 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17531 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17532 } 17533 } 17534 } 17535 } 17536 17537 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17538 boolean printedSomething = false; 17539 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17540 if (packageName != null && !packageName.equals(p.info.packageName)) { 17541 continue; 17542 } 17543 if (!printedSomething) { 17544 if (dumpState.onTitlePrinted()) 17545 pw.println(); 17546 pw.println("Registered ContentProviders:"); 17547 printedSomething = true; 17548 } 17549 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17550 pw.print(" "); pw.println(p.toString()); 17551 } 17552 printedSomething = false; 17553 for (Map.Entry<String, PackageParser.Provider> entry : 17554 mProvidersByAuthority.entrySet()) { 17555 PackageParser.Provider p = entry.getValue(); 17556 if (packageName != null && !packageName.equals(p.info.packageName)) { 17557 continue; 17558 } 17559 if (!printedSomething) { 17560 if (dumpState.onTitlePrinted()) 17561 pw.println(); 17562 pw.println("ContentProvider Authorities:"); 17563 printedSomething = true; 17564 } 17565 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17566 pw.print(" "); pw.println(p.toString()); 17567 if (p.info != null && p.info.applicationInfo != null) { 17568 final String appInfo = p.info.applicationInfo.toString(); 17569 pw.print(" applicationInfo="); pw.println(appInfo); 17570 } 17571 } 17572 } 17573 17574 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17575 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17576 } 17577 17578 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17579 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17580 } 17581 17582 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17583 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17584 } 17585 17586 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17587 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17588 } 17589 17590 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17591 // XXX should handle packageName != null by dumping only install data that 17592 // the given package is involved with. 17593 if (dumpState.onTitlePrinted()) pw.println(); 17594 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17595 } 17596 17597 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17598 if (dumpState.onTitlePrinted()) pw.println(); 17599 mSettings.dumpReadMessagesLPr(pw, dumpState); 17600 17601 pw.println(); 17602 pw.println("Package warning messages:"); 17603 BufferedReader in = null; 17604 String line = null; 17605 try { 17606 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17607 while ((line = in.readLine()) != null) { 17608 if (line.contains("ignored: updated version")) continue; 17609 pw.println(line); 17610 } 17611 } catch (IOException ignored) { 17612 } finally { 17613 IoUtils.closeQuietly(in); 17614 } 17615 } 17616 17617 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17618 BufferedReader in = null; 17619 String line = null; 17620 try { 17621 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17622 while ((line = in.readLine()) != null) { 17623 if (line.contains("ignored: updated version")) continue; 17624 pw.print("msg,"); 17625 pw.println(line); 17626 } 17627 } catch (IOException ignored) { 17628 } finally { 17629 IoUtils.closeQuietly(in); 17630 } 17631 } 17632 } 17633 } 17634 17635 private String dumpDomainString(String packageName) { 17636 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17637 .getList(); 17638 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17639 17640 ArraySet<String> result = new ArraySet<>(); 17641 if (iviList.size() > 0) { 17642 for (IntentFilterVerificationInfo ivi : iviList) { 17643 for (String host : ivi.getDomains()) { 17644 result.add(host); 17645 } 17646 } 17647 } 17648 if (filters != null && filters.size() > 0) { 17649 for (IntentFilter filter : filters) { 17650 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17651 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17652 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17653 result.addAll(filter.getHostsList()); 17654 } 17655 } 17656 } 17657 17658 StringBuilder sb = new StringBuilder(result.size() * 16); 17659 for (String domain : result) { 17660 if (sb.length() > 0) sb.append(" "); 17661 sb.append(domain); 17662 } 17663 return sb.toString(); 17664 } 17665 17666 // ------- apps on sdcard specific code ------- 17667 static final boolean DEBUG_SD_INSTALL = false; 17668 17669 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17670 17671 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17672 17673 private boolean mMediaMounted = false; 17674 17675 static String getEncryptKey() { 17676 try { 17677 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17678 SD_ENCRYPTION_KEYSTORE_NAME); 17679 if (sdEncKey == null) { 17680 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17681 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17682 if (sdEncKey == null) { 17683 Slog.e(TAG, "Failed to create encryption keys"); 17684 return null; 17685 } 17686 } 17687 return sdEncKey; 17688 } catch (NoSuchAlgorithmException nsae) { 17689 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17690 return null; 17691 } catch (IOException ioe) { 17692 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17693 return null; 17694 } 17695 } 17696 17697 /* 17698 * Update media status on PackageManager. 17699 */ 17700 @Override 17701 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17702 int callingUid = Binder.getCallingUid(); 17703 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17704 throw new SecurityException("Media status can only be updated by the system"); 17705 } 17706 // reader; this apparently protects mMediaMounted, but should probably 17707 // be a different lock in that case. 17708 synchronized (mPackages) { 17709 Log.i(TAG, "Updating external media status from " 17710 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17711 + (mediaStatus ? "mounted" : "unmounted")); 17712 if (DEBUG_SD_INSTALL) 17713 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17714 + ", mMediaMounted=" + mMediaMounted); 17715 if (mediaStatus == mMediaMounted) { 17716 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17717 : 0, -1); 17718 mHandler.sendMessage(msg); 17719 return; 17720 } 17721 mMediaMounted = mediaStatus; 17722 } 17723 // Queue up an async operation since the package installation may take a 17724 // little while. 17725 mHandler.post(new Runnable() { 17726 public void run() { 17727 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17728 } 17729 }); 17730 } 17731 17732 /** 17733 * Called by MountService when the initial ASECs to scan are available. 17734 * Should block until all the ASEC containers are finished being scanned. 17735 */ 17736 public void scanAvailableAsecs() { 17737 updateExternalMediaStatusInner(true, false, false); 17738 } 17739 17740 /* 17741 * Collect information of applications on external media, map them against 17742 * existing containers and update information based on current mount status. 17743 * Please note that we always have to report status if reportStatus has been 17744 * set to true especially when unloading packages. 17745 */ 17746 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17747 boolean externalStorage) { 17748 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17749 int[] uidArr = EmptyArray.INT; 17750 17751 final String[] list = PackageHelper.getSecureContainerList(); 17752 if (ArrayUtils.isEmpty(list)) { 17753 Log.i(TAG, "No secure containers found"); 17754 } else { 17755 // Process list of secure containers and categorize them 17756 // as active or stale based on their package internal state. 17757 17758 // reader 17759 synchronized (mPackages) { 17760 for (String cid : list) { 17761 // Leave stages untouched for now; installer service owns them 17762 if (PackageInstallerService.isStageName(cid)) continue; 17763 17764 if (DEBUG_SD_INSTALL) 17765 Log.i(TAG, "Processing container " + cid); 17766 String pkgName = getAsecPackageName(cid); 17767 if (pkgName == null) { 17768 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17769 continue; 17770 } 17771 if (DEBUG_SD_INSTALL) 17772 Log.i(TAG, "Looking for pkg : " + pkgName); 17773 17774 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17775 if (ps == null) { 17776 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17777 continue; 17778 } 17779 17780 /* 17781 * Skip packages that are not external if we're unmounting 17782 * external storage. 17783 */ 17784 if (externalStorage && !isMounted && !isExternal(ps)) { 17785 continue; 17786 } 17787 17788 final AsecInstallArgs args = new AsecInstallArgs(cid, 17789 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17790 // The package status is changed only if the code path 17791 // matches between settings and the container id. 17792 if (ps.codePathString != null 17793 && ps.codePathString.startsWith(args.getCodePath())) { 17794 if (DEBUG_SD_INSTALL) { 17795 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17796 + " at code path: " + ps.codePathString); 17797 } 17798 17799 // We do have a valid package installed on sdcard 17800 processCids.put(args, ps.codePathString); 17801 final int uid = ps.appId; 17802 if (uid != -1) { 17803 uidArr = ArrayUtils.appendInt(uidArr, uid); 17804 } 17805 } else { 17806 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17807 + ps.codePathString); 17808 } 17809 } 17810 } 17811 17812 Arrays.sort(uidArr); 17813 } 17814 17815 // Process packages with valid entries. 17816 if (isMounted) { 17817 if (DEBUG_SD_INSTALL) 17818 Log.i(TAG, "Loading packages"); 17819 loadMediaPackages(processCids, uidArr, externalStorage); 17820 startCleaningPackages(); 17821 mInstallerService.onSecureContainersAvailable(); 17822 } else { 17823 if (DEBUG_SD_INSTALL) 17824 Log.i(TAG, "Unloading packages"); 17825 unloadMediaPackages(processCids, uidArr, reportStatus); 17826 } 17827 } 17828 17829 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17830 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17831 final int size = infos.size(); 17832 final String[] packageNames = new String[size]; 17833 final int[] packageUids = new int[size]; 17834 for (int i = 0; i < size; i++) { 17835 final ApplicationInfo info = infos.get(i); 17836 packageNames[i] = info.packageName; 17837 packageUids[i] = info.uid; 17838 } 17839 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17840 finishedReceiver); 17841 } 17842 17843 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17844 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17845 sendResourcesChangedBroadcast(mediaStatus, replacing, 17846 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17847 } 17848 17849 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17850 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17851 int size = pkgList.length; 17852 if (size > 0) { 17853 // Send broadcasts here 17854 Bundle extras = new Bundle(); 17855 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17856 if (uidArr != null) { 17857 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17858 } 17859 if (replacing) { 17860 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17861 } 17862 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17863 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17864 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17865 } 17866 } 17867 17868 /* 17869 * Look at potentially valid container ids from processCids If package 17870 * information doesn't match the one on record or package scanning fails, 17871 * the cid is added to list of removeCids. We currently don't delete stale 17872 * containers. 17873 */ 17874 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17875 boolean externalStorage) { 17876 ArrayList<String> pkgList = new ArrayList<String>(); 17877 Set<AsecInstallArgs> keys = processCids.keySet(); 17878 17879 for (AsecInstallArgs args : keys) { 17880 String codePath = processCids.get(args); 17881 if (DEBUG_SD_INSTALL) 17882 Log.i(TAG, "Loading container : " + args.cid); 17883 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17884 try { 17885 // Make sure there are no container errors first. 17886 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17887 Slog.e(TAG, "Failed to mount cid : " + args.cid 17888 + " when installing from sdcard"); 17889 continue; 17890 } 17891 // Check code path here. 17892 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17893 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17894 + " does not match one in settings " + codePath); 17895 continue; 17896 } 17897 // Parse package 17898 int parseFlags = mDefParseFlags; 17899 if (args.isExternalAsec()) { 17900 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17901 } 17902 if (args.isFwdLocked()) { 17903 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17904 } 17905 17906 synchronized (mInstallLock) { 17907 PackageParser.Package pkg = null; 17908 try { 17909 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17910 } catch (PackageManagerException e) { 17911 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17912 } 17913 // Scan the package 17914 if (pkg != null) { 17915 /* 17916 * TODO why is the lock being held? doPostInstall is 17917 * called in other places without the lock. This needs 17918 * to be straightened out. 17919 */ 17920 // writer 17921 synchronized (mPackages) { 17922 retCode = PackageManager.INSTALL_SUCCEEDED; 17923 pkgList.add(pkg.packageName); 17924 // Post process args 17925 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17926 pkg.applicationInfo.uid); 17927 } 17928 } else { 17929 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17930 } 17931 } 17932 17933 } finally { 17934 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17935 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17936 } 17937 } 17938 } 17939 // writer 17940 synchronized (mPackages) { 17941 // If the platform SDK has changed since the last time we booted, 17942 // we need to re-grant app permission to catch any new ones that 17943 // appear. This is really a hack, and means that apps can in some 17944 // cases get permissions that the user didn't initially explicitly 17945 // allow... it would be nice to have some better way to handle 17946 // this situation. 17947 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17948 : mSettings.getInternalVersion(); 17949 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17950 : StorageManager.UUID_PRIVATE_INTERNAL; 17951 17952 int updateFlags = UPDATE_PERMISSIONS_ALL; 17953 if (ver.sdkVersion != mSdkVersion) { 17954 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17955 + mSdkVersion + "; regranting permissions for external"); 17956 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17957 } 17958 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17959 17960 // Yay, everything is now upgraded 17961 ver.forceCurrent(); 17962 17963 // can downgrade to reader 17964 // Persist settings 17965 mSettings.writeLPr(); 17966 } 17967 // Send a broadcast to let everyone know we are done processing 17968 if (pkgList.size() > 0) { 17969 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17970 } 17971 } 17972 17973 /* 17974 * Utility method to unload a list of specified containers 17975 */ 17976 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17977 // Just unmount all valid containers. 17978 for (AsecInstallArgs arg : cidArgs) { 17979 synchronized (mInstallLock) { 17980 arg.doPostDeleteLI(false); 17981 } 17982 } 17983 } 17984 17985 /* 17986 * Unload packages mounted on external media. This involves deleting package 17987 * data from internal structures, sending broadcasts about disabled packages, 17988 * gc'ing to free up references, unmounting all secure containers 17989 * corresponding to packages on external media, and posting a 17990 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17991 * that we always have to post this message if status has been requested no 17992 * matter what. 17993 */ 17994 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17995 final boolean reportStatus) { 17996 if (DEBUG_SD_INSTALL) 17997 Log.i(TAG, "unloading media packages"); 17998 ArrayList<String> pkgList = new ArrayList<String>(); 17999 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18000 final Set<AsecInstallArgs> keys = processCids.keySet(); 18001 for (AsecInstallArgs args : keys) { 18002 String pkgName = args.getPackageName(); 18003 if (DEBUG_SD_INSTALL) 18004 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18005 // Delete package internally 18006 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18007 synchronized (mInstallLock) { 18008 boolean res = deletePackageLI(pkgName, null, false, null, 18009 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18010 if (res) { 18011 pkgList.add(pkgName); 18012 } else { 18013 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18014 failedList.add(args); 18015 } 18016 } 18017 } 18018 18019 // reader 18020 synchronized (mPackages) { 18021 // We didn't update the settings after removing each package; 18022 // write them now for all packages. 18023 mSettings.writeLPr(); 18024 } 18025 18026 // We have to absolutely send UPDATED_MEDIA_STATUS only 18027 // after confirming that all the receivers processed the ordered 18028 // broadcast when packages get disabled, force a gc to clean things up. 18029 // and unload all the containers. 18030 if (pkgList.size() > 0) { 18031 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18032 new IIntentReceiver.Stub() { 18033 public void performReceive(Intent intent, int resultCode, String data, 18034 Bundle extras, boolean ordered, boolean sticky, 18035 int sendingUser) throws RemoteException { 18036 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18037 reportStatus ? 1 : 0, 1, keys); 18038 mHandler.sendMessage(msg); 18039 } 18040 }); 18041 } else { 18042 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18043 keys); 18044 mHandler.sendMessage(msg); 18045 } 18046 } 18047 18048 private void loadPrivatePackages(final VolumeInfo vol) { 18049 mHandler.post(new Runnable() { 18050 @Override 18051 public void run() { 18052 loadPrivatePackagesInner(vol); 18053 } 18054 }); 18055 } 18056 18057 private void loadPrivatePackagesInner(VolumeInfo vol) { 18058 final String volumeUuid = vol.fsUuid; 18059 if (TextUtils.isEmpty(volumeUuid)) { 18060 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18061 return; 18062 } 18063 18064 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18065 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18066 18067 final VersionInfo ver; 18068 final List<PackageSetting> packages; 18069 synchronized (mPackages) { 18070 ver = mSettings.findOrCreateVersion(volumeUuid); 18071 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18072 } 18073 18074 // TODO: introduce a new concept similar to "frozen" to prevent these 18075 // apps from being launched until after data has been fully reconciled 18076 for (PackageSetting ps : packages) { 18077 synchronized (mInstallLock) { 18078 final PackageParser.Package pkg; 18079 try { 18080 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18081 loaded.add(pkg.applicationInfo); 18082 18083 } catch (PackageManagerException e) { 18084 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18085 } 18086 18087 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18088 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18089 } 18090 } 18091 } 18092 18093 // Reconcile app data for all started/unlocked users 18094 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18095 final UserManager um = mContext.getSystemService(UserManager.class); 18096 for (UserInfo user : um.getUsers()) { 18097 final int flags; 18098 if (um.isUserUnlocked(user.id)) { 18099 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18100 } else if (um.isUserRunning(user.id)) { 18101 flags = StorageManager.FLAG_STORAGE_DE; 18102 } else { 18103 continue; 18104 } 18105 18106 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18107 reconcileAppsData(volumeUuid, user.id, flags); 18108 } 18109 18110 synchronized (mPackages) { 18111 int updateFlags = UPDATE_PERMISSIONS_ALL; 18112 if (ver.sdkVersion != mSdkVersion) { 18113 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18114 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18115 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18116 } 18117 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18118 18119 // Yay, everything is now upgraded 18120 ver.forceCurrent(); 18121 18122 mSettings.writeLPr(); 18123 } 18124 18125 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18126 sendResourcesChangedBroadcast(true, false, loaded, null); 18127 } 18128 18129 private void unloadPrivatePackages(final VolumeInfo vol) { 18130 mHandler.post(new Runnable() { 18131 @Override 18132 public void run() { 18133 unloadPrivatePackagesInner(vol); 18134 } 18135 }); 18136 } 18137 18138 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18139 final String volumeUuid = vol.fsUuid; 18140 if (TextUtils.isEmpty(volumeUuid)) { 18141 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18142 return; 18143 } 18144 18145 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18146 synchronized (mInstallLock) { 18147 synchronized (mPackages) { 18148 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18149 for (PackageSetting ps : packages) { 18150 if (ps.pkg == null) continue; 18151 18152 final ApplicationInfo info = ps.pkg.applicationInfo; 18153 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18154 if (deletePackageLI(ps.name, null, false, null, 18155 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18156 unloaded.add(info); 18157 } else { 18158 Slog.w(TAG, "Failed to unload " + ps.codePath); 18159 } 18160 } 18161 18162 mSettings.writeLPr(); 18163 } 18164 } 18165 18166 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18167 sendResourcesChangedBroadcast(false, false, unloaded, null); 18168 } 18169 18170 /** 18171 * Examine all users present on given mounted volume, and destroy data 18172 * belonging to users that are no longer valid, or whose user ID has been 18173 * recycled. 18174 */ 18175 private void reconcileUsers(String volumeUuid) { 18176 // TODO: also reconcile DE directories 18177 final File[] files = FileUtils 18178 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18179 for (File file : files) { 18180 if (!file.isDirectory()) continue; 18181 18182 final int userId; 18183 final UserInfo info; 18184 try { 18185 userId = Integer.parseInt(file.getName()); 18186 info = sUserManager.getUserInfo(userId); 18187 } catch (NumberFormatException e) { 18188 Slog.w(TAG, "Invalid user directory " + file); 18189 continue; 18190 } 18191 18192 boolean destroyUser = false; 18193 if (info == null) { 18194 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18195 + " because no matching user was found"); 18196 destroyUser = true; 18197 } else { 18198 try { 18199 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18200 } catch (IOException e) { 18201 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18202 + " because we failed to enforce serial number: " + e); 18203 destroyUser = true; 18204 } 18205 } 18206 18207 if (destroyUser) { 18208 synchronized (mInstallLock) { 18209 try { 18210 mInstaller.removeUserDataDirs(volumeUuid, userId); 18211 } catch (InstallerException e) { 18212 Slog.w(TAG, "Failed to clean up user dirs", e); 18213 } 18214 } 18215 } 18216 } 18217 } 18218 18219 private void assertPackageKnown(String volumeUuid, String packageName) 18220 throws PackageManagerException { 18221 synchronized (mPackages) { 18222 final PackageSetting ps = mSettings.mPackages.get(packageName); 18223 if (ps == null) { 18224 throw new PackageManagerException("Package " + packageName + " is unknown"); 18225 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18226 throw new PackageManagerException( 18227 "Package " + packageName + " found on unknown volume " + volumeUuid 18228 + "; expected volume " + ps.volumeUuid); 18229 } 18230 } 18231 } 18232 18233 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18234 throws PackageManagerException { 18235 synchronized (mPackages) { 18236 final PackageSetting ps = mSettings.mPackages.get(packageName); 18237 if (ps == null) { 18238 throw new PackageManagerException("Package " + packageName + " is unknown"); 18239 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18240 throw new PackageManagerException( 18241 "Package " + packageName + " found on unknown volume " + volumeUuid 18242 + "; expected volume " + ps.volumeUuid); 18243 } else if (!ps.getInstalled(userId)) { 18244 throw new PackageManagerException( 18245 "Package " + packageName + " not installed for user " + userId); 18246 } 18247 } 18248 } 18249 18250 /** 18251 * Examine all apps present on given mounted volume, and destroy apps that 18252 * aren't expected, either due to uninstallation or reinstallation on 18253 * another volume. 18254 */ 18255 private void reconcileApps(String volumeUuid) { 18256 final File[] files = FileUtils 18257 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18258 for (File file : files) { 18259 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18260 && !PackageInstallerService.isStageName(file.getName()); 18261 if (!isPackage) { 18262 // Ignore entries which are not packages 18263 continue; 18264 } 18265 18266 try { 18267 final PackageLite pkg = PackageParser.parsePackageLite(file, 18268 PackageParser.PARSE_MUST_BE_APK); 18269 assertPackageKnown(volumeUuid, pkg.packageName); 18270 18271 } catch (PackageParserException | PackageManagerException e) { 18272 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18273 synchronized (mInstallLock) { 18274 removeCodePathLI(file); 18275 } 18276 } 18277 } 18278 } 18279 18280 /** 18281 * Reconcile all app data for the given user. 18282 * <p> 18283 * Verifies that directories exist and that ownership and labeling is 18284 * correct for all installed apps on all mounted volumes. 18285 */ 18286 void reconcileAppsData(int userId, int flags) { 18287 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18288 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18289 final String volumeUuid = vol.getFsUuid(); 18290 reconcileAppsData(volumeUuid, userId, flags); 18291 } 18292 } 18293 18294 /** 18295 * Reconcile all app data on given mounted volume. 18296 * <p> 18297 * Destroys app data that isn't expected, either due to uninstallation or 18298 * reinstallation on another volume. 18299 * <p> 18300 * Verifies that directories exist and that ownership and labeling is 18301 * correct for all installed apps. 18302 */ 18303 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18304 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18305 + Integer.toHexString(flags)); 18306 18307 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18308 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18309 18310 boolean restoreconNeeded = false; 18311 18312 // First look for stale data that doesn't belong, and check if things 18313 // have changed since we did our last restorecon 18314 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18315 if (!isUserKeyUnlocked(userId)) { 18316 throw new RuntimeException( 18317 "Yikes, someone asked us to reconcile CE storage while " + userId 18318 + " was still locked; this would have caused massive data loss!"); 18319 } 18320 18321 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18322 18323 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18324 for (File file : files) { 18325 final String packageName = file.getName(); 18326 try { 18327 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18328 } catch (PackageManagerException e) { 18329 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18330 synchronized (mInstallLock) { 18331 destroyAppDataLI(volumeUuid, packageName, userId, 18332 StorageManager.FLAG_STORAGE_CE); 18333 } 18334 } 18335 } 18336 } 18337 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18338 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18339 18340 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18341 for (File file : files) { 18342 final String packageName = file.getName(); 18343 try { 18344 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18345 } catch (PackageManagerException e) { 18346 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18347 synchronized (mInstallLock) { 18348 destroyAppDataLI(volumeUuid, packageName, userId, 18349 StorageManager.FLAG_STORAGE_DE); 18350 } 18351 } 18352 } 18353 } 18354 18355 // Ensure that data directories are ready to roll for all packages 18356 // installed for this volume and user 18357 final List<PackageSetting> packages; 18358 synchronized (mPackages) { 18359 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18360 } 18361 int preparedCount = 0; 18362 for (PackageSetting ps : packages) { 18363 final String packageName = ps.name; 18364 if (ps.pkg == null) { 18365 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18366 // TODO: might be due to legacy ASEC apps; we should circle back 18367 // and reconcile again once they're scanned 18368 continue; 18369 } 18370 18371 if (ps.getInstalled(userId)) { 18372 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18373 18374 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18375 // We may have just shuffled around app data directories, so 18376 // prepare them one more time 18377 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18378 } 18379 18380 preparedCount++; 18381 } 18382 } 18383 18384 if (restoreconNeeded) { 18385 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18386 SELinuxMMAC.setRestoreconDone(ceDir); 18387 } 18388 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18389 SELinuxMMAC.setRestoreconDone(deDir); 18390 } 18391 } 18392 18393 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18394 + " packages; restoreconNeeded was " + restoreconNeeded); 18395 } 18396 18397 /** 18398 * Prepare app data for the given app just after it was installed or 18399 * upgraded. This method carefully only touches users that it's installed 18400 * for, and it forces a restorecon to handle any seinfo changes. 18401 * <p> 18402 * Verifies that directories exist and that ownership and labeling is 18403 * correct for all installed apps. If there is an ownership mismatch, it 18404 * will try recovering system apps by wiping data; third-party app data is 18405 * left intact. 18406 * <p> 18407 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18408 */ 18409 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18410 prepareAppDataAfterInstallInternal(pkg); 18411 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18412 for (int i = 0; i < childCount; i++) { 18413 PackageParser.Package childPackage = pkg.childPackages.get(i); 18414 prepareAppDataAfterInstallInternal(childPackage); 18415 } 18416 } 18417 18418 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18419 final PackageSetting ps; 18420 synchronized (mPackages) { 18421 ps = mSettings.mPackages.get(pkg.packageName); 18422 mSettings.writeKernelMappingLPr(ps); 18423 } 18424 18425 final UserManager um = mContext.getSystemService(UserManager.class); 18426 for (UserInfo user : um.getUsers()) { 18427 final int flags; 18428 if (um.isUserUnlocked(user.id)) { 18429 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18430 } else if (um.isUserRunning(user.id)) { 18431 flags = StorageManager.FLAG_STORAGE_DE; 18432 } else { 18433 continue; 18434 } 18435 18436 if (ps.getInstalled(user.id)) { 18437 // Whenever an app changes, force a restorecon of its data 18438 // TODO: when user data is locked, mark that we're still dirty 18439 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18440 } 18441 } 18442 } 18443 18444 /** 18445 * Prepare app data for the given app. 18446 * <p> 18447 * Verifies that directories exist and that ownership and labeling is 18448 * correct for all installed apps. If there is an ownership mismatch, this 18449 * will try recovering system apps by wiping data; third-party app data is 18450 * left intact. 18451 */ 18452 private void prepareAppData(String volumeUuid, int userId, int flags, 18453 PackageParser.Package pkg, boolean restoreconNeeded) { 18454 if (DEBUG_APP_DATA) { 18455 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18456 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18457 } 18458 18459 final String packageName = pkg.packageName; 18460 final ApplicationInfo app = pkg.applicationInfo; 18461 final int appId = UserHandle.getAppId(app.uid); 18462 18463 Preconditions.checkNotNull(app.seinfo); 18464 18465 synchronized (mInstallLock) { 18466 try { 18467 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18468 appId, app.seinfo, app.targetSdkVersion); 18469 } catch (InstallerException e) { 18470 if (app.isSystemApp()) { 18471 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18472 + ", but trying to recover: " + e); 18473 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18474 try { 18475 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18476 appId, app.seinfo, app.targetSdkVersion); 18477 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18478 } catch (InstallerException e2) { 18479 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18480 } 18481 } else { 18482 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18483 } 18484 } 18485 18486 if (restoreconNeeded) { 18487 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18488 } 18489 18490 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18491 // Create a native library symlink only if we have native libraries 18492 // and if the native libraries are 32 bit libraries. We do not provide 18493 // this symlink for 64 bit libraries. 18494 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18495 final String nativeLibPath = app.nativeLibraryDir; 18496 try { 18497 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18498 nativeLibPath, userId); 18499 } catch (InstallerException e) { 18500 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18501 } 18502 } 18503 } 18504 } 18505 } 18506 18507 /** 18508 * For system apps on non-FBE devices, this method migrates any existing 18509 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18510 * requested by the app. 18511 */ 18512 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18513 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18514 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18515 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18516 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18517 synchronized (mInstallLock) { 18518 try { 18519 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18520 } catch (InstallerException e) { 18521 logCriticalInfo(Log.WARN, 18522 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18523 } 18524 } 18525 return true; 18526 } else { 18527 return false; 18528 } 18529 } 18530 18531 private void unfreezePackage(String packageName) { 18532 synchronized (mPackages) { 18533 final PackageSetting ps = mSettings.mPackages.get(packageName); 18534 if (ps != null) { 18535 ps.frozen = false; 18536 } 18537 } 18538 } 18539 18540 @Override 18541 public int movePackage(final String packageName, final String volumeUuid) { 18542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18543 18544 final int moveId = mNextMoveId.getAndIncrement(); 18545 mHandler.post(new Runnable() { 18546 @Override 18547 public void run() { 18548 try { 18549 movePackageInternal(packageName, volumeUuid, moveId); 18550 } catch (PackageManagerException e) { 18551 Slog.w(TAG, "Failed to move " + packageName, e); 18552 mMoveCallbacks.notifyStatusChanged(moveId, 18553 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18554 } 18555 } 18556 }); 18557 return moveId; 18558 } 18559 18560 private void movePackageInternal(final String packageName, final String volumeUuid, 18561 final int moveId) throws PackageManagerException { 18562 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18563 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18564 final PackageManager pm = mContext.getPackageManager(); 18565 18566 final boolean currentAsec; 18567 final String currentVolumeUuid; 18568 final File codeFile; 18569 final String installerPackageName; 18570 final String packageAbiOverride; 18571 final int appId; 18572 final String seinfo; 18573 final String label; 18574 final int targetSdkVersion; 18575 18576 // reader 18577 synchronized (mPackages) { 18578 final PackageParser.Package pkg = mPackages.get(packageName); 18579 final PackageSetting ps = mSettings.mPackages.get(packageName); 18580 if (pkg == null || ps == null) { 18581 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18582 } 18583 18584 if (pkg.applicationInfo.isSystemApp()) { 18585 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18586 "Cannot move system application"); 18587 } 18588 18589 if (pkg.applicationInfo.isExternalAsec()) { 18590 currentAsec = true; 18591 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18592 } else if (pkg.applicationInfo.isForwardLocked()) { 18593 currentAsec = true; 18594 currentVolumeUuid = "forward_locked"; 18595 } else { 18596 currentAsec = false; 18597 currentVolumeUuid = ps.volumeUuid; 18598 18599 final File probe = new File(pkg.codePath); 18600 final File probeOat = new File(probe, "oat"); 18601 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18602 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18603 "Move only supported for modern cluster style installs"); 18604 } 18605 } 18606 18607 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18608 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18609 "Package already moved to " + volumeUuid); 18610 } 18611 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18612 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18613 "Device admin cannot be moved"); 18614 } 18615 18616 if (ps.frozen) { 18617 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18618 "Failed to move already frozen package"); 18619 } 18620 ps.frozen = true; 18621 18622 codeFile = new File(pkg.codePath); 18623 installerPackageName = ps.installerPackageName; 18624 packageAbiOverride = ps.cpuAbiOverrideString; 18625 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18626 seinfo = pkg.applicationInfo.seinfo; 18627 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18628 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18629 } 18630 18631 // Now that we're guarded by frozen state, kill app during move 18632 final long token = Binder.clearCallingIdentity(); 18633 try { 18634 killApplication(packageName, appId, "move pkg"); 18635 } finally { 18636 Binder.restoreCallingIdentity(token); 18637 } 18638 18639 final Bundle extras = new Bundle(); 18640 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18641 extras.putString(Intent.EXTRA_TITLE, label); 18642 mMoveCallbacks.notifyCreated(moveId, extras); 18643 18644 int installFlags; 18645 final boolean moveCompleteApp; 18646 final File measurePath; 18647 18648 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18649 installFlags = INSTALL_INTERNAL; 18650 moveCompleteApp = !currentAsec; 18651 measurePath = Environment.getDataAppDirectory(volumeUuid); 18652 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18653 installFlags = INSTALL_EXTERNAL; 18654 moveCompleteApp = false; 18655 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18656 } else { 18657 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18658 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18659 || !volume.isMountedWritable()) { 18660 unfreezePackage(packageName); 18661 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18662 "Move location not mounted private volume"); 18663 } 18664 18665 Preconditions.checkState(!currentAsec); 18666 18667 installFlags = INSTALL_INTERNAL; 18668 moveCompleteApp = true; 18669 measurePath = Environment.getDataAppDirectory(volumeUuid); 18670 } 18671 18672 final PackageStats stats = new PackageStats(null, -1); 18673 synchronized (mInstaller) { 18674 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18675 unfreezePackage(packageName); 18676 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18677 "Failed to measure package size"); 18678 } 18679 } 18680 18681 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18682 + stats.dataSize); 18683 18684 final long startFreeBytes = measurePath.getFreeSpace(); 18685 final long sizeBytes; 18686 if (moveCompleteApp) { 18687 sizeBytes = stats.codeSize + stats.dataSize; 18688 } else { 18689 sizeBytes = stats.codeSize; 18690 } 18691 18692 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18693 unfreezePackage(packageName); 18694 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18695 "Not enough free space to move"); 18696 } 18697 18698 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18699 18700 final CountDownLatch installedLatch = new CountDownLatch(1); 18701 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18702 @Override 18703 public void onUserActionRequired(Intent intent) throws RemoteException { 18704 throw new IllegalStateException(); 18705 } 18706 18707 @Override 18708 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18709 Bundle extras) throws RemoteException { 18710 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18711 + PackageManager.installStatusToString(returnCode, msg)); 18712 18713 installedLatch.countDown(); 18714 18715 // Regardless of success or failure of the move operation, 18716 // always unfreeze the package 18717 unfreezePackage(packageName); 18718 18719 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18720 switch (status) { 18721 case PackageInstaller.STATUS_SUCCESS: 18722 mMoveCallbacks.notifyStatusChanged(moveId, 18723 PackageManager.MOVE_SUCCEEDED); 18724 break; 18725 case PackageInstaller.STATUS_FAILURE_STORAGE: 18726 mMoveCallbacks.notifyStatusChanged(moveId, 18727 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18728 break; 18729 default: 18730 mMoveCallbacks.notifyStatusChanged(moveId, 18731 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18732 break; 18733 } 18734 } 18735 }; 18736 18737 final MoveInfo move; 18738 if (moveCompleteApp) { 18739 // Kick off a thread to report progress estimates 18740 new Thread() { 18741 @Override 18742 public void run() { 18743 while (true) { 18744 try { 18745 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18746 break; 18747 } 18748 } catch (InterruptedException ignored) { 18749 } 18750 18751 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18752 final int progress = 10 + (int) MathUtils.constrain( 18753 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18754 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18755 } 18756 } 18757 }.start(); 18758 18759 final String dataAppName = codeFile.getName(); 18760 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18761 dataAppName, appId, seinfo, targetSdkVersion); 18762 } else { 18763 move = null; 18764 } 18765 18766 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18767 18768 final Message msg = mHandler.obtainMessage(INIT_COPY); 18769 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18770 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18771 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18772 packageAbiOverride, null); 18773 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18774 msg.obj = params; 18775 18776 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18777 System.identityHashCode(msg.obj)); 18778 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18779 System.identityHashCode(msg.obj)); 18780 18781 mHandler.sendMessage(msg); 18782 } 18783 18784 @Override 18785 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18787 18788 final int realMoveId = mNextMoveId.getAndIncrement(); 18789 final Bundle extras = new Bundle(); 18790 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18791 mMoveCallbacks.notifyCreated(realMoveId, extras); 18792 18793 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18794 @Override 18795 public void onCreated(int moveId, Bundle extras) { 18796 // Ignored 18797 } 18798 18799 @Override 18800 public void onStatusChanged(int moveId, int status, long estMillis) { 18801 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18802 } 18803 }; 18804 18805 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18806 storage.setPrimaryStorageUuid(volumeUuid, callback); 18807 return realMoveId; 18808 } 18809 18810 @Override 18811 public int getMoveStatus(int moveId) { 18812 mContext.enforceCallingOrSelfPermission( 18813 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18814 return mMoveCallbacks.mLastStatus.get(moveId); 18815 } 18816 18817 @Override 18818 public void registerMoveCallback(IPackageMoveObserver callback) { 18819 mContext.enforceCallingOrSelfPermission( 18820 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18821 mMoveCallbacks.register(callback); 18822 } 18823 18824 @Override 18825 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18826 mContext.enforceCallingOrSelfPermission( 18827 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18828 mMoveCallbacks.unregister(callback); 18829 } 18830 18831 @Override 18832 public boolean setInstallLocation(int loc) { 18833 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18834 null); 18835 if (getInstallLocation() == loc) { 18836 return true; 18837 } 18838 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18839 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18840 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18841 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18842 return true; 18843 } 18844 return false; 18845 } 18846 18847 @Override 18848 public int getInstallLocation() { 18849 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18850 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18851 PackageHelper.APP_INSTALL_AUTO); 18852 } 18853 18854 /** Called by UserManagerService */ 18855 void cleanUpUser(UserManagerService userManager, int userHandle) { 18856 synchronized (mPackages) { 18857 mDirtyUsers.remove(userHandle); 18858 mUserNeedsBadging.delete(userHandle); 18859 mSettings.removeUserLPw(userHandle); 18860 mPendingBroadcasts.remove(userHandle); 18861 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18862 } 18863 synchronized (mInstallLock) { 18864 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18865 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18866 final String volumeUuid = vol.getFsUuid(); 18867 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18868 try { 18869 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18870 } catch (InstallerException e) { 18871 Slog.w(TAG, "Failed to remove user data", e); 18872 } 18873 } 18874 synchronized (mPackages) { 18875 removeUnusedPackagesLILPw(userManager, userHandle); 18876 } 18877 } 18878 } 18879 18880 /** 18881 * We're removing userHandle and would like to remove any downloaded packages 18882 * that are no longer in use by any other user. 18883 * @param userHandle the user being removed 18884 */ 18885 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18886 final boolean DEBUG_CLEAN_APKS = false; 18887 int [] users = userManager.getUserIds(); 18888 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18889 while (psit.hasNext()) { 18890 PackageSetting ps = psit.next(); 18891 if (ps.pkg == null) { 18892 continue; 18893 } 18894 final String packageName = ps.pkg.packageName; 18895 // Skip over if system app 18896 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18897 continue; 18898 } 18899 if (DEBUG_CLEAN_APKS) { 18900 Slog.i(TAG, "Checking package " + packageName); 18901 } 18902 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18903 if (keep) { 18904 if (DEBUG_CLEAN_APKS) { 18905 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18906 } 18907 } else { 18908 for (int i = 0; i < users.length; i++) { 18909 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18910 keep = true; 18911 if (DEBUG_CLEAN_APKS) { 18912 Slog.i(TAG, " Keeping package " + packageName + " for user " 18913 + users[i]); 18914 } 18915 break; 18916 } 18917 } 18918 } 18919 if (!keep) { 18920 if (DEBUG_CLEAN_APKS) { 18921 Slog.i(TAG, " Removing package " + packageName); 18922 } 18923 mHandler.post(new Runnable() { 18924 public void run() { 18925 deletePackageX(packageName, userHandle, 0); 18926 } //end run 18927 }); 18928 } 18929 } 18930 } 18931 18932 /** Called by UserManagerService */ 18933 void createNewUser(int userHandle) { 18934 synchronized (mInstallLock) { 18935 try { 18936 mInstaller.createUserConfig(userHandle); 18937 } catch (InstallerException e) { 18938 Slog.w(TAG, "Failed to create user config", e); 18939 } 18940 mSettings.createNewUserLI(this, mInstaller, userHandle); 18941 } 18942 synchronized (mPackages) { 18943 applyFactoryDefaultBrowserLPw(userHandle); 18944 primeDomainVerificationsLPw(userHandle); 18945 } 18946 } 18947 18948 void newUserCreated(final int userHandle) { 18949 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18950 // If permission review for legacy apps is required, we represent 18951 // dagerous permissions for such apps as always granted runtime 18952 // permissions to keep per user flag state whether review is needed. 18953 // Hence, if a new user is added we have to propagate dangerous 18954 // permission grants for these legacy apps. 18955 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18956 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18957 | UPDATE_PERMISSIONS_REPLACE_ALL); 18958 } 18959 } 18960 18961 @Override 18962 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18963 mContext.enforceCallingOrSelfPermission( 18964 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18965 "Only package verification agents can read the verifier device identity"); 18966 18967 synchronized (mPackages) { 18968 return mSettings.getVerifierDeviceIdentityLPw(); 18969 } 18970 } 18971 18972 @Override 18973 public void setPermissionEnforced(String permission, boolean enforced) { 18974 // TODO: Now that we no longer change GID for storage, this should to away. 18975 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18976 "setPermissionEnforced"); 18977 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18978 synchronized (mPackages) { 18979 if (mSettings.mReadExternalStorageEnforced == null 18980 || mSettings.mReadExternalStorageEnforced != enforced) { 18981 mSettings.mReadExternalStorageEnforced = enforced; 18982 mSettings.writeLPr(); 18983 } 18984 } 18985 // kill any non-foreground processes so we restart them and 18986 // grant/revoke the GID. 18987 final IActivityManager am = ActivityManagerNative.getDefault(); 18988 if (am != null) { 18989 final long token = Binder.clearCallingIdentity(); 18990 try { 18991 am.killProcessesBelowForeground("setPermissionEnforcement"); 18992 } catch (RemoteException e) { 18993 } finally { 18994 Binder.restoreCallingIdentity(token); 18995 } 18996 } 18997 } else { 18998 throw new IllegalArgumentException("No selective enforcement for " + permission); 18999 } 19000 } 19001 19002 @Override 19003 @Deprecated 19004 public boolean isPermissionEnforced(String permission) { 19005 return true; 19006 } 19007 19008 @Override 19009 public boolean isStorageLow() { 19010 final long token = Binder.clearCallingIdentity(); 19011 try { 19012 final DeviceStorageMonitorInternal 19013 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19014 if (dsm != null) { 19015 return dsm.isMemoryLow(); 19016 } else { 19017 return false; 19018 } 19019 } finally { 19020 Binder.restoreCallingIdentity(token); 19021 } 19022 } 19023 19024 @Override 19025 public IPackageInstaller getPackageInstaller() { 19026 return mInstallerService; 19027 } 19028 19029 private boolean userNeedsBadging(int userId) { 19030 int index = mUserNeedsBadging.indexOfKey(userId); 19031 if (index < 0) { 19032 final UserInfo userInfo; 19033 final long token = Binder.clearCallingIdentity(); 19034 try { 19035 userInfo = sUserManager.getUserInfo(userId); 19036 } finally { 19037 Binder.restoreCallingIdentity(token); 19038 } 19039 final boolean b; 19040 if (userInfo != null && userInfo.isManagedProfile()) { 19041 b = true; 19042 } else { 19043 b = false; 19044 } 19045 mUserNeedsBadging.put(userId, b); 19046 return b; 19047 } 19048 return mUserNeedsBadging.valueAt(index); 19049 } 19050 19051 @Override 19052 public KeySet getKeySetByAlias(String packageName, String alias) { 19053 if (packageName == null || alias == null) { 19054 return null; 19055 } 19056 synchronized(mPackages) { 19057 final PackageParser.Package pkg = mPackages.get(packageName); 19058 if (pkg == null) { 19059 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19060 throw new IllegalArgumentException("Unknown package: " + packageName); 19061 } 19062 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19063 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19064 } 19065 } 19066 19067 @Override 19068 public KeySet getSigningKeySet(String packageName) { 19069 if (packageName == null) { 19070 return null; 19071 } 19072 synchronized(mPackages) { 19073 final PackageParser.Package pkg = mPackages.get(packageName); 19074 if (pkg == null) { 19075 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19076 throw new IllegalArgumentException("Unknown package: " + packageName); 19077 } 19078 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19079 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19080 throw new SecurityException("May not access signing KeySet of other apps."); 19081 } 19082 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19083 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19084 } 19085 } 19086 19087 @Override 19088 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19089 if (packageName == null || ks == null) { 19090 return false; 19091 } 19092 synchronized(mPackages) { 19093 final PackageParser.Package pkg = mPackages.get(packageName); 19094 if (pkg == null) { 19095 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19096 throw new IllegalArgumentException("Unknown package: " + packageName); 19097 } 19098 IBinder ksh = ks.getToken(); 19099 if (ksh instanceof KeySetHandle) { 19100 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19101 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19102 } 19103 return false; 19104 } 19105 } 19106 19107 @Override 19108 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19109 if (packageName == null || ks == null) { 19110 return false; 19111 } 19112 synchronized(mPackages) { 19113 final PackageParser.Package pkg = mPackages.get(packageName); 19114 if (pkg == null) { 19115 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19116 throw new IllegalArgumentException("Unknown package: " + packageName); 19117 } 19118 IBinder ksh = ks.getToken(); 19119 if (ksh instanceof KeySetHandle) { 19120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19121 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19122 } 19123 return false; 19124 } 19125 } 19126 19127 private void deletePackageIfUnusedLPr(final String packageName) { 19128 PackageSetting ps = mSettings.mPackages.get(packageName); 19129 if (ps == null) { 19130 return; 19131 } 19132 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19133 // TODO Implement atomic delete if package is unused 19134 // It is currently possible that the package will be deleted even if it is installed 19135 // after this method returns. 19136 mHandler.post(new Runnable() { 19137 public void run() { 19138 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19139 } 19140 }); 19141 } 19142 } 19143 19144 /** 19145 * Check and throw if the given before/after packages would be considered a 19146 * downgrade. 19147 */ 19148 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19149 throws PackageManagerException { 19150 if (after.versionCode < before.mVersionCode) { 19151 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19152 "Update version code " + after.versionCode + " is older than current " 19153 + before.mVersionCode); 19154 } else if (after.versionCode == before.mVersionCode) { 19155 if (after.baseRevisionCode < before.baseRevisionCode) { 19156 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19157 "Update base revision code " + after.baseRevisionCode 19158 + " is older than current " + before.baseRevisionCode); 19159 } 19160 19161 if (!ArrayUtils.isEmpty(after.splitNames)) { 19162 for (int i = 0; i < after.splitNames.length; i++) { 19163 final String splitName = after.splitNames[i]; 19164 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19165 if (j != -1) { 19166 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19167 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19168 "Update split " + splitName + " revision code " 19169 + after.splitRevisionCodes[i] + " is older than current " 19170 + before.splitRevisionCodes[j]); 19171 } 19172 } 19173 } 19174 } 19175 } 19176 } 19177 19178 private static class MoveCallbacks extends Handler { 19179 private static final int MSG_CREATED = 1; 19180 private static final int MSG_STATUS_CHANGED = 2; 19181 19182 private final RemoteCallbackList<IPackageMoveObserver> 19183 mCallbacks = new RemoteCallbackList<>(); 19184 19185 private final SparseIntArray mLastStatus = new SparseIntArray(); 19186 19187 public MoveCallbacks(Looper looper) { 19188 super(looper); 19189 } 19190 19191 public void register(IPackageMoveObserver callback) { 19192 mCallbacks.register(callback); 19193 } 19194 19195 public void unregister(IPackageMoveObserver callback) { 19196 mCallbacks.unregister(callback); 19197 } 19198 19199 @Override 19200 public void handleMessage(Message msg) { 19201 final SomeArgs args = (SomeArgs) msg.obj; 19202 final int n = mCallbacks.beginBroadcast(); 19203 for (int i = 0; i < n; i++) { 19204 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19205 try { 19206 invokeCallback(callback, msg.what, args); 19207 } catch (RemoteException ignored) { 19208 } 19209 } 19210 mCallbacks.finishBroadcast(); 19211 args.recycle(); 19212 } 19213 19214 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19215 throws RemoteException { 19216 switch (what) { 19217 case MSG_CREATED: { 19218 callback.onCreated(args.argi1, (Bundle) args.arg2); 19219 break; 19220 } 19221 case MSG_STATUS_CHANGED: { 19222 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19223 break; 19224 } 19225 } 19226 } 19227 19228 private void notifyCreated(int moveId, Bundle extras) { 19229 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19230 19231 final SomeArgs args = SomeArgs.obtain(); 19232 args.argi1 = moveId; 19233 args.arg2 = extras; 19234 obtainMessage(MSG_CREATED, args).sendToTarget(); 19235 } 19236 19237 private void notifyStatusChanged(int moveId, int status) { 19238 notifyStatusChanged(moveId, status, -1); 19239 } 19240 19241 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19242 Slog.v(TAG, "Move " + moveId + " status " + status); 19243 19244 final SomeArgs args = SomeArgs.obtain(); 19245 args.argi1 = moveId; 19246 args.argi2 = status; 19247 args.arg3 = estMillis; 19248 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19249 19250 synchronized (mLastStatus) { 19251 mLastStatus.put(moveId, status); 19252 } 19253 } 19254 } 19255 19256 private final static class OnPermissionChangeListeners extends Handler { 19257 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19258 19259 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19260 new RemoteCallbackList<>(); 19261 19262 public OnPermissionChangeListeners(Looper looper) { 19263 super(looper); 19264 } 19265 19266 @Override 19267 public void handleMessage(Message msg) { 19268 switch (msg.what) { 19269 case MSG_ON_PERMISSIONS_CHANGED: { 19270 final int uid = msg.arg1; 19271 handleOnPermissionsChanged(uid); 19272 } break; 19273 } 19274 } 19275 19276 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19277 mPermissionListeners.register(listener); 19278 19279 } 19280 19281 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19282 mPermissionListeners.unregister(listener); 19283 } 19284 19285 public void onPermissionsChanged(int uid) { 19286 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19287 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19288 } 19289 } 19290 19291 private void handleOnPermissionsChanged(int uid) { 19292 final int count = mPermissionListeners.beginBroadcast(); 19293 try { 19294 for (int i = 0; i < count; i++) { 19295 IOnPermissionsChangeListener callback = mPermissionListeners 19296 .getBroadcastItem(i); 19297 try { 19298 callback.onPermissionsChanged(uid); 19299 } catch (RemoteException e) { 19300 Log.e(TAG, "Permission listener is dead", e); 19301 } 19302 } 19303 } finally { 19304 mPermissionListeners.finishBroadcast(); 19305 } 19306 } 19307 } 19308 19309 private class PackageManagerInternalImpl extends PackageManagerInternal { 19310 @Override 19311 public void setLocationPackagesProvider(PackagesProvider provider) { 19312 synchronized (mPackages) { 19313 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19314 } 19315 } 19316 19317 @Override 19318 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19319 synchronized (mPackages) { 19320 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19321 } 19322 } 19323 19324 @Override 19325 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19326 synchronized (mPackages) { 19327 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19328 } 19329 } 19330 19331 @Override 19332 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19333 synchronized (mPackages) { 19334 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19335 } 19336 } 19337 19338 @Override 19339 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19340 synchronized (mPackages) { 19341 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19342 } 19343 } 19344 19345 @Override 19346 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19347 synchronized (mPackages) { 19348 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19349 } 19350 } 19351 19352 @Override 19353 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19354 synchronized (mPackages) { 19355 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19356 packageName, userId); 19357 } 19358 } 19359 19360 @Override 19361 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19362 synchronized (mPackages) { 19363 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19364 packageName, userId); 19365 } 19366 } 19367 19368 @Override 19369 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19370 synchronized (mPackages) { 19371 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19372 packageName, userId); 19373 } 19374 } 19375 19376 @Override 19377 public void setKeepUninstalledPackages(final List<String> packageList) { 19378 Preconditions.checkNotNull(packageList); 19379 List<String> removedFromList = null; 19380 synchronized (mPackages) { 19381 if (mKeepUninstalledPackages != null) { 19382 final int packagesCount = mKeepUninstalledPackages.size(); 19383 for (int i = 0; i < packagesCount; i++) { 19384 String oldPackage = mKeepUninstalledPackages.get(i); 19385 if (packageList != null && packageList.contains(oldPackage)) { 19386 continue; 19387 } 19388 if (removedFromList == null) { 19389 removedFromList = new ArrayList<>(); 19390 } 19391 removedFromList.add(oldPackage); 19392 } 19393 } 19394 mKeepUninstalledPackages = new ArrayList<>(packageList); 19395 if (removedFromList != null) { 19396 final int removedCount = removedFromList.size(); 19397 for (int i = 0; i < removedCount; i++) { 19398 deletePackageIfUnusedLPr(removedFromList.get(i)); 19399 } 19400 } 19401 } 19402 } 19403 19404 @Override 19405 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19406 synchronized (mPackages) { 19407 // If we do not support permission review, done. 19408 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19409 return false; 19410 } 19411 19412 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19413 if (packageSetting == null) { 19414 return false; 19415 } 19416 19417 // Permission review applies only to apps not supporting the new permission model. 19418 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19419 return false; 19420 } 19421 19422 // Legacy apps have the permission and get user consent on launch. 19423 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19424 return permissionsState.isPermissionReviewRequired(userId); 19425 } 19426 } 19427 19428 @Override 19429 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19430 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19431 } 19432 19433 @Override 19434 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19435 int userId) { 19436 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19437 } 19438 } 19439 19440 @Override 19441 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19442 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19443 synchronized (mPackages) { 19444 final long identity = Binder.clearCallingIdentity(); 19445 try { 19446 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19447 packageNames, userId); 19448 } finally { 19449 Binder.restoreCallingIdentity(identity); 19450 } 19451 } 19452 } 19453 19454 private static void enforceSystemOrPhoneCaller(String tag) { 19455 int callingUid = Binder.getCallingUid(); 19456 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19457 throw new SecurityException( 19458 "Cannot call " + tag + " from UID " + callingUid); 19459 } 19460 } 19461 19462 boolean isHistoricalPackageUsageAvailable() { 19463 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19464 } 19465 19466 /** 19467 * Return a <b>copy</b> of the collection of packages known to the package manager. 19468 * @return A copy of the values of mPackages. 19469 */ 19470 Collection<PackageParser.Package> getPackages() { 19471 synchronized (mPackages) { 19472 return new ArrayList<>(mPackages.values()); 19473 } 19474 } 19475 19476 /** 19477 * Logs process start information (including base APK hash) to the security log. 19478 * @hide 19479 */ 19480 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19481 String apkFile, int pid) { 19482 if (!SecurityLog.isLoggingEnabled()) { 19483 return; 19484 } 19485 Bundle data = new Bundle(); 19486 data.putLong("startTimestamp", System.currentTimeMillis()); 19487 data.putString("processName", processName); 19488 data.putInt("uid", uid); 19489 data.putString("seinfo", seinfo); 19490 data.putString("apkFile", apkFile); 19491 data.putInt("pid", pid); 19492 Message msg = mProcessLoggingHandler.obtainMessage( 19493 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19494 msg.setData(data); 19495 mProcessLoggingHandler.sendMessage(msg); 19496 } 19497} 19498