PackageManagerService.java revision b23346639b66783c1662fd8ffa5345ef5cef336c
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 final @Nullable String mSetupWizardPackage; 1038 1039 private final PackageUsage mPackageUsage = new PackageUsage(); 1040 1041 private class PackageUsage { 1042 private static final int WRITE_INTERVAL 1043 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1044 1045 private final Object mFileLock = new Object(); 1046 private final AtomicLong mLastWritten = new AtomicLong(0); 1047 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1048 1049 private boolean mIsHistoricalPackageUsageAvailable = true; 1050 1051 boolean isHistoricalPackageUsageAvailable() { 1052 return mIsHistoricalPackageUsageAvailable; 1053 } 1054 1055 void write(boolean force) { 1056 if (force) { 1057 writeInternal(); 1058 return; 1059 } 1060 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1061 && !DEBUG_DEXOPT) { 1062 return; 1063 } 1064 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1065 new Thread("PackageUsage_DiskWriter") { 1066 @Override 1067 public void run() { 1068 try { 1069 writeInternal(); 1070 } finally { 1071 mBackgroundWriteRunning.set(false); 1072 } 1073 } 1074 }.start(); 1075 } 1076 } 1077 1078 private void writeInternal() { 1079 synchronized (mPackages) { 1080 synchronized (mFileLock) { 1081 AtomicFile file = getFile(); 1082 FileOutputStream f = null; 1083 try { 1084 f = file.startWrite(); 1085 BufferedOutputStream out = new BufferedOutputStream(f); 1086 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1087 StringBuilder sb = new StringBuilder(); 1088 for (PackageParser.Package pkg : mPackages.values()) { 1089 if (pkg.mLastPackageUsageTimeInMills == 0) { 1090 continue; 1091 } 1092 sb.setLength(0); 1093 sb.append(pkg.packageName); 1094 sb.append(' '); 1095 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1096 sb.append('\n'); 1097 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1098 } 1099 out.flush(); 1100 file.finishWrite(f); 1101 } catch (IOException e) { 1102 if (f != null) { 1103 file.failWrite(f); 1104 } 1105 Log.e(TAG, "Failed to write package usage times", e); 1106 } 1107 } 1108 } 1109 mLastWritten.set(SystemClock.elapsedRealtime()); 1110 } 1111 1112 void readLP() { 1113 synchronized (mFileLock) { 1114 AtomicFile file = getFile(); 1115 BufferedInputStream in = null; 1116 try { 1117 in = new BufferedInputStream(file.openRead()); 1118 StringBuffer sb = new StringBuffer(); 1119 while (true) { 1120 String packageName = readToken(in, sb, ' '); 1121 if (packageName == null) { 1122 break; 1123 } 1124 String timeInMillisString = readToken(in, sb, '\n'); 1125 if (timeInMillisString == null) { 1126 throw new IOException("Failed to find last usage time for package " 1127 + packageName); 1128 } 1129 PackageParser.Package pkg = mPackages.get(packageName); 1130 if (pkg == null) { 1131 continue; 1132 } 1133 long timeInMillis; 1134 try { 1135 timeInMillis = Long.parseLong(timeInMillisString); 1136 } catch (NumberFormatException e) { 1137 throw new IOException("Failed to parse " + timeInMillisString 1138 + " as a long.", e); 1139 } 1140 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1141 } 1142 } catch (FileNotFoundException expected) { 1143 mIsHistoricalPackageUsageAvailable = false; 1144 } catch (IOException e) { 1145 Log.w(TAG, "Failed to read package usage times", e); 1146 } finally { 1147 IoUtils.closeQuietly(in); 1148 } 1149 } 1150 mLastWritten.set(SystemClock.elapsedRealtime()); 1151 } 1152 1153 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1154 throws IOException { 1155 sb.setLength(0); 1156 while (true) { 1157 int ch = in.read(); 1158 if (ch == -1) { 1159 if (sb.length() == 0) { 1160 return null; 1161 } 1162 throw new IOException("Unexpected EOF"); 1163 } 1164 if (ch == endOfToken) { 1165 return sb.toString(); 1166 } 1167 sb.append((char)ch); 1168 } 1169 } 1170 1171 private AtomicFile getFile() { 1172 File dataDir = Environment.getDataDirectory(); 1173 File systemDir = new File(dataDir, "system"); 1174 File fname = new File(systemDir, "package-usage.list"); 1175 return new AtomicFile(fname); 1176 } 1177 } 1178 1179 class PackageHandler extends Handler { 1180 private boolean mBound = false; 1181 final ArrayList<HandlerParams> mPendingInstalls = 1182 new ArrayList<HandlerParams>(); 1183 1184 private boolean connectToService() { 1185 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1186 " DefaultContainerService"); 1187 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1188 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1189 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1190 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1192 mBound = true; 1193 return true; 1194 } 1195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1196 return false; 1197 } 1198 1199 private void disconnectService() { 1200 mContainerService = null; 1201 mBound = false; 1202 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1203 mContext.unbindService(mDefContainerConn); 1204 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1205 } 1206 1207 PackageHandler(Looper looper) { 1208 super(looper); 1209 } 1210 1211 public void handleMessage(Message msg) { 1212 try { 1213 doHandleMessage(msg); 1214 } finally { 1215 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1216 } 1217 } 1218 1219 void doHandleMessage(Message msg) { 1220 switch (msg.what) { 1221 case INIT_COPY: { 1222 HandlerParams params = (HandlerParams) msg.obj; 1223 int idx = mPendingInstalls.size(); 1224 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1225 // If a bind was already initiated we dont really 1226 // need to do anything. The pending install 1227 // will be processed later on. 1228 if (!mBound) { 1229 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1230 System.identityHashCode(mHandler)); 1231 // If this is the only one pending we might 1232 // have to bind to the service again. 1233 if (!connectToService()) { 1234 Slog.e(TAG, "Failed to bind to media container service"); 1235 params.serviceError(); 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1237 System.identityHashCode(mHandler)); 1238 if (params.traceMethod != null) { 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1240 params.traceCookie); 1241 } 1242 return; 1243 } else { 1244 // Once we bind to the service, the first 1245 // pending request will be processed. 1246 mPendingInstalls.add(idx, params); 1247 } 1248 } else { 1249 mPendingInstalls.add(idx, params); 1250 // Already bound to the service. Just make 1251 // sure we trigger off processing the first request. 1252 if (idx == 0) { 1253 mHandler.sendEmptyMessage(MCS_BOUND); 1254 } 1255 } 1256 break; 1257 } 1258 case MCS_BOUND: { 1259 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1260 if (msg.obj != null) { 1261 mContainerService = (IMediaContainerService) msg.obj; 1262 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1263 System.identityHashCode(mHandler)); 1264 } 1265 if (mContainerService == null) { 1266 if (!mBound) { 1267 // Something seriously wrong since we are not bound and we are not 1268 // waiting for connection. Bail out. 1269 Slog.e(TAG, "Cannot bind to media container service"); 1270 for (HandlerParams params : mPendingInstalls) { 1271 // Indicate service bind error 1272 params.serviceError(); 1273 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1274 System.identityHashCode(params)); 1275 if (params.traceMethod != null) { 1276 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1277 params.traceMethod, params.traceCookie); 1278 } 1279 return; 1280 } 1281 mPendingInstalls.clear(); 1282 } else { 1283 Slog.w(TAG, "Waiting to connect to media container service"); 1284 } 1285 } else if (mPendingInstalls.size() > 0) { 1286 HandlerParams params = mPendingInstalls.get(0); 1287 if (params != null) { 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1291 if (params.startCopy()) { 1292 // We are done... look for more work or to 1293 // go idle. 1294 if (DEBUG_SD_INSTALL) Log.i(TAG, 1295 "Checking for more work or unbind..."); 1296 // Delete pending install 1297 if (mPendingInstalls.size() > 0) { 1298 mPendingInstalls.remove(0); 1299 } 1300 if (mPendingInstalls.size() == 0) { 1301 if (mBound) { 1302 if (DEBUG_SD_INSTALL) Log.i(TAG, 1303 "Posting delayed MCS_UNBIND"); 1304 removeMessages(MCS_UNBIND); 1305 Message ubmsg = obtainMessage(MCS_UNBIND); 1306 // Unbind after a little delay, to avoid 1307 // continual thrashing. 1308 sendMessageDelayed(ubmsg, 10000); 1309 } 1310 } else { 1311 // There are more pending requests in queue. 1312 // Just post MCS_BOUND message to trigger processing 1313 // of next pending install. 1314 if (DEBUG_SD_INSTALL) Log.i(TAG, 1315 "Posting MCS_BOUND for next work"); 1316 mHandler.sendEmptyMessage(MCS_BOUND); 1317 } 1318 } 1319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1320 } 1321 } else { 1322 // Should never happen ideally. 1323 Slog.w(TAG, "Empty queue"); 1324 } 1325 break; 1326 } 1327 case MCS_RECONNECT: { 1328 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1329 if (mPendingInstalls.size() > 0) { 1330 if (mBound) { 1331 disconnectService(); 1332 } 1333 if (!connectToService()) { 1334 Slog.e(TAG, "Failed to bind to media container service"); 1335 for (HandlerParams params : mPendingInstalls) { 1336 // Indicate service bind error 1337 params.serviceError(); 1338 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1339 System.identityHashCode(params)); 1340 } 1341 mPendingInstalls.clear(); 1342 } 1343 } 1344 break; 1345 } 1346 case MCS_UNBIND: { 1347 // If there is no actual work left, then time to unbind. 1348 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1349 1350 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1351 if (mBound) { 1352 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1353 1354 disconnectService(); 1355 } 1356 } else if (mPendingInstalls.size() > 0) { 1357 // There are more pending requests in queue. 1358 // Just post MCS_BOUND message to trigger processing 1359 // of next pending install. 1360 mHandler.sendEmptyMessage(MCS_BOUND); 1361 } 1362 1363 break; 1364 } 1365 case MCS_GIVE_UP: { 1366 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1367 HandlerParams params = mPendingInstalls.remove(0); 1368 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1369 System.identityHashCode(params)); 1370 break; 1371 } 1372 case SEND_PENDING_BROADCAST: { 1373 String packages[]; 1374 ArrayList<String> components[]; 1375 int size = 0; 1376 int uids[]; 1377 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1378 synchronized (mPackages) { 1379 if (mPendingBroadcasts == null) { 1380 return; 1381 } 1382 size = mPendingBroadcasts.size(); 1383 if (size <= 0) { 1384 // Nothing to be done. Just return 1385 return; 1386 } 1387 packages = new String[size]; 1388 components = new ArrayList[size]; 1389 uids = new int[size]; 1390 int i = 0; // filling out the above arrays 1391 1392 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1393 int packageUserId = mPendingBroadcasts.userIdAt(n); 1394 Iterator<Map.Entry<String, ArrayList<String>>> it 1395 = mPendingBroadcasts.packagesForUserId(packageUserId) 1396 .entrySet().iterator(); 1397 while (it.hasNext() && i < size) { 1398 Map.Entry<String, ArrayList<String>> ent = it.next(); 1399 packages[i] = ent.getKey(); 1400 components[i] = ent.getValue(); 1401 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1402 uids[i] = (ps != null) 1403 ? UserHandle.getUid(packageUserId, ps.appId) 1404 : -1; 1405 i++; 1406 } 1407 } 1408 size = i; 1409 mPendingBroadcasts.clear(); 1410 } 1411 // Send broadcasts 1412 for (int i = 0; i < size; i++) { 1413 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1414 } 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 break; 1417 } 1418 case START_CLEANING_PACKAGE: { 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1420 final String packageName = (String)msg.obj; 1421 final int userId = msg.arg1; 1422 final boolean andCode = msg.arg2 != 0; 1423 synchronized (mPackages) { 1424 if (userId == UserHandle.USER_ALL) { 1425 int[] users = sUserManager.getUserIds(); 1426 for (int user : users) { 1427 mSettings.addPackageToCleanLPw( 1428 new PackageCleanItem(user, packageName, andCode)); 1429 } 1430 } else { 1431 mSettings.addPackageToCleanLPw( 1432 new PackageCleanItem(userId, packageName, andCode)); 1433 } 1434 } 1435 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1436 startCleaningPackages(); 1437 } break; 1438 case POST_INSTALL: { 1439 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1440 1441 PostInstallData data = mRunningInstalls.get(msg.arg1); 1442 mRunningInstalls.delete(msg.arg1); 1443 1444 if (data != null) { 1445 InstallArgs args = data.args; 1446 PackageInstalledInfo parentRes = data.res; 1447 1448 final boolean grantPermissions = (args.installFlags 1449 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1450 final boolean killApp = (args.installFlags 1451 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1452 final String[] grantedPermissions = args.installGrantPermissions; 1453 1454 // Handle the parent package 1455 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1456 grantedPermissions, args.observer); 1457 1458 // Handle the child packages 1459 final int childCount = (parentRes.addedChildPackages != null) 1460 ? parentRes.addedChildPackages.size() : 0; 1461 for (int i = 0; i < childCount; i++) { 1462 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1463 handlePackagePostInstall(childRes, grantPermissions, killApp, 1464 grantedPermissions, args.observer); 1465 } 1466 1467 // Log tracing if needed 1468 if (args.traceMethod != null) { 1469 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1470 args.traceCookie); 1471 } 1472 } else { 1473 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1474 } 1475 1476 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1477 } break; 1478 case UPDATED_MEDIA_STATUS: { 1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1480 boolean reportStatus = msg.arg1 == 1; 1481 boolean doGc = msg.arg2 == 1; 1482 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1483 if (doGc) { 1484 // Force a gc to clear up stale containers. 1485 Runtime.getRuntime().gc(); 1486 } 1487 if (msg.obj != null) { 1488 @SuppressWarnings("unchecked") 1489 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1490 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1491 // Unload containers 1492 unloadAllContainers(args); 1493 } 1494 if (reportStatus) { 1495 try { 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1497 PackageHelper.getMountService().finishMediaUpdate(); 1498 } catch (RemoteException e) { 1499 Log.e(TAG, "MountService not running?"); 1500 } 1501 } 1502 } break; 1503 case WRITE_SETTINGS: { 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1505 synchronized (mPackages) { 1506 removeMessages(WRITE_SETTINGS); 1507 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1508 mSettings.writeLPr(); 1509 mDirtyUsers.clear(); 1510 } 1511 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1512 } break; 1513 case WRITE_PACKAGE_RESTRICTIONS: { 1514 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1515 synchronized (mPackages) { 1516 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1517 for (int userId : mDirtyUsers) { 1518 mSettings.writePackageRestrictionsLPr(userId); 1519 } 1520 mDirtyUsers.clear(); 1521 } 1522 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1523 } break; 1524 case CHECK_PENDING_VERIFICATION: { 1525 final int verificationId = msg.arg1; 1526 final PackageVerificationState state = mPendingVerification.get(verificationId); 1527 1528 if ((state != null) && !state.timeoutExtended()) { 1529 final InstallArgs args = state.getInstallArgs(); 1530 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1531 1532 Slog.i(TAG, "Verification timed out for " + originUri); 1533 mPendingVerification.remove(verificationId); 1534 1535 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1536 1537 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1538 Slog.i(TAG, "Continuing with installation of " + originUri); 1539 state.setVerifierResponse(Binder.getCallingUid(), 1540 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1541 broadcastPackageVerified(verificationId, originUri, 1542 PackageManager.VERIFICATION_ALLOW, 1543 state.getInstallArgs().getUser()); 1544 try { 1545 ret = args.copyApk(mContainerService, true); 1546 } catch (RemoteException e) { 1547 Slog.e(TAG, "Could not contact the ContainerService"); 1548 } 1549 } else { 1550 broadcastPackageVerified(verificationId, originUri, 1551 PackageManager.VERIFICATION_REJECT, 1552 state.getInstallArgs().getUser()); 1553 } 1554 1555 Trace.asyncTraceEnd( 1556 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1557 1558 processPendingInstall(args, ret); 1559 mHandler.sendEmptyMessage(MCS_UNBIND); 1560 } 1561 break; 1562 } 1563 case PACKAGE_VERIFIED: { 1564 final int verificationId = msg.arg1; 1565 1566 final PackageVerificationState state = mPendingVerification.get(verificationId); 1567 if (state == null) { 1568 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1569 break; 1570 } 1571 1572 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1573 1574 state.setVerifierResponse(response.callerUid, response.code); 1575 1576 if (state.isVerificationComplete()) { 1577 mPendingVerification.remove(verificationId); 1578 1579 final InstallArgs args = state.getInstallArgs(); 1580 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1581 1582 int ret; 1583 if (state.isInstallAllowed()) { 1584 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1585 broadcastPackageVerified(verificationId, originUri, 1586 response.code, state.getInstallArgs().getUser()); 1587 try { 1588 ret = args.copyApk(mContainerService, true); 1589 } catch (RemoteException e) { 1590 Slog.e(TAG, "Could not contact the ContainerService"); 1591 } 1592 } else { 1593 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1594 } 1595 1596 Trace.asyncTraceEnd( 1597 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1598 1599 processPendingInstall(args, ret); 1600 mHandler.sendEmptyMessage(MCS_UNBIND); 1601 } 1602 1603 break; 1604 } 1605 case START_INTENT_FILTER_VERIFICATIONS: { 1606 IFVerificationParams params = (IFVerificationParams) msg.obj; 1607 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1608 params.replacing, params.pkg); 1609 break; 1610 } 1611 case INTENT_FILTER_VERIFIED: { 1612 final int verificationId = msg.arg1; 1613 1614 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1615 verificationId); 1616 if (state == null) { 1617 Slog.w(TAG, "Invalid IntentFilter verification token " 1618 + verificationId + " received"); 1619 break; 1620 } 1621 1622 final int userId = state.getUserId(); 1623 1624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1625 "Processing IntentFilter verification with token:" 1626 + verificationId + " and userId:" + userId); 1627 1628 final IntentFilterVerificationResponse response = 1629 (IntentFilterVerificationResponse) msg.obj; 1630 1631 state.setVerifierResponse(response.callerUid, response.code); 1632 1633 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1634 "IntentFilter verification with token:" + verificationId 1635 + " and userId:" + userId 1636 + " is settings verifier response with response code:" 1637 + response.code); 1638 1639 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1641 + response.getFailedDomainsString()); 1642 } 1643 1644 if (state.isVerificationComplete()) { 1645 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1646 } else { 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "IntentFilter verification with token:" + verificationId 1649 + " was not said to be complete"); 1650 } 1651 1652 break; 1653 } 1654 } 1655 } 1656 } 1657 1658 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1659 boolean killApp, String[] grantedPermissions, 1660 IPackageInstallObserver2 installObserver) { 1661 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1662 // Send the removed broadcasts 1663 if (res.removedInfo != null) { 1664 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1665 } 1666 1667 // Now that we successfully installed the package, grant runtime 1668 // permissions if requested before broadcasting the install. 1669 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1670 >= Build.VERSION_CODES.M) { 1671 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1672 } 1673 1674 final boolean update = res.removedInfo != null 1675 && res.removedInfo.removedPackage != null; 1676 1677 // If this is the first time we have child packages for a disabled privileged 1678 // app that had no children, we grant requested runtime permissions to the new 1679 // children if the parent on the system image had them already granted. 1680 if (res.pkg.parentPackage != null) { 1681 synchronized (mPackages) { 1682 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1683 } 1684 } 1685 1686 synchronized (mPackages) { 1687 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1688 } 1689 1690 final String packageName = res.pkg.applicationInfo.packageName; 1691 Bundle extras = new Bundle(1); 1692 extras.putInt(Intent.EXTRA_UID, res.uid); 1693 1694 // Determine the set of users who are adding this package for 1695 // the first time vs. those who are seeing an update. 1696 int[] firstUsers = EMPTY_INT_ARRAY; 1697 int[] updateUsers = EMPTY_INT_ARRAY; 1698 if (res.origUsers == null || res.origUsers.length == 0) { 1699 firstUsers = res.newUsers; 1700 } else { 1701 for (int newUser : res.newUsers) { 1702 boolean isNew = true; 1703 for (int origUser : res.origUsers) { 1704 if (origUser == newUser) { 1705 isNew = false; 1706 break; 1707 } 1708 } 1709 if (isNew) { 1710 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1711 } else { 1712 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1713 } 1714 } 1715 } 1716 1717 // Send installed broadcasts if the install/update is not ephemeral 1718 if (!isEphemeral(res.pkg)) { 1719 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1720 1721 // Send added for users that see the package for the first time 1722 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1723 extras, 0 /*flags*/, null /*targetPackage*/, 1724 null /*finishedReceiver*/, firstUsers); 1725 1726 // Send added for users that don't see the package for the first time 1727 if (update) { 1728 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1729 } 1730 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1731 extras, 0 /*flags*/, null /*targetPackage*/, 1732 null /*finishedReceiver*/, updateUsers); 1733 1734 // Send replaced for users that don't see the package for the first time 1735 if (update) { 1736 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1737 packageName, extras, 0 /*flags*/, 1738 null /*targetPackage*/, null /*finishedReceiver*/, 1739 updateUsers); 1740 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1741 null /*package*/, null /*extras*/, 0 /*flags*/, 1742 packageName /*targetPackage*/, 1743 null /*finishedReceiver*/, updateUsers); 1744 } 1745 1746 // Send broadcast package appeared if forward locked/external for all users 1747 // treat asec-hosted packages like removable media on upgrade 1748 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1749 if (DEBUG_INSTALL) { 1750 Slog.i(TAG, "upgrading pkg " + res.pkg 1751 + " is ASEC-hosted -> AVAILABLE"); 1752 } 1753 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1754 ArrayList<String> pkgList = new ArrayList<>(1); 1755 pkgList.add(packageName); 1756 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1757 } 1758 } 1759 1760 // Work that needs to happen on first install within each user 1761 if (firstUsers != null && firstUsers.length > 0) { 1762 synchronized (mPackages) { 1763 for (int userId : firstUsers) { 1764 // If this app is a browser and it's newly-installed for some 1765 // users, clear any default-browser state in those users. The 1766 // app's nature doesn't depend on the user, so we can just check 1767 // its browser nature in any user and generalize. 1768 if (packageIsBrowser(packageName, userId)) { 1769 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1770 } 1771 1772 // We may also need to apply pending (restored) runtime 1773 // permission grants within these users. 1774 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1775 } 1776 } 1777 } 1778 1779 // Log current value of "unknown sources" setting 1780 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1781 getUnknownSourcesSettings()); 1782 1783 // Force a gc to clear up things 1784 Runtime.getRuntime().gc(); 1785 1786 // Remove the replaced package's older resources safely now 1787 // We delete after a gc for applications on sdcard. 1788 if (res.removedInfo != null && res.removedInfo.args != null) { 1789 synchronized (mInstallLock) { 1790 res.removedInfo.args.doPostDeleteLI(true); 1791 } 1792 } 1793 } 1794 1795 // If someone is watching installs - notify them 1796 if (installObserver != null) { 1797 try { 1798 Bundle extras = extrasForInstallResult(res); 1799 installObserver.onPackageInstalled(res.name, res.returnCode, 1800 res.returnMsg, extras); 1801 } catch (RemoteException e) { 1802 Slog.i(TAG, "Observer no longer exists."); 1803 } 1804 } 1805 } 1806 1807 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1808 PackageParser.Package pkg) { 1809 if (pkg.parentPackage == null) { 1810 return; 1811 } 1812 if (pkg.requestedPermissions == null) { 1813 return; 1814 } 1815 final PackageSetting disabledSysParentPs = mSettings 1816 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1817 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1818 || !disabledSysParentPs.isPrivileged() 1819 || (disabledSysParentPs.childPackageNames != null 1820 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1821 return; 1822 } 1823 final int[] allUserIds = sUserManager.getUserIds(); 1824 final int permCount = pkg.requestedPermissions.size(); 1825 for (int i = 0; i < permCount; i++) { 1826 String permission = pkg.requestedPermissions.get(i); 1827 BasePermission bp = mSettings.mPermissions.get(permission); 1828 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1829 continue; 1830 } 1831 for (int userId : allUserIds) { 1832 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1833 permission, userId)) { 1834 grantRuntimePermission(pkg.packageName, permission, userId); 1835 } 1836 } 1837 } 1838 } 1839 1840 private StorageEventListener mStorageListener = new StorageEventListener() { 1841 @Override 1842 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1843 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1844 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1845 final String volumeUuid = vol.getFsUuid(); 1846 1847 // Clean up any users or apps that were removed or recreated 1848 // while this volume was missing 1849 reconcileUsers(volumeUuid); 1850 reconcileApps(volumeUuid); 1851 1852 // Clean up any install sessions that expired or were 1853 // cancelled while this volume was missing 1854 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1855 1856 loadPrivatePackages(vol); 1857 1858 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1859 unloadPrivatePackages(vol); 1860 } 1861 } 1862 1863 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1864 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1865 updateExternalMediaStatus(true, false); 1866 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1867 updateExternalMediaStatus(false, false); 1868 } 1869 } 1870 } 1871 1872 @Override 1873 public void onVolumeForgotten(String fsUuid) { 1874 if (TextUtils.isEmpty(fsUuid)) { 1875 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1876 return; 1877 } 1878 1879 // Remove any apps installed on the forgotten volume 1880 synchronized (mPackages) { 1881 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1882 for (PackageSetting ps : packages) { 1883 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1884 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1885 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1886 } 1887 1888 mSettings.onVolumeForgotten(fsUuid); 1889 mSettings.writeLPr(); 1890 } 1891 } 1892 }; 1893 1894 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1895 String[] grantedPermissions) { 1896 for (int userId : userIds) { 1897 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1898 } 1899 1900 // We could have touched GID membership, so flush out packages.list 1901 synchronized (mPackages) { 1902 mSettings.writePackageListLPr(); 1903 } 1904 } 1905 1906 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1907 String[] grantedPermissions) { 1908 SettingBase sb = (SettingBase) pkg.mExtras; 1909 if (sb == null) { 1910 return; 1911 } 1912 1913 PermissionsState permissionsState = sb.getPermissionsState(); 1914 1915 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1916 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1917 1918 synchronized (mPackages) { 1919 for (String permission : pkg.requestedPermissions) { 1920 BasePermission bp = mSettings.mPermissions.get(permission); 1921 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1922 && (grantedPermissions == null 1923 || ArrayUtils.contains(grantedPermissions, permission))) { 1924 final int flags = permissionsState.getPermissionFlags(permission, userId); 1925 // Installer cannot change immutable permissions. 1926 if ((flags & immutableFlags) == 0) { 1927 grantRuntimePermission(pkg.packageName, permission, userId); 1928 } 1929 } 1930 } 1931 } 1932 } 1933 1934 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1935 Bundle extras = null; 1936 switch (res.returnCode) { 1937 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1938 extras = new Bundle(); 1939 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1940 res.origPermission); 1941 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1942 res.origPackage); 1943 break; 1944 } 1945 case PackageManager.INSTALL_SUCCEEDED: { 1946 extras = new Bundle(); 1947 extras.putBoolean(Intent.EXTRA_REPLACING, 1948 res.removedInfo != null && res.removedInfo.removedPackage != null); 1949 break; 1950 } 1951 } 1952 return extras; 1953 } 1954 1955 void scheduleWriteSettingsLocked() { 1956 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1957 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1958 } 1959 } 1960 1961 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1962 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1963 scheduleWritePackageRestrictionsLocked(userId); 1964 } 1965 1966 void scheduleWritePackageRestrictionsLocked(int userId) { 1967 final int[] userIds = (userId == UserHandle.USER_ALL) 1968 ? sUserManager.getUserIds() : new int[]{userId}; 1969 for (int nextUserId : userIds) { 1970 if (!sUserManager.exists(nextUserId)) return; 1971 mDirtyUsers.add(nextUserId); 1972 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1973 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1974 } 1975 } 1976 } 1977 1978 public static PackageManagerService main(Context context, Installer installer, 1979 boolean factoryTest, boolean onlyCore) { 1980 // Self-check for initial settings. 1981 PackageManagerServiceCompilerMapping.checkProperties(); 1982 1983 PackageManagerService m = new PackageManagerService(context, installer, 1984 factoryTest, onlyCore); 1985 m.enableSystemUserPackages(); 1986 ServiceManager.addService("package", m); 1987 return m; 1988 } 1989 1990 private void enableSystemUserPackages() { 1991 if (!UserManager.isSplitSystemUser()) { 1992 return; 1993 } 1994 // For system user, enable apps based on the following conditions: 1995 // - app is whitelisted or belong to one of these groups: 1996 // -- system app which has no launcher icons 1997 // -- system app which has INTERACT_ACROSS_USERS permission 1998 // -- system IME app 1999 // - app is not in the blacklist 2000 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2001 Set<String> enableApps = new ArraySet<>(); 2002 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2003 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2004 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2005 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2006 enableApps.addAll(wlApps); 2007 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2008 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2009 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2010 enableApps.removeAll(blApps); 2011 Log.i(TAG, "Applications installed for system user: " + enableApps); 2012 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2013 UserHandle.SYSTEM); 2014 final int allAppsSize = allAps.size(); 2015 synchronized (mPackages) { 2016 for (int i = 0; i < allAppsSize; i++) { 2017 String pName = allAps.get(i); 2018 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2019 // Should not happen, but we shouldn't be failing if it does 2020 if (pkgSetting == null) { 2021 continue; 2022 } 2023 boolean install = enableApps.contains(pName); 2024 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2025 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2026 + " for system user"); 2027 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2028 } 2029 } 2030 } 2031 } 2032 2033 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2034 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2035 Context.DISPLAY_SERVICE); 2036 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2037 } 2038 2039 public PackageManagerService(Context context, Installer installer, 2040 boolean factoryTest, boolean onlyCore) { 2041 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2042 SystemClock.uptimeMillis()); 2043 2044 if (mSdkVersion <= 0) { 2045 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2046 } 2047 2048 mContext = context; 2049 mFactoryTest = factoryTest; 2050 mOnlyCore = onlyCore; 2051 mMetrics = new DisplayMetrics(); 2052 mSettings = new Settings(mPackages); 2053 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2054 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2055 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2056 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2057 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2058 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2059 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2060 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2061 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2062 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2063 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2064 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2065 2066 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2067 if (separateProcesses != null && separateProcesses.length() > 0) { 2068 if ("*".equals(separateProcesses)) { 2069 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2070 mSeparateProcesses = null; 2071 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2072 } else { 2073 mDefParseFlags = 0; 2074 mSeparateProcesses = separateProcesses.split(","); 2075 Slog.w(TAG, "Running with debug.separate_processes: " 2076 + separateProcesses); 2077 } 2078 } else { 2079 mDefParseFlags = 0; 2080 mSeparateProcesses = null; 2081 } 2082 2083 mInstaller = installer; 2084 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2085 "*dexopt*"); 2086 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2087 2088 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2089 FgThread.get().getLooper()); 2090 2091 getDefaultDisplayMetrics(context, mMetrics); 2092 2093 SystemConfig systemConfig = SystemConfig.getInstance(); 2094 mGlobalGids = systemConfig.getGlobalGids(); 2095 mSystemPermissions = systemConfig.getSystemPermissions(); 2096 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2097 2098 synchronized (mInstallLock) { 2099 // writer 2100 synchronized (mPackages) { 2101 mHandlerThread = new ServiceThread(TAG, 2102 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2103 mHandlerThread.start(); 2104 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2105 mProcessLoggingHandler = new ProcessLoggingHandler(); 2106 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2107 2108 File dataDir = Environment.getDataDirectory(); 2109 mAppInstallDir = new File(dataDir, "app"); 2110 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2111 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2112 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2113 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2114 2115 sUserManager = new UserManagerService(context, this, mPackages); 2116 2117 // Propagate permission configuration in to package manager. 2118 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2119 = systemConfig.getPermissions(); 2120 for (int i=0; i<permConfig.size(); i++) { 2121 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2122 BasePermission bp = mSettings.mPermissions.get(perm.name); 2123 if (bp == null) { 2124 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2125 mSettings.mPermissions.put(perm.name, bp); 2126 } 2127 if (perm.gids != null) { 2128 bp.setGids(perm.gids, perm.perUser); 2129 } 2130 } 2131 2132 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2133 for (int i=0; i<libConfig.size(); i++) { 2134 mSharedLibraries.put(libConfig.keyAt(i), 2135 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2136 } 2137 2138 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2139 2140 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2141 2142 String customResolverActivity = Resources.getSystem().getString( 2143 R.string.config_customResolverActivity); 2144 if (TextUtils.isEmpty(customResolverActivity)) { 2145 customResolverActivity = null; 2146 } else { 2147 mCustomResolverComponentName = ComponentName.unflattenFromString( 2148 customResolverActivity); 2149 } 2150 2151 long startTime = SystemClock.uptimeMillis(); 2152 2153 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2154 startTime); 2155 2156 // Set flag to monitor and not change apk file paths when 2157 // scanning install directories. 2158 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2159 2160 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2161 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2162 2163 if (bootClassPath == null) { 2164 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2165 } 2166 2167 if (systemServerClassPath == null) { 2168 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2169 } 2170 2171 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2172 final String[] dexCodeInstructionSets = 2173 getDexCodeInstructionSets( 2174 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2175 2176 /** 2177 * Ensure all external libraries have had dexopt run on them. 2178 */ 2179 if (mSharedLibraries.size() > 0) { 2180 // NOTE: For now, we're compiling these system "shared libraries" 2181 // (and framework jars) into all available architectures. It's possible 2182 // to compile them only when we come across an app that uses them (there's 2183 // already logic for that in scanPackageLI) but that adds some complexity. 2184 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2185 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2186 final String lib = libEntry.path; 2187 if (lib == null) { 2188 continue; 2189 } 2190 2191 try { 2192 // Shared libraries do not have profiles so we perform a full 2193 // AOT compilation (if needed). 2194 int dexoptNeeded = DexFile.getDexOptNeeded( 2195 lib, dexCodeInstructionSet, 2196 getCompilerFilterForReason(REASON_SHARED_APK), 2197 false /* newProfile */); 2198 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2199 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2200 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2201 getCompilerFilterForReason(REASON_SHARED_APK), 2202 StorageManager.UUID_PRIVATE_INTERNAL); 2203 } 2204 } catch (FileNotFoundException e) { 2205 Slog.w(TAG, "Library not found: " + lib); 2206 } catch (IOException | InstallerException e) { 2207 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2208 + e.getMessage()); 2209 } 2210 } 2211 } 2212 } 2213 2214 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2215 2216 final VersionInfo ver = mSettings.getInternalVersion(); 2217 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2218 2219 // when upgrading from pre-M, promote system app permissions from install to runtime 2220 mPromoteSystemApps = 2221 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2222 2223 // save off the names of pre-existing system packages prior to scanning; we don't 2224 // want to automatically grant runtime permissions for new system apps 2225 if (mPromoteSystemApps) { 2226 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2227 while (pkgSettingIter.hasNext()) { 2228 PackageSetting ps = pkgSettingIter.next(); 2229 if (isSystemApp(ps)) { 2230 mExistingSystemPackages.add(ps.name); 2231 } 2232 } 2233 } 2234 2235 // When upgrading from pre-N, we need to handle package extraction like first boot, 2236 // as there is no profiling data available. 2237 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2238 mSettings.setNWorkDone(); 2239 2240 // Collect vendor overlay packages. 2241 // (Do this before scanning any apps.) 2242 // For security and version matching reason, only consider 2243 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2244 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2245 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2246 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2247 2248 // Find base frameworks (resource packages without code). 2249 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2250 | PackageParser.PARSE_IS_SYSTEM_DIR 2251 | PackageParser.PARSE_IS_PRIVILEGED, 2252 scanFlags | SCAN_NO_DEX, 0); 2253 2254 // Collected privileged system packages. 2255 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2256 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2257 | PackageParser.PARSE_IS_SYSTEM_DIR 2258 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2259 2260 // Collect ordinary system packages. 2261 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2262 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2263 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2264 2265 // Collect all vendor packages. 2266 File vendorAppDir = new File("/vendor/app"); 2267 try { 2268 vendorAppDir = vendorAppDir.getCanonicalFile(); 2269 } catch (IOException e) { 2270 // failed to look up canonical path, continue with original one 2271 } 2272 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2273 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2274 2275 // Collect all OEM packages. 2276 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2277 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2278 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2279 2280 // Prune any system packages that no longer exist. 2281 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2282 if (!mOnlyCore) { 2283 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2284 while (psit.hasNext()) { 2285 PackageSetting ps = psit.next(); 2286 2287 /* 2288 * If this is not a system app, it can't be a 2289 * disable system app. 2290 */ 2291 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2292 continue; 2293 } 2294 2295 /* 2296 * If the package is scanned, it's not erased. 2297 */ 2298 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2299 if (scannedPkg != null) { 2300 /* 2301 * If the system app is both scanned and in the 2302 * disabled packages list, then it must have been 2303 * added via OTA. Remove it from the currently 2304 * scanned package so the previously user-installed 2305 * application can be scanned. 2306 */ 2307 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2308 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2309 + ps.name + "; removing system app. Last known codePath=" 2310 + ps.codePathString + ", installStatus=" + ps.installStatus 2311 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2312 + scannedPkg.mVersionCode); 2313 removePackageLI(scannedPkg, true); 2314 mExpectingBetter.put(ps.name, ps.codePath); 2315 } 2316 2317 continue; 2318 } 2319 2320 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2321 psit.remove(); 2322 logCriticalInfo(Log.WARN, "System package " + ps.name 2323 + " no longer exists; wiping its data"); 2324 removeDataDirsLI(null, ps.name); 2325 } else { 2326 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2327 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2328 possiblyDeletedUpdatedSystemApps.add(ps.name); 2329 } 2330 } 2331 } 2332 } 2333 2334 //look for any incomplete package installations 2335 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2336 //clean up list 2337 for(int i = 0; i < deletePkgsList.size(); i++) { 2338 //clean up here 2339 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2340 } 2341 //delete tmp files 2342 deleteTempPackageFiles(); 2343 2344 // Remove any shared userIDs that have no associated packages 2345 mSettings.pruneSharedUsersLPw(); 2346 2347 if (!mOnlyCore) { 2348 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2349 SystemClock.uptimeMillis()); 2350 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2351 2352 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2353 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2354 2355 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2356 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2357 2358 /** 2359 * Remove disable package settings for any updated system 2360 * apps that were removed via an OTA. If they're not a 2361 * previously-updated app, remove them completely. 2362 * Otherwise, just revoke their system-level permissions. 2363 */ 2364 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2365 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2366 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2367 2368 String msg; 2369 if (deletedPkg == null) { 2370 msg = "Updated system package " + deletedAppName 2371 + " no longer exists; wiping its data"; 2372 removeDataDirsLI(null, deletedAppName); 2373 } else { 2374 msg = "Updated system app + " + deletedAppName 2375 + " no longer present; removing system privileges for " 2376 + deletedAppName; 2377 2378 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2379 2380 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2381 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2382 } 2383 logCriticalInfo(Log.WARN, msg); 2384 } 2385 2386 /** 2387 * Make sure all system apps that we expected to appear on 2388 * the userdata partition actually showed up. If they never 2389 * appeared, crawl back and revive the system version. 2390 */ 2391 for (int i = 0; i < mExpectingBetter.size(); i++) { 2392 final String packageName = mExpectingBetter.keyAt(i); 2393 if (!mPackages.containsKey(packageName)) { 2394 final File scanFile = mExpectingBetter.valueAt(i); 2395 2396 logCriticalInfo(Log.WARN, "Expected better " + packageName 2397 + " but never showed up; reverting to system"); 2398 2399 final int reparseFlags; 2400 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2401 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR 2403 | PackageParser.PARSE_IS_PRIVILEGED; 2404 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2405 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR; 2407 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2408 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2409 | PackageParser.PARSE_IS_SYSTEM_DIR; 2410 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2411 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR; 2413 } else { 2414 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2415 continue; 2416 } 2417 2418 mSettings.enableSystemPackageLPw(packageName); 2419 2420 try { 2421 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2422 } catch (PackageManagerException e) { 2423 Slog.e(TAG, "Failed to parse original system package: " 2424 + e.getMessage()); 2425 } 2426 } 2427 } 2428 } 2429 mExpectingBetter.clear(); 2430 2431 // Now that we know all of the shared libraries, update all clients to have 2432 // the correct library paths. 2433 updateAllSharedLibrariesLPw(); 2434 2435 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2436 // NOTE: We ignore potential failures here during a system scan (like 2437 // the rest of the commands above) because there's precious little we 2438 // can do about it. A settings error is reported, though. 2439 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2440 false /* boot complete */); 2441 } 2442 2443 // Now that we know all the packages we are keeping, 2444 // read and update their last usage times. 2445 mPackageUsage.readLP(); 2446 2447 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2448 SystemClock.uptimeMillis()); 2449 Slog.i(TAG, "Time to scan packages: " 2450 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2451 + " seconds"); 2452 2453 // If the platform SDK has changed since the last time we booted, 2454 // we need to re-grant app permission to catch any new ones that 2455 // appear. This is really a hack, and means that apps can in some 2456 // cases get permissions that the user didn't initially explicitly 2457 // allow... it would be nice to have some better way to handle 2458 // this situation. 2459 int updateFlags = UPDATE_PERMISSIONS_ALL; 2460 if (ver.sdkVersion != mSdkVersion) { 2461 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2462 + mSdkVersion + "; regranting permissions for internal storage"); 2463 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2464 } 2465 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2466 ver.sdkVersion = mSdkVersion; 2467 2468 // If this is the first boot or an update from pre-M, and it is a normal 2469 // boot, then we need to initialize the default preferred apps across 2470 // all defined users. 2471 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2472 for (UserInfo user : sUserManager.getUsers(true)) { 2473 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2474 applyFactoryDefaultBrowserLPw(user.id); 2475 primeDomainVerificationsLPw(user.id); 2476 } 2477 } 2478 2479 // Prepare storage for system user really early during boot, 2480 // since core system apps like SettingsProvider and SystemUI 2481 // can't wait for user to start 2482 final int storageFlags; 2483 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2484 storageFlags = StorageManager.FLAG_STORAGE_DE; 2485 } else { 2486 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2487 } 2488 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2489 storageFlags); 2490 2491 // If this is first boot after an OTA, and a normal boot, then 2492 // we need to clear code cache directories. 2493 if (mIsUpgrade && !onlyCore) { 2494 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2495 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2496 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2497 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2498 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2499 } 2500 } 2501 ver.fingerprint = Build.FINGERPRINT; 2502 } 2503 2504 checkDefaultBrowser(); 2505 2506 // clear only after permissions and other defaults have been updated 2507 mExistingSystemPackages.clear(); 2508 mPromoteSystemApps = false; 2509 2510 // All the changes are done during package scanning. 2511 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2512 2513 // can downgrade to reader 2514 mSettings.writeLPr(); 2515 2516 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2517 SystemClock.uptimeMillis()); 2518 2519 if (!mOnlyCore) { 2520 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2521 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2522 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2523 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2524 mIntentFilterVerifierComponent); 2525 } else { 2526 mRequiredVerifierPackage = null; 2527 mRequiredInstallerPackage = null; 2528 mIntentFilterVerifierComponent = null; 2529 mIntentFilterVerifier = null; 2530 } 2531 2532 mInstallerService = new PackageInstallerService(context, this); 2533 mSetupWizardPackage = getSetupWizardPackageName(); 2534 2535 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2536 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2537 // both the installer and resolver must be present to enable ephemeral 2538 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2539 if (DEBUG_EPHEMERAL) { 2540 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2541 + " installer:" + ephemeralInstallerComponent); 2542 } 2543 mEphemeralResolverComponent = ephemeralResolverComponent; 2544 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2545 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2546 mEphemeralResolverConnection = 2547 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2548 } else { 2549 if (DEBUG_EPHEMERAL) { 2550 final String missingComponent = 2551 (ephemeralResolverComponent == null) 2552 ? (ephemeralInstallerComponent == null) 2553 ? "resolver and installer" 2554 : "resolver" 2555 : "installer"; 2556 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2557 } 2558 mEphemeralResolverComponent = null; 2559 mEphemeralInstallerComponent = null; 2560 mEphemeralResolverConnection = null; 2561 } 2562 2563 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2564 } // synchronized (mPackages) 2565 } // synchronized (mInstallLock) 2566 2567 // Now after opening every single application zip, make sure they 2568 // are all flushed. Not really needed, but keeps things nice and 2569 // tidy. 2570 Runtime.getRuntime().gc(); 2571 2572 // The initial scanning above does many calls into installd while 2573 // holding the mPackages lock, but we're mostly interested in yelling 2574 // once we have a booted system. 2575 mInstaller.setWarnIfHeld(mPackages); 2576 2577 // Expose private service for system components to use. 2578 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2579 } 2580 2581 @Override 2582 public boolean isFirstBoot() { 2583 return !mRestoredSettings; 2584 } 2585 2586 @Override 2587 public boolean isOnlyCoreApps() { 2588 return mOnlyCore; 2589 } 2590 2591 @Override 2592 public boolean isUpgrade() { 2593 return mIsUpgrade; 2594 } 2595 2596 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2597 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2598 2599 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2600 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2601 UserHandle.USER_SYSTEM); 2602 if (matches.size() == 1) { 2603 return matches.get(0).getComponentInfo().packageName; 2604 } else { 2605 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2606 return null; 2607 } 2608 } 2609 2610 private @NonNull String getRequiredInstallerLPr() { 2611 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2612 intent.addCategory(Intent.CATEGORY_DEFAULT); 2613 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2614 2615 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2616 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2617 UserHandle.USER_SYSTEM); 2618 if (matches.size() == 1) { 2619 return matches.get(0).getComponentInfo().packageName; 2620 } else { 2621 throw new RuntimeException("There must be exactly one installer; found " + matches); 2622 } 2623 } 2624 2625 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2626 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2627 2628 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2629 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2630 UserHandle.USER_SYSTEM); 2631 ResolveInfo best = null; 2632 final int N = matches.size(); 2633 for (int i = 0; i < N; i++) { 2634 final ResolveInfo cur = matches.get(i); 2635 final String packageName = cur.getComponentInfo().packageName; 2636 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2637 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2638 continue; 2639 } 2640 2641 if (best == null || cur.priority > best.priority) { 2642 best = cur; 2643 } 2644 } 2645 2646 if (best != null) { 2647 return best.getComponentInfo().getComponentName(); 2648 } else { 2649 throw new RuntimeException("There must be at least one intent filter verifier"); 2650 } 2651 } 2652 2653 private @Nullable ComponentName getEphemeralResolverLPr() { 2654 final String[] packageArray = 2655 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2656 if (packageArray.length == 0) { 2657 if (DEBUG_EPHEMERAL) { 2658 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2659 } 2660 return null; 2661 } 2662 2663 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2664 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2665 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2666 UserHandle.USER_SYSTEM); 2667 2668 final int N = resolvers.size(); 2669 if (N == 0) { 2670 if (DEBUG_EPHEMERAL) { 2671 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2672 } 2673 return null; 2674 } 2675 2676 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2677 for (int i = 0; i < N; i++) { 2678 final ResolveInfo info = resolvers.get(i); 2679 2680 if (info.serviceInfo == null) { 2681 continue; 2682 } 2683 2684 final String packageName = info.serviceInfo.packageName; 2685 if (!possiblePackages.contains(packageName)) { 2686 if (DEBUG_EPHEMERAL) { 2687 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2688 + " pkg: " + packageName + ", info:" + info); 2689 } 2690 continue; 2691 } 2692 2693 if (DEBUG_EPHEMERAL) { 2694 Slog.v(TAG, "Ephemeral resolver found;" 2695 + " pkg: " + packageName + ", info:" + info); 2696 } 2697 return new ComponentName(packageName, info.serviceInfo.name); 2698 } 2699 if (DEBUG_EPHEMERAL) { 2700 Slog.v(TAG, "Ephemeral resolver NOT found"); 2701 } 2702 return null; 2703 } 2704 2705 private @Nullable ComponentName getEphemeralInstallerLPr() { 2706 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2707 intent.addCategory(Intent.CATEGORY_DEFAULT); 2708 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2709 2710 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2711 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2712 UserHandle.USER_SYSTEM); 2713 if (matches.size() == 0) { 2714 return null; 2715 } else if (matches.size() == 1) { 2716 return matches.get(0).getComponentInfo().getComponentName(); 2717 } else { 2718 throw new RuntimeException( 2719 "There must be at most one ephemeral installer; found " + matches); 2720 } 2721 } 2722 2723 private void primeDomainVerificationsLPw(int userId) { 2724 if (DEBUG_DOMAIN_VERIFICATION) { 2725 Slog.d(TAG, "Priming domain verifications in user " + userId); 2726 } 2727 2728 SystemConfig systemConfig = SystemConfig.getInstance(); 2729 ArraySet<String> packages = systemConfig.getLinkedApps(); 2730 ArraySet<String> domains = new ArraySet<String>(); 2731 2732 for (String packageName : packages) { 2733 PackageParser.Package pkg = mPackages.get(packageName); 2734 if (pkg != null) { 2735 if (!pkg.isSystemApp()) { 2736 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2737 continue; 2738 } 2739 2740 domains.clear(); 2741 for (PackageParser.Activity a : pkg.activities) { 2742 for (ActivityIntentInfo filter : a.intents) { 2743 if (hasValidDomains(filter)) { 2744 domains.addAll(filter.getHostsList()); 2745 } 2746 } 2747 } 2748 2749 if (domains.size() > 0) { 2750 if (DEBUG_DOMAIN_VERIFICATION) { 2751 Slog.v(TAG, " + " + packageName); 2752 } 2753 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2754 // state w.r.t. the formal app-linkage "no verification attempted" state; 2755 // and then 'always' in the per-user state actually used for intent resolution. 2756 final IntentFilterVerificationInfo ivi; 2757 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2758 new ArrayList<String>(domains)); 2759 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2760 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2761 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2762 } else { 2763 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2764 + "' does not handle web links"); 2765 } 2766 } else { 2767 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2768 } 2769 } 2770 2771 scheduleWritePackageRestrictionsLocked(userId); 2772 scheduleWriteSettingsLocked(); 2773 } 2774 2775 private void applyFactoryDefaultBrowserLPw(int userId) { 2776 // The default browser app's package name is stored in a string resource, 2777 // with a product-specific overlay used for vendor customization. 2778 String browserPkg = mContext.getResources().getString( 2779 com.android.internal.R.string.default_browser); 2780 if (!TextUtils.isEmpty(browserPkg)) { 2781 // non-empty string => required to be a known package 2782 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2783 if (ps == null) { 2784 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2785 browserPkg = null; 2786 } else { 2787 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2788 } 2789 } 2790 2791 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2792 // default. If there's more than one, just leave everything alone. 2793 if (browserPkg == null) { 2794 calculateDefaultBrowserLPw(userId); 2795 } 2796 } 2797 2798 private void calculateDefaultBrowserLPw(int userId) { 2799 List<String> allBrowsers = resolveAllBrowserApps(userId); 2800 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2801 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2802 } 2803 2804 private List<String> resolveAllBrowserApps(int userId) { 2805 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2806 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2807 PackageManager.MATCH_ALL, userId); 2808 2809 final int count = list.size(); 2810 List<String> result = new ArrayList<String>(count); 2811 for (int i=0; i<count; i++) { 2812 ResolveInfo info = list.get(i); 2813 if (info.activityInfo == null 2814 || !info.handleAllWebDataURI 2815 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2816 || result.contains(info.activityInfo.packageName)) { 2817 continue; 2818 } 2819 result.add(info.activityInfo.packageName); 2820 } 2821 2822 return result; 2823 } 2824 2825 private boolean packageIsBrowser(String packageName, int userId) { 2826 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2827 PackageManager.MATCH_ALL, userId); 2828 final int N = list.size(); 2829 for (int i = 0; i < N; i++) { 2830 ResolveInfo info = list.get(i); 2831 if (packageName.equals(info.activityInfo.packageName)) { 2832 return true; 2833 } 2834 } 2835 return false; 2836 } 2837 2838 private void checkDefaultBrowser() { 2839 final int myUserId = UserHandle.myUserId(); 2840 final String packageName = getDefaultBrowserPackageName(myUserId); 2841 if (packageName != null) { 2842 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2843 if (info == null) { 2844 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2845 synchronized (mPackages) { 2846 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2847 } 2848 } 2849 } 2850 } 2851 2852 @Override 2853 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2854 throws RemoteException { 2855 try { 2856 return super.onTransact(code, data, reply, flags); 2857 } catch (RuntimeException e) { 2858 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2859 Slog.wtf(TAG, "Package Manager Crash", e); 2860 } 2861 throw e; 2862 } 2863 } 2864 2865 void cleanupInstallFailedPackage(PackageSetting ps) { 2866 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2867 2868 removeDataDirsLI(ps.volumeUuid, ps.name); 2869 if (ps.codePath != null) { 2870 removeCodePathLI(ps.codePath); 2871 } 2872 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2873 if (ps.resourcePath.isDirectory()) { 2874 FileUtils.deleteContents(ps.resourcePath); 2875 } 2876 ps.resourcePath.delete(); 2877 } 2878 mSettings.removePackageLPw(ps.name); 2879 } 2880 2881 static int[] appendInts(int[] cur, int[] add) { 2882 if (add == null) return cur; 2883 if (cur == null) return add; 2884 final int N = add.length; 2885 for (int i=0; i<N; i++) { 2886 cur = appendInt(cur, add[i]); 2887 } 2888 return cur; 2889 } 2890 2891 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2892 if (!sUserManager.exists(userId)) return null; 2893 final PackageSetting ps = (PackageSetting) p.mExtras; 2894 if (ps == null) { 2895 return null; 2896 } 2897 2898 final PermissionsState permissionsState = ps.getPermissionsState(); 2899 2900 final int[] gids = permissionsState.computeGids(userId); 2901 final Set<String> permissions = permissionsState.getPermissions(userId); 2902 final PackageUserState state = ps.readUserState(userId); 2903 2904 return PackageParser.generatePackageInfo(p, gids, flags, 2905 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2906 } 2907 2908 @Override 2909 public void checkPackageStartable(String packageName, int userId) { 2910 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2911 2912 synchronized (mPackages) { 2913 final PackageSetting ps = mSettings.mPackages.get(packageName); 2914 if (ps == null) { 2915 throw new SecurityException("Package " + packageName + " was not found!"); 2916 } 2917 2918 if (!ps.getInstalled(userId)) { 2919 throw new SecurityException( 2920 "Package " + packageName + " was not installed for user " + userId + "!"); 2921 } 2922 2923 if (mSafeMode && !ps.isSystem()) { 2924 throw new SecurityException("Package " + packageName + " not a system app!"); 2925 } 2926 2927 if (ps.frozen) { 2928 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2929 } 2930 2931 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2932 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2933 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2934 } 2935 } 2936 } 2937 2938 @Override 2939 public boolean isPackageAvailable(String packageName, int userId) { 2940 if (!sUserManager.exists(userId)) return false; 2941 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2942 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2943 synchronized (mPackages) { 2944 PackageParser.Package p = mPackages.get(packageName); 2945 if (p != null) { 2946 final PackageSetting ps = (PackageSetting) p.mExtras; 2947 if (ps != null) { 2948 final PackageUserState state = ps.readUserState(userId); 2949 if (state != null) { 2950 return PackageParser.isAvailable(state); 2951 } 2952 } 2953 } 2954 } 2955 return false; 2956 } 2957 2958 @Override 2959 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2960 if (!sUserManager.exists(userId)) return null; 2961 flags = updateFlagsForPackage(flags, userId, packageName); 2962 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2963 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2964 // reader 2965 synchronized (mPackages) { 2966 PackageParser.Package p = mPackages.get(packageName); 2967 if (DEBUG_PACKAGE_INFO) 2968 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2969 if (p != null) { 2970 return generatePackageInfo(p, flags, userId); 2971 } 2972 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2973 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2974 } 2975 } 2976 return null; 2977 } 2978 2979 @Override 2980 public String[] currentToCanonicalPackageNames(String[] names) { 2981 String[] out = new String[names.length]; 2982 // reader 2983 synchronized (mPackages) { 2984 for (int i=names.length-1; i>=0; i--) { 2985 PackageSetting ps = mSettings.mPackages.get(names[i]); 2986 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2987 } 2988 } 2989 return out; 2990 } 2991 2992 @Override 2993 public String[] canonicalToCurrentPackageNames(String[] names) { 2994 String[] out = new String[names.length]; 2995 // reader 2996 synchronized (mPackages) { 2997 for (int i=names.length-1; i>=0; i--) { 2998 String cur = mSettings.mRenamedPackages.get(names[i]); 2999 out[i] = cur != null ? cur : names[i]; 3000 } 3001 } 3002 return out; 3003 } 3004 3005 @Override 3006 public int getPackageUid(String packageName, int flags, int userId) { 3007 if (!sUserManager.exists(userId)) return -1; 3008 flags = updateFlagsForPackage(flags, userId, packageName); 3009 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3010 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3011 3012 // reader 3013 synchronized (mPackages) { 3014 final PackageParser.Package p = mPackages.get(packageName); 3015 if (p != null && p.isMatch(flags)) { 3016 return UserHandle.getUid(userId, p.applicationInfo.uid); 3017 } 3018 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3019 final PackageSetting ps = mSettings.mPackages.get(packageName); 3020 if (ps != null && ps.isMatch(flags)) { 3021 return UserHandle.getUid(userId, ps.appId); 3022 } 3023 } 3024 } 3025 3026 return -1; 3027 } 3028 3029 @Override 3030 public int[] getPackageGids(String packageName, int flags, int userId) { 3031 if (!sUserManager.exists(userId)) return null; 3032 flags = updateFlagsForPackage(flags, userId, packageName); 3033 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3034 false /* requireFullPermission */, false /* checkShell */, 3035 "getPackageGids"); 3036 3037 // reader 3038 synchronized (mPackages) { 3039 final PackageParser.Package p = mPackages.get(packageName); 3040 if (p != null && p.isMatch(flags)) { 3041 PackageSetting ps = (PackageSetting) p.mExtras; 3042 return ps.getPermissionsState().computeGids(userId); 3043 } 3044 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3045 final PackageSetting ps = mSettings.mPackages.get(packageName); 3046 if (ps != null && ps.isMatch(flags)) { 3047 return ps.getPermissionsState().computeGids(userId); 3048 } 3049 } 3050 } 3051 3052 return null; 3053 } 3054 3055 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3056 if (bp.perm != null) { 3057 return PackageParser.generatePermissionInfo(bp.perm, flags); 3058 } 3059 PermissionInfo pi = new PermissionInfo(); 3060 pi.name = bp.name; 3061 pi.packageName = bp.sourcePackage; 3062 pi.nonLocalizedLabel = bp.name; 3063 pi.protectionLevel = bp.protectionLevel; 3064 return pi; 3065 } 3066 3067 @Override 3068 public PermissionInfo getPermissionInfo(String name, int flags) { 3069 // reader 3070 synchronized (mPackages) { 3071 final BasePermission p = mSettings.mPermissions.get(name); 3072 if (p != null) { 3073 return generatePermissionInfo(p, flags); 3074 } 3075 return null; 3076 } 3077 } 3078 3079 @Override 3080 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3081 int flags) { 3082 // reader 3083 synchronized (mPackages) { 3084 if (group != null && !mPermissionGroups.containsKey(group)) { 3085 // This is thrown as NameNotFoundException 3086 return null; 3087 } 3088 3089 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3090 for (BasePermission p : mSettings.mPermissions.values()) { 3091 if (group == null) { 3092 if (p.perm == null || p.perm.info.group == null) { 3093 out.add(generatePermissionInfo(p, flags)); 3094 } 3095 } else { 3096 if (p.perm != null && group.equals(p.perm.info.group)) { 3097 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3098 } 3099 } 3100 } 3101 return new ParceledListSlice<>(out); 3102 } 3103 } 3104 3105 @Override 3106 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3107 // reader 3108 synchronized (mPackages) { 3109 return PackageParser.generatePermissionGroupInfo( 3110 mPermissionGroups.get(name), flags); 3111 } 3112 } 3113 3114 @Override 3115 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3116 // reader 3117 synchronized (mPackages) { 3118 final int N = mPermissionGroups.size(); 3119 ArrayList<PermissionGroupInfo> out 3120 = new ArrayList<PermissionGroupInfo>(N); 3121 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3122 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3123 } 3124 return new ParceledListSlice<>(out); 3125 } 3126 } 3127 3128 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3129 int userId) { 3130 if (!sUserManager.exists(userId)) return null; 3131 PackageSetting ps = mSettings.mPackages.get(packageName); 3132 if (ps != null) { 3133 if (ps.pkg == null) { 3134 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3135 flags, userId); 3136 if (pInfo != null) { 3137 return pInfo.applicationInfo; 3138 } 3139 return null; 3140 } 3141 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3142 ps.readUserState(userId), userId); 3143 } 3144 return null; 3145 } 3146 3147 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3148 int userId) { 3149 if (!sUserManager.exists(userId)) return null; 3150 PackageSetting ps = mSettings.mPackages.get(packageName); 3151 if (ps != null) { 3152 PackageParser.Package pkg = ps.pkg; 3153 if (pkg == null) { 3154 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3155 return null; 3156 } 3157 // Only data remains, so we aren't worried about code paths 3158 pkg = new PackageParser.Package(packageName); 3159 pkg.applicationInfo.packageName = packageName; 3160 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3161 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3162 pkg.applicationInfo.uid = ps.appId; 3163 pkg.applicationInfo.initForUser(userId); 3164 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3165 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3166 } 3167 return generatePackageInfo(pkg, flags, userId); 3168 } 3169 return null; 3170 } 3171 3172 @Override 3173 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3174 if (!sUserManager.exists(userId)) return null; 3175 flags = updateFlagsForApplication(flags, userId, packageName); 3176 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3177 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3178 // writer 3179 synchronized (mPackages) { 3180 PackageParser.Package p = mPackages.get(packageName); 3181 if (DEBUG_PACKAGE_INFO) Log.v( 3182 TAG, "getApplicationInfo " + packageName 3183 + ": " + p); 3184 if (p != null) { 3185 PackageSetting ps = mSettings.mPackages.get(packageName); 3186 if (ps == null) return null; 3187 // Note: isEnabledLP() does not apply here - always return info 3188 return PackageParser.generateApplicationInfo( 3189 p, flags, ps.readUserState(userId), userId); 3190 } 3191 if ("android".equals(packageName)||"system".equals(packageName)) { 3192 return mAndroidApplication; 3193 } 3194 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3195 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3196 } 3197 } 3198 return null; 3199 } 3200 3201 @Override 3202 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3203 final IPackageDataObserver observer) { 3204 mContext.enforceCallingOrSelfPermission( 3205 android.Manifest.permission.CLEAR_APP_CACHE, null); 3206 // Queue up an async operation since clearing cache may take a little while. 3207 mHandler.post(new Runnable() { 3208 public void run() { 3209 mHandler.removeCallbacks(this); 3210 boolean success = true; 3211 synchronized (mInstallLock) { 3212 try { 3213 mInstaller.freeCache(volumeUuid, freeStorageSize); 3214 } catch (InstallerException e) { 3215 Slog.w(TAG, "Couldn't clear application caches: " + e); 3216 success = false; 3217 } 3218 } 3219 if (observer != null) { 3220 try { 3221 observer.onRemoveCompleted(null, success); 3222 } catch (RemoteException e) { 3223 Slog.w(TAG, "RemoveException when invoking call back"); 3224 } 3225 } 3226 } 3227 }); 3228 } 3229 3230 @Override 3231 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3232 final IntentSender pi) { 3233 mContext.enforceCallingOrSelfPermission( 3234 android.Manifest.permission.CLEAR_APP_CACHE, null); 3235 // Queue up an async operation since clearing cache may take a little while. 3236 mHandler.post(new Runnable() { 3237 public void run() { 3238 mHandler.removeCallbacks(this); 3239 boolean success = true; 3240 synchronized (mInstallLock) { 3241 try { 3242 mInstaller.freeCache(volumeUuid, freeStorageSize); 3243 } catch (InstallerException e) { 3244 Slog.w(TAG, "Couldn't clear application caches: " + e); 3245 success = false; 3246 } 3247 } 3248 if(pi != null) { 3249 try { 3250 // Callback via pending intent 3251 int code = success ? 1 : 0; 3252 pi.sendIntent(null, code, null, 3253 null, null); 3254 } catch (SendIntentException e1) { 3255 Slog.i(TAG, "Failed to send pending intent"); 3256 } 3257 } 3258 } 3259 }); 3260 } 3261 3262 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3263 synchronized (mInstallLock) { 3264 try { 3265 mInstaller.freeCache(volumeUuid, freeStorageSize); 3266 } catch (InstallerException e) { 3267 throw new IOException("Failed to free enough space", e); 3268 } 3269 } 3270 } 3271 3272 /** 3273 * Return if the user key is currently unlocked. 3274 */ 3275 private boolean isUserKeyUnlocked(int userId) { 3276 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3277 final IMountService mount = IMountService.Stub 3278 .asInterface(ServiceManager.getService("mount")); 3279 if (mount == null) { 3280 Slog.w(TAG, "Early during boot, assuming locked"); 3281 return false; 3282 } 3283 final long token = Binder.clearCallingIdentity(); 3284 try { 3285 return mount.isUserKeyUnlocked(userId); 3286 } catch (RemoteException e) { 3287 throw e.rethrowAsRuntimeException(); 3288 } finally { 3289 Binder.restoreCallingIdentity(token); 3290 } 3291 } else { 3292 return true; 3293 } 3294 } 3295 3296 /** 3297 * Update given flags based on encryption status of current user. 3298 */ 3299 private int updateFlags(int flags, int userId) { 3300 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3301 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3302 // Caller expressed an explicit opinion about what encryption 3303 // aware/unaware components they want to see, so fall through and 3304 // give them what they want 3305 } else { 3306 // Caller expressed no opinion, so match based on user state 3307 if (isUserKeyUnlocked(userId)) { 3308 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3309 } else { 3310 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3311 } 3312 } 3313 return flags; 3314 } 3315 3316 /** 3317 * Update given flags when being used to request {@link PackageInfo}. 3318 */ 3319 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3320 boolean triaged = true; 3321 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3322 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3323 // Caller is asking for component details, so they'd better be 3324 // asking for specific encryption matching behavior, or be triaged 3325 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3326 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3327 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3328 triaged = false; 3329 } 3330 } 3331 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3332 | PackageManager.MATCH_SYSTEM_ONLY 3333 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3334 triaged = false; 3335 } 3336 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3337 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3338 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3339 } 3340 return updateFlags(flags, userId); 3341 } 3342 3343 /** 3344 * Update given flags when being used to request {@link ApplicationInfo}. 3345 */ 3346 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3347 return updateFlagsForPackage(flags, userId, cookie); 3348 } 3349 3350 /** 3351 * Update given flags when being used to request {@link ComponentInfo}. 3352 */ 3353 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3354 if (cookie instanceof Intent) { 3355 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3356 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3357 } 3358 } 3359 3360 boolean triaged = true; 3361 // Caller is asking for component details, so they'd better be 3362 // asking for specific encryption matching behavior, or be triaged 3363 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3364 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3365 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3366 triaged = false; 3367 } 3368 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3369 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3370 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3371 } 3372 3373 return updateFlags(flags, userId); 3374 } 3375 3376 /** 3377 * Update given flags when being used to request {@link ResolveInfo}. 3378 */ 3379 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3380 // Safe mode means we shouldn't match any third-party components 3381 if (mSafeMode) { 3382 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3383 } 3384 3385 return updateFlagsForComponent(flags, userId, cookie); 3386 } 3387 3388 @Override 3389 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3390 if (!sUserManager.exists(userId)) return null; 3391 flags = updateFlagsForComponent(flags, userId, component); 3392 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3393 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3394 synchronized (mPackages) { 3395 PackageParser.Activity a = mActivities.mActivities.get(component); 3396 3397 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3398 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3399 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3400 if (ps == null) return null; 3401 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3402 userId); 3403 } 3404 if (mResolveComponentName.equals(component)) { 3405 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3406 new PackageUserState(), userId); 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3414 String resolvedType) { 3415 synchronized (mPackages) { 3416 if (component.equals(mResolveComponentName)) { 3417 // The resolver supports EVERYTHING! 3418 return true; 3419 } 3420 PackageParser.Activity a = mActivities.mActivities.get(component); 3421 if (a == null) { 3422 return false; 3423 } 3424 for (int i=0; i<a.intents.size(); i++) { 3425 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3426 intent.getData(), intent.getCategories(), TAG) >= 0) { 3427 return true; 3428 } 3429 } 3430 return false; 3431 } 3432 } 3433 3434 @Override 3435 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3436 if (!sUserManager.exists(userId)) return null; 3437 flags = updateFlagsForComponent(flags, userId, component); 3438 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3439 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3440 synchronized (mPackages) { 3441 PackageParser.Activity a = mReceivers.mActivities.get(component); 3442 if (DEBUG_PACKAGE_INFO) Log.v( 3443 TAG, "getReceiverInfo " + component + ": " + a); 3444 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3445 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3446 if (ps == null) return null; 3447 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3448 userId); 3449 } 3450 } 3451 return null; 3452 } 3453 3454 @Override 3455 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3456 if (!sUserManager.exists(userId)) return null; 3457 flags = updateFlagsForComponent(flags, userId, component); 3458 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3459 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3460 synchronized (mPackages) { 3461 PackageParser.Service s = mServices.mServices.get(component); 3462 if (DEBUG_PACKAGE_INFO) Log.v( 3463 TAG, "getServiceInfo " + component + ": " + s); 3464 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3465 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3466 if (ps == null) return null; 3467 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3468 userId); 3469 } 3470 } 3471 return null; 3472 } 3473 3474 @Override 3475 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3476 if (!sUserManager.exists(userId)) return null; 3477 flags = updateFlagsForComponent(flags, userId, component); 3478 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3479 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3480 synchronized (mPackages) { 3481 PackageParser.Provider p = mProviders.mProviders.get(component); 3482 if (DEBUG_PACKAGE_INFO) Log.v( 3483 TAG, "getProviderInfo " + component + ": " + p); 3484 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3485 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3486 if (ps == null) return null; 3487 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3488 userId); 3489 } 3490 } 3491 return null; 3492 } 3493 3494 @Override 3495 public String[] getSystemSharedLibraryNames() { 3496 Set<String> libSet; 3497 synchronized (mPackages) { 3498 libSet = mSharedLibraries.keySet(); 3499 int size = libSet.size(); 3500 if (size > 0) { 3501 String[] libs = new String[size]; 3502 libSet.toArray(libs); 3503 return libs; 3504 } 3505 } 3506 return null; 3507 } 3508 3509 @Override 3510 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3511 synchronized (mPackages) { 3512 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3513 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3514 if (libraryEntry != null) { 3515 return libraryEntry.apk; 3516 } 3517 } 3518 return null; 3519 } 3520 3521 @Override 3522 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3523 synchronized (mPackages) { 3524 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3525 3526 final FeatureInfo fi = new FeatureInfo(); 3527 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3528 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3529 res.add(fi); 3530 3531 return new ParceledListSlice<>(res); 3532 } 3533 } 3534 3535 @Override 3536 public boolean hasSystemFeature(String name, int version) { 3537 synchronized (mPackages) { 3538 final FeatureInfo feat = mAvailableFeatures.get(name); 3539 if (feat == null) { 3540 return false; 3541 } else { 3542 return feat.version >= version; 3543 } 3544 } 3545 } 3546 3547 @Override 3548 public int checkPermission(String permName, String pkgName, int userId) { 3549 if (!sUserManager.exists(userId)) { 3550 return PackageManager.PERMISSION_DENIED; 3551 } 3552 3553 synchronized (mPackages) { 3554 final PackageParser.Package p = mPackages.get(pkgName); 3555 if (p != null && p.mExtras != null) { 3556 final PackageSetting ps = (PackageSetting) p.mExtras; 3557 final PermissionsState permissionsState = ps.getPermissionsState(); 3558 if (permissionsState.hasPermission(permName, userId)) { 3559 return PackageManager.PERMISSION_GRANTED; 3560 } 3561 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3562 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3563 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3564 return PackageManager.PERMISSION_GRANTED; 3565 } 3566 } 3567 } 3568 3569 return PackageManager.PERMISSION_DENIED; 3570 } 3571 3572 @Override 3573 public int checkUidPermission(String permName, int uid) { 3574 final int userId = UserHandle.getUserId(uid); 3575 3576 if (!sUserManager.exists(userId)) { 3577 return PackageManager.PERMISSION_DENIED; 3578 } 3579 3580 synchronized (mPackages) { 3581 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3582 if (obj != null) { 3583 final SettingBase ps = (SettingBase) obj; 3584 final PermissionsState permissionsState = ps.getPermissionsState(); 3585 if (permissionsState.hasPermission(permName, userId)) { 3586 return PackageManager.PERMISSION_GRANTED; 3587 } 3588 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3589 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3590 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3591 return PackageManager.PERMISSION_GRANTED; 3592 } 3593 } else { 3594 ArraySet<String> perms = mSystemPermissions.get(uid); 3595 if (perms != null) { 3596 if (perms.contains(permName)) { 3597 return PackageManager.PERMISSION_GRANTED; 3598 } 3599 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3600 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3601 return PackageManager.PERMISSION_GRANTED; 3602 } 3603 } 3604 } 3605 } 3606 3607 return PackageManager.PERMISSION_DENIED; 3608 } 3609 3610 @Override 3611 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3612 if (UserHandle.getCallingUserId() != userId) { 3613 mContext.enforceCallingPermission( 3614 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3615 "isPermissionRevokedByPolicy for user " + userId); 3616 } 3617 3618 if (checkPermission(permission, packageName, userId) 3619 == PackageManager.PERMISSION_GRANTED) { 3620 return false; 3621 } 3622 3623 final long identity = Binder.clearCallingIdentity(); 3624 try { 3625 final int flags = getPermissionFlags(permission, packageName, userId); 3626 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3627 } finally { 3628 Binder.restoreCallingIdentity(identity); 3629 } 3630 } 3631 3632 @Override 3633 public String getPermissionControllerPackageName() { 3634 synchronized (mPackages) { 3635 return mRequiredInstallerPackage; 3636 } 3637 } 3638 3639 /** 3640 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3641 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3642 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3643 * @param message the message to log on security exception 3644 */ 3645 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3646 boolean checkShell, String message) { 3647 if (userId < 0) { 3648 throw new IllegalArgumentException("Invalid userId " + userId); 3649 } 3650 if (checkShell) { 3651 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3652 } 3653 if (userId == UserHandle.getUserId(callingUid)) return; 3654 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3655 if (requireFullPermission) { 3656 mContext.enforceCallingOrSelfPermission( 3657 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3658 } else { 3659 try { 3660 mContext.enforceCallingOrSelfPermission( 3661 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3662 } catch (SecurityException se) { 3663 mContext.enforceCallingOrSelfPermission( 3664 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3665 } 3666 } 3667 } 3668 } 3669 3670 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3671 if (callingUid == Process.SHELL_UID) { 3672 if (userHandle >= 0 3673 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3674 throw new SecurityException("Shell does not have permission to access user " 3675 + userHandle); 3676 } else if (userHandle < 0) { 3677 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3678 + Debug.getCallers(3)); 3679 } 3680 } 3681 } 3682 3683 private BasePermission findPermissionTreeLP(String permName) { 3684 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3685 if (permName.startsWith(bp.name) && 3686 permName.length() > bp.name.length() && 3687 permName.charAt(bp.name.length()) == '.') { 3688 return bp; 3689 } 3690 } 3691 return null; 3692 } 3693 3694 private BasePermission checkPermissionTreeLP(String permName) { 3695 if (permName != null) { 3696 BasePermission bp = findPermissionTreeLP(permName); 3697 if (bp != null) { 3698 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3699 return bp; 3700 } 3701 throw new SecurityException("Calling uid " 3702 + Binder.getCallingUid() 3703 + " is not allowed to add to permission tree " 3704 + bp.name + " owned by uid " + bp.uid); 3705 } 3706 } 3707 throw new SecurityException("No permission tree found for " + permName); 3708 } 3709 3710 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3711 if (s1 == null) { 3712 return s2 == null; 3713 } 3714 if (s2 == null) { 3715 return false; 3716 } 3717 if (s1.getClass() != s2.getClass()) { 3718 return false; 3719 } 3720 return s1.equals(s2); 3721 } 3722 3723 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3724 if (pi1.icon != pi2.icon) return false; 3725 if (pi1.logo != pi2.logo) return false; 3726 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3727 if (!compareStrings(pi1.name, pi2.name)) return false; 3728 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3729 // We'll take care of setting this one. 3730 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3731 // These are not currently stored in settings. 3732 //if (!compareStrings(pi1.group, pi2.group)) return false; 3733 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3734 //if (pi1.labelRes != pi2.labelRes) return false; 3735 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3736 return true; 3737 } 3738 3739 int permissionInfoFootprint(PermissionInfo info) { 3740 int size = info.name.length(); 3741 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3742 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3743 return size; 3744 } 3745 3746 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3747 int size = 0; 3748 for (BasePermission perm : mSettings.mPermissions.values()) { 3749 if (perm.uid == tree.uid) { 3750 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3751 } 3752 } 3753 return size; 3754 } 3755 3756 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3757 // We calculate the max size of permissions defined by this uid and throw 3758 // if that plus the size of 'info' would exceed our stated maximum. 3759 if (tree.uid != Process.SYSTEM_UID) { 3760 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3761 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3762 throw new SecurityException("Permission tree size cap exceeded"); 3763 } 3764 } 3765 } 3766 3767 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3768 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3769 throw new SecurityException("Label must be specified in permission"); 3770 } 3771 BasePermission tree = checkPermissionTreeLP(info.name); 3772 BasePermission bp = mSettings.mPermissions.get(info.name); 3773 boolean added = bp == null; 3774 boolean changed = true; 3775 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3776 if (added) { 3777 enforcePermissionCapLocked(info, tree); 3778 bp = new BasePermission(info.name, tree.sourcePackage, 3779 BasePermission.TYPE_DYNAMIC); 3780 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3781 throw new SecurityException( 3782 "Not allowed to modify non-dynamic permission " 3783 + info.name); 3784 } else { 3785 if (bp.protectionLevel == fixedLevel 3786 && bp.perm.owner.equals(tree.perm.owner) 3787 && bp.uid == tree.uid 3788 && comparePermissionInfos(bp.perm.info, info)) { 3789 changed = false; 3790 } 3791 } 3792 bp.protectionLevel = fixedLevel; 3793 info = new PermissionInfo(info); 3794 info.protectionLevel = fixedLevel; 3795 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3796 bp.perm.info.packageName = tree.perm.info.packageName; 3797 bp.uid = tree.uid; 3798 if (added) { 3799 mSettings.mPermissions.put(info.name, bp); 3800 } 3801 if (changed) { 3802 if (!async) { 3803 mSettings.writeLPr(); 3804 } else { 3805 scheduleWriteSettingsLocked(); 3806 } 3807 } 3808 return added; 3809 } 3810 3811 @Override 3812 public boolean addPermission(PermissionInfo info) { 3813 synchronized (mPackages) { 3814 return addPermissionLocked(info, false); 3815 } 3816 } 3817 3818 @Override 3819 public boolean addPermissionAsync(PermissionInfo info) { 3820 synchronized (mPackages) { 3821 return addPermissionLocked(info, true); 3822 } 3823 } 3824 3825 @Override 3826 public void removePermission(String name) { 3827 synchronized (mPackages) { 3828 checkPermissionTreeLP(name); 3829 BasePermission bp = mSettings.mPermissions.get(name); 3830 if (bp != null) { 3831 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3832 throw new SecurityException( 3833 "Not allowed to modify non-dynamic permission " 3834 + name); 3835 } 3836 mSettings.mPermissions.remove(name); 3837 mSettings.writeLPr(); 3838 } 3839 } 3840 } 3841 3842 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3843 BasePermission bp) { 3844 int index = pkg.requestedPermissions.indexOf(bp.name); 3845 if (index == -1) { 3846 throw new SecurityException("Package " + pkg.packageName 3847 + " has not requested permission " + bp.name); 3848 } 3849 if (!bp.isRuntime() && !bp.isDevelopment()) { 3850 throw new SecurityException("Permission " + bp.name 3851 + " is not a changeable permission type"); 3852 } 3853 } 3854 3855 @Override 3856 public void grantRuntimePermission(String packageName, String name, final int userId) { 3857 if (!sUserManager.exists(userId)) { 3858 Log.e(TAG, "No such user:" + userId); 3859 return; 3860 } 3861 3862 mContext.enforceCallingOrSelfPermission( 3863 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3864 "grantRuntimePermission"); 3865 3866 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3867 true /* requireFullPermission */, true /* checkShell */, 3868 "grantRuntimePermission"); 3869 3870 final int uid; 3871 final SettingBase sb; 3872 3873 synchronized (mPackages) { 3874 final PackageParser.Package pkg = mPackages.get(packageName); 3875 if (pkg == null) { 3876 throw new IllegalArgumentException("Unknown package: " + packageName); 3877 } 3878 3879 final BasePermission bp = mSettings.mPermissions.get(name); 3880 if (bp == null) { 3881 throw new IllegalArgumentException("Unknown permission: " + name); 3882 } 3883 3884 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3885 3886 // If a permission review is required for legacy apps we represent 3887 // their permissions as always granted runtime ones since we need 3888 // to keep the review required permission flag per user while an 3889 // install permission's state is shared across all users. 3890 if (Build.PERMISSIONS_REVIEW_REQUIRED 3891 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3892 && bp.isRuntime()) { 3893 return; 3894 } 3895 3896 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3897 sb = (SettingBase) pkg.mExtras; 3898 if (sb == null) { 3899 throw new IllegalArgumentException("Unknown package: " + packageName); 3900 } 3901 3902 final PermissionsState permissionsState = sb.getPermissionsState(); 3903 3904 final int flags = permissionsState.getPermissionFlags(name, userId); 3905 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3906 throw new SecurityException("Cannot grant system fixed permission " 3907 + name + " for package " + packageName); 3908 } 3909 3910 if (bp.isDevelopment()) { 3911 // Development permissions must be handled specially, since they are not 3912 // normal runtime permissions. For now they apply to all users. 3913 if (permissionsState.grantInstallPermission(bp) != 3914 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3915 scheduleWriteSettingsLocked(); 3916 } 3917 return; 3918 } 3919 3920 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3921 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3922 return; 3923 } 3924 3925 final int result = permissionsState.grantRuntimePermission(bp, userId); 3926 switch (result) { 3927 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3928 return; 3929 } 3930 3931 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3932 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3933 mHandler.post(new Runnable() { 3934 @Override 3935 public void run() { 3936 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3937 } 3938 }); 3939 } 3940 break; 3941 } 3942 3943 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3944 3945 // Not critical if that is lost - app has to request again. 3946 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3947 } 3948 3949 // Only need to do this if user is initialized. Otherwise it's a new user 3950 // and there are no processes running as the user yet and there's no need 3951 // to make an expensive call to remount processes for the changed permissions. 3952 if (READ_EXTERNAL_STORAGE.equals(name) 3953 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3954 final long token = Binder.clearCallingIdentity(); 3955 try { 3956 if (sUserManager.isInitialized(userId)) { 3957 MountServiceInternal mountServiceInternal = LocalServices.getService( 3958 MountServiceInternal.class); 3959 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3960 } 3961 } finally { 3962 Binder.restoreCallingIdentity(token); 3963 } 3964 } 3965 } 3966 3967 @Override 3968 public void revokeRuntimePermission(String packageName, String name, int userId) { 3969 if (!sUserManager.exists(userId)) { 3970 Log.e(TAG, "No such user:" + userId); 3971 return; 3972 } 3973 3974 mContext.enforceCallingOrSelfPermission( 3975 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3976 "revokeRuntimePermission"); 3977 3978 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3979 true /* requireFullPermission */, true /* checkShell */, 3980 "revokeRuntimePermission"); 3981 3982 final int appId; 3983 3984 synchronized (mPackages) { 3985 final PackageParser.Package pkg = mPackages.get(packageName); 3986 if (pkg == null) { 3987 throw new IllegalArgumentException("Unknown package: " + packageName); 3988 } 3989 3990 final BasePermission bp = mSettings.mPermissions.get(name); 3991 if (bp == null) { 3992 throw new IllegalArgumentException("Unknown permission: " + name); 3993 } 3994 3995 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3996 3997 // If a permission review is required for legacy apps we represent 3998 // their permissions as always granted runtime ones since we need 3999 // to keep the review required permission flag per user while an 4000 // install permission's state is shared across all users. 4001 if (Build.PERMISSIONS_REVIEW_REQUIRED 4002 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4003 && bp.isRuntime()) { 4004 return; 4005 } 4006 4007 SettingBase sb = (SettingBase) pkg.mExtras; 4008 if (sb == null) { 4009 throw new IllegalArgumentException("Unknown package: " + packageName); 4010 } 4011 4012 final PermissionsState permissionsState = sb.getPermissionsState(); 4013 4014 final int flags = permissionsState.getPermissionFlags(name, userId); 4015 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4016 throw new SecurityException("Cannot revoke system fixed permission " 4017 + name + " for package " + packageName); 4018 } 4019 4020 if (bp.isDevelopment()) { 4021 // Development permissions must be handled specially, since they are not 4022 // normal runtime permissions. For now they apply to all users. 4023 if (permissionsState.revokeInstallPermission(bp) != 4024 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4025 scheduleWriteSettingsLocked(); 4026 } 4027 return; 4028 } 4029 4030 if (permissionsState.revokeRuntimePermission(bp, userId) == 4031 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4032 return; 4033 } 4034 4035 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4036 4037 // Critical, after this call app should never have the permission. 4038 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4039 4040 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4041 } 4042 4043 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4044 } 4045 4046 @Override 4047 public void resetRuntimePermissions() { 4048 mContext.enforceCallingOrSelfPermission( 4049 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4050 "revokeRuntimePermission"); 4051 4052 int callingUid = Binder.getCallingUid(); 4053 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4054 mContext.enforceCallingOrSelfPermission( 4055 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4056 "resetRuntimePermissions"); 4057 } 4058 4059 synchronized (mPackages) { 4060 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4061 for (int userId : UserManagerService.getInstance().getUserIds()) { 4062 final int packageCount = mPackages.size(); 4063 for (int i = 0; i < packageCount; i++) { 4064 PackageParser.Package pkg = mPackages.valueAt(i); 4065 if (!(pkg.mExtras instanceof PackageSetting)) { 4066 continue; 4067 } 4068 PackageSetting ps = (PackageSetting) pkg.mExtras; 4069 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4070 } 4071 } 4072 } 4073 } 4074 4075 @Override 4076 public int getPermissionFlags(String name, String packageName, int userId) { 4077 if (!sUserManager.exists(userId)) { 4078 return 0; 4079 } 4080 4081 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4082 4083 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4084 true /* requireFullPermission */, false /* checkShell */, 4085 "getPermissionFlags"); 4086 4087 synchronized (mPackages) { 4088 final PackageParser.Package pkg = mPackages.get(packageName); 4089 if (pkg == null) { 4090 throw new IllegalArgumentException("Unknown package: " + packageName); 4091 } 4092 4093 final BasePermission bp = mSettings.mPermissions.get(name); 4094 if (bp == null) { 4095 throw new IllegalArgumentException("Unknown permission: " + name); 4096 } 4097 4098 SettingBase sb = (SettingBase) pkg.mExtras; 4099 if (sb == null) { 4100 throw new IllegalArgumentException("Unknown package: " + packageName); 4101 } 4102 4103 PermissionsState permissionsState = sb.getPermissionsState(); 4104 return permissionsState.getPermissionFlags(name, userId); 4105 } 4106 } 4107 4108 @Override 4109 public void updatePermissionFlags(String name, String packageName, int flagMask, 4110 int flagValues, int userId) { 4111 if (!sUserManager.exists(userId)) { 4112 return; 4113 } 4114 4115 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4116 4117 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4118 true /* requireFullPermission */, true /* checkShell */, 4119 "updatePermissionFlags"); 4120 4121 // Only the system can change these flags and nothing else. 4122 if (getCallingUid() != Process.SYSTEM_UID) { 4123 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4124 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4125 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4126 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4127 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4128 } 4129 4130 synchronized (mPackages) { 4131 final PackageParser.Package pkg = mPackages.get(packageName); 4132 if (pkg == null) { 4133 throw new IllegalArgumentException("Unknown package: " + packageName); 4134 } 4135 4136 final BasePermission bp = mSettings.mPermissions.get(name); 4137 if (bp == null) { 4138 throw new IllegalArgumentException("Unknown permission: " + name); 4139 } 4140 4141 SettingBase sb = (SettingBase) pkg.mExtras; 4142 if (sb == null) { 4143 throw new IllegalArgumentException("Unknown package: " + packageName); 4144 } 4145 4146 PermissionsState permissionsState = sb.getPermissionsState(); 4147 4148 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4149 4150 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4151 // Install and runtime permissions are stored in different places, 4152 // so figure out what permission changed and persist the change. 4153 if (permissionsState.getInstallPermissionState(name) != null) { 4154 scheduleWriteSettingsLocked(); 4155 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4156 || hadState) { 4157 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4158 } 4159 } 4160 } 4161 } 4162 4163 /** 4164 * Update the permission flags for all packages and runtime permissions of a user in order 4165 * to allow device or profile owner to remove POLICY_FIXED. 4166 */ 4167 @Override 4168 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4169 if (!sUserManager.exists(userId)) { 4170 return; 4171 } 4172 4173 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4174 4175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4176 true /* requireFullPermission */, true /* checkShell */, 4177 "updatePermissionFlagsForAllApps"); 4178 4179 // Only the system can change system fixed flags. 4180 if (getCallingUid() != Process.SYSTEM_UID) { 4181 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4182 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4183 } 4184 4185 synchronized (mPackages) { 4186 boolean changed = false; 4187 final int packageCount = mPackages.size(); 4188 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4189 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4190 SettingBase sb = (SettingBase) pkg.mExtras; 4191 if (sb == null) { 4192 continue; 4193 } 4194 PermissionsState permissionsState = sb.getPermissionsState(); 4195 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4196 userId, flagMask, flagValues); 4197 } 4198 if (changed) { 4199 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4200 } 4201 } 4202 } 4203 4204 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4205 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4206 != PackageManager.PERMISSION_GRANTED 4207 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4208 != PackageManager.PERMISSION_GRANTED) { 4209 throw new SecurityException(message + " requires " 4210 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4211 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4212 } 4213 } 4214 4215 @Override 4216 public boolean shouldShowRequestPermissionRationale(String permissionName, 4217 String packageName, int userId) { 4218 if (UserHandle.getCallingUserId() != userId) { 4219 mContext.enforceCallingPermission( 4220 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4221 "canShowRequestPermissionRationale for user " + userId); 4222 } 4223 4224 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4225 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4226 return false; 4227 } 4228 4229 if (checkPermission(permissionName, packageName, userId) 4230 == PackageManager.PERMISSION_GRANTED) { 4231 return false; 4232 } 4233 4234 final int flags; 4235 4236 final long identity = Binder.clearCallingIdentity(); 4237 try { 4238 flags = getPermissionFlags(permissionName, 4239 packageName, userId); 4240 } finally { 4241 Binder.restoreCallingIdentity(identity); 4242 } 4243 4244 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4245 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4246 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4247 4248 if ((flags & fixedFlags) != 0) { 4249 return false; 4250 } 4251 4252 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4253 } 4254 4255 @Override 4256 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4257 mContext.enforceCallingOrSelfPermission( 4258 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4259 "addOnPermissionsChangeListener"); 4260 4261 synchronized (mPackages) { 4262 mOnPermissionChangeListeners.addListenerLocked(listener); 4263 } 4264 } 4265 4266 @Override 4267 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4268 synchronized (mPackages) { 4269 mOnPermissionChangeListeners.removeListenerLocked(listener); 4270 } 4271 } 4272 4273 @Override 4274 public boolean isProtectedBroadcast(String actionName) { 4275 synchronized (mPackages) { 4276 if (mProtectedBroadcasts.contains(actionName)) { 4277 return true; 4278 } else if (actionName != null) { 4279 // TODO: remove these terrible hacks 4280 if (actionName.startsWith("android.net.netmon.lingerExpired") 4281 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4282 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4283 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4284 return true; 4285 } 4286 } 4287 } 4288 return false; 4289 } 4290 4291 @Override 4292 public int checkSignatures(String pkg1, String pkg2) { 4293 synchronized (mPackages) { 4294 final PackageParser.Package p1 = mPackages.get(pkg1); 4295 final PackageParser.Package p2 = mPackages.get(pkg2); 4296 if (p1 == null || p1.mExtras == null 4297 || p2 == null || p2.mExtras == null) { 4298 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4299 } 4300 return compareSignatures(p1.mSignatures, p2.mSignatures); 4301 } 4302 } 4303 4304 @Override 4305 public int checkUidSignatures(int uid1, int uid2) { 4306 // Map to base uids. 4307 uid1 = UserHandle.getAppId(uid1); 4308 uid2 = UserHandle.getAppId(uid2); 4309 // reader 4310 synchronized (mPackages) { 4311 Signature[] s1; 4312 Signature[] s2; 4313 Object obj = mSettings.getUserIdLPr(uid1); 4314 if (obj != null) { 4315 if (obj instanceof SharedUserSetting) { 4316 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4317 } else if (obj instanceof PackageSetting) { 4318 s1 = ((PackageSetting)obj).signatures.mSignatures; 4319 } else { 4320 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4321 } 4322 } else { 4323 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4324 } 4325 obj = mSettings.getUserIdLPr(uid2); 4326 if (obj != null) { 4327 if (obj instanceof SharedUserSetting) { 4328 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4329 } else if (obj instanceof PackageSetting) { 4330 s2 = ((PackageSetting)obj).signatures.mSignatures; 4331 } else { 4332 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4333 } 4334 } else { 4335 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4336 } 4337 return compareSignatures(s1, s2); 4338 } 4339 } 4340 4341 private void killUid(int appId, int userId, String reason) { 4342 final long identity = Binder.clearCallingIdentity(); 4343 try { 4344 IActivityManager am = ActivityManagerNative.getDefault(); 4345 if (am != null) { 4346 try { 4347 am.killUid(appId, userId, reason); 4348 } catch (RemoteException e) { 4349 /* ignore - same process */ 4350 } 4351 } 4352 } finally { 4353 Binder.restoreCallingIdentity(identity); 4354 } 4355 } 4356 4357 /** 4358 * Compares two sets of signatures. Returns: 4359 * <br /> 4360 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4361 * <br /> 4362 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4363 * <br /> 4364 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4365 * <br /> 4366 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4367 * <br /> 4368 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4369 */ 4370 static int compareSignatures(Signature[] s1, Signature[] s2) { 4371 if (s1 == null) { 4372 return s2 == null 4373 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4374 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4375 } 4376 4377 if (s2 == null) { 4378 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4379 } 4380 4381 if (s1.length != s2.length) { 4382 return PackageManager.SIGNATURE_NO_MATCH; 4383 } 4384 4385 // Since both signature sets are of size 1, we can compare without HashSets. 4386 if (s1.length == 1) { 4387 return s1[0].equals(s2[0]) ? 4388 PackageManager.SIGNATURE_MATCH : 4389 PackageManager.SIGNATURE_NO_MATCH; 4390 } 4391 4392 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4393 for (Signature sig : s1) { 4394 set1.add(sig); 4395 } 4396 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4397 for (Signature sig : s2) { 4398 set2.add(sig); 4399 } 4400 // Make sure s2 contains all signatures in s1. 4401 if (set1.equals(set2)) { 4402 return PackageManager.SIGNATURE_MATCH; 4403 } 4404 return PackageManager.SIGNATURE_NO_MATCH; 4405 } 4406 4407 /** 4408 * If the database version for this type of package (internal storage or 4409 * external storage) is less than the version where package signatures 4410 * were updated, return true. 4411 */ 4412 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4413 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4414 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4415 } 4416 4417 /** 4418 * Used for backward compatibility to make sure any packages with 4419 * certificate chains get upgraded to the new style. {@code existingSigs} 4420 * will be in the old format (since they were stored on disk from before the 4421 * system upgrade) and {@code scannedSigs} will be in the newer format. 4422 */ 4423 private int compareSignaturesCompat(PackageSignatures existingSigs, 4424 PackageParser.Package scannedPkg) { 4425 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4426 return PackageManager.SIGNATURE_NO_MATCH; 4427 } 4428 4429 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4430 for (Signature sig : existingSigs.mSignatures) { 4431 existingSet.add(sig); 4432 } 4433 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4434 for (Signature sig : scannedPkg.mSignatures) { 4435 try { 4436 Signature[] chainSignatures = sig.getChainSignatures(); 4437 for (Signature chainSig : chainSignatures) { 4438 scannedCompatSet.add(chainSig); 4439 } 4440 } catch (CertificateEncodingException e) { 4441 scannedCompatSet.add(sig); 4442 } 4443 } 4444 /* 4445 * Make sure the expanded scanned set contains all signatures in the 4446 * existing one. 4447 */ 4448 if (scannedCompatSet.equals(existingSet)) { 4449 // Migrate the old signatures to the new scheme. 4450 existingSigs.assignSignatures(scannedPkg.mSignatures); 4451 // The new KeySets will be re-added later in the scanning process. 4452 synchronized (mPackages) { 4453 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4454 } 4455 return PackageManager.SIGNATURE_MATCH; 4456 } 4457 return PackageManager.SIGNATURE_NO_MATCH; 4458 } 4459 4460 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4461 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4462 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4463 } 4464 4465 private int compareSignaturesRecover(PackageSignatures existingSigs, 4466 PackageParser.Package scannedPkg) { 4467 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4468 return PackageManager.SIGNATURE_NO_MATCH; 4469 } 4470 4471 String msg = null; 4472 try { 4473 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4474 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4475 + scannedPkg.packageName); 4476 return PackageManager.SIGNATURE_MATCH; 4477 } 4478 } catch (CertificateException e) { 4479 msg = e.getMessage(); 4480 } 4481 4482 logCriticalInfo(Log.INFO, 4483 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4484 return PackageManager.SIGNATURE_NO_MATCH; 4485 } 4486 4487 @Override 4488 public List<String> getAllPackages() { 4489 synchronized (mPackages) { 4490 return new ArrayList<String>(mPackages.keySet()); 4491 } 4492 } 4493 4494 @Override 4495 public String[] getPackagesForUid(int uid) { 4496 uid = UserHandle.getAppId(uid); 4497 // reader 4498 synchronized (mPackages) { 4499 Object obj = mSettings.getUserIdLPr(uid); 4500 if (obj instanceof SharedUserSetting) { 4501 final SharedUserSetting sus = (SharedUserSetting) obj; 4502 final int N = sus.packages.size(); 4503 final String[] res = new String[N]; 4504 final Iterator<PackageSetting> it = sus.packages.iterator(); 4505 int i = 0; 4506 while (it.hasNext()) { 4507 res[i++] = it.next().name; 4508 } 4509 return res; 4510 } else if (obj instanceof PackageSetting) { 4511 final PackageSetting ps = (PackageSetting) obj; 4512 return new String[] { ps.name }; 4513 } 4514 } 4515 return null; 4516 } 4517 4518 @Override 4519 public String getNameForUid(int uid) { 4520 // reader 4521 synchronized (mPackages) { 4522 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4523 if (obj instanceof SharedUserSetting) { 4524 final SharedUserSetting sus = (SharedUserSetting) obj; 4525 return sus.name + ":" + sus.userId; 4526 } else if (obj instanceof PackageSetting) { 4527 final PackageSetting ps = (PackageSetting) obj; 4528 return ps.name; 4529 } 4530 } 4531 return null; 4532 } 4533 4534 @Override 4535 public int getUidForSharedUser(String sharedUserName) { 4536 if(sharedUserName == null) { 4537 return -1; 4538 } 4539 // reader 4540 synchronized (mPackages) { 4541 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4542 if (suid == null) { 4543 return -1; 4544 } 4545 return suid.userId; 4546 } 4547 } 4548 4549 @Override 4550 public int getFlagsForUid(int uid) { 4551 synchronized (mPackages) { 4552 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4553 if (obj instanceof SharedUserSetting) { 4554 final SharedUserSetting sus = (SharedUserSetting) obj; 4555 return sus.pkgFlags; 4556 } else if (obj instanceof PackageSetting) { 4557 final PackageSetting ps = (PackageSetting) obj; 4558 return ps.pkgFlags; 4559 } 4560 } 4561 return 0; 4562 } 4563 4564 @Override 4565 public int getPrivateFlagsForUid(int uid) { 4566 synchronized (mPackages) { 4567 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4568 if (obj instanceof SharedUserSetting) { 4569 final SharedUserSetting sus = (SharedUserSetting) obj; 4570 return sus.pkgPrivateFlags; 4571 } else if (obj instanceof PackageSetting) { 4572 final PackageSetting ps = (PackageSetting) obj; 4573 return ps.pkgPrivateFlags; 4574 } 4575 } 4576 return 0; 4577 } 4578 4579 @Override 4580 public boolean isUidPrivileged(int uid) { 4581 uid = UserHandle.getAppId(uid); 4582 // reader 4583 synchronized (mPackages) { 4584 Object obj = mSettings.getUserIdLPr(uid); 4585 if (obj instanceof SharedUserSetting) { 4586 final SharedUserSetting sus = (SharedUserSetting) obj; 4587 final Iterator<PackageSetting> it = sus.packages.iterator(); 4588 while (it.hasNext()) { 4589 if (it.next().isPrivileged()) { 4590 return true; 4591 } 4592 } 4593 } else if (obj instanceof PackageSetting) { 4594 final PackageSetting ps = (PackageSetting) obj; 4595 return ps.isPrivileged(); 4596 } 4597 } 4598 return false; 4599 } 4600 4601 @Override 4602 public String[] getAppOpPermissionPackages(String permissionName) { 4603 synchronized (mPackages) { 4604 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4605 if (pkgs == null) { 4606 return null; 4607 } 4608 return pkgs.toArray(new String[pkgs.size()]); 4609 } 4610 } 4611 4612 @Override 4613 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4614 int flags, int userId) { 4615 if (!sUserManager.exists(userId)) return null; 4616 flags = updateFlagsForResolve(flags, userId, intent); 4617 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4618 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4619 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4620 userId); 4621 final ResolveInfo bestChoice = 4622 chooseBestActivity(intent, resolvedType, flags, query, userId); 4623 4624 if (isEphemeralAllowed(intent, query, userId)) { 4625 final EphemeralResolveInfo ai = 4626 getEphemeralResolveInfo(intent, resolvedType, userId); 4627 if (ai != null) { 4628 if (DEBUG_EPHEMERAL) { 4629 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4630 } 4631 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4632 bestChoice.ephemeralResolveInfo = ai; 4633 } 4634 } 4635 return bestChoice; 4636 } 4637 4638 @Override 4639 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4640 IntentFilter filter, int match, ComponentName activity) { 4641 final int userId = UserHandle.getCallingUserId(); 4642 if (DEBUG_PREFERRED) { 4643 Log.v(TAG, "setLastChosenActivity intent=" + intent 4644 + " resolvedType=" + resolvedType 4645 + " flags=" + flags 4646 + " filter=" + filter 4647 + " match=" + match 4648 + " activity=" + activity); 4649 filter.dump(new PrintStreamPrinter(System.out), " "); 4650 } 4651 intent.setComponent(null); 4652 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4653 userId); 4654 // Find any earlier preferred or last chosen entries and nuke them 4655 findPreferredActivity(intent, resolvedType, 4656 flags, query, 0, false, true, false, userId); 4657 // Add the new activity as the last chosen for this filter 4658 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4659 "Setting last chosen"); 4660 } 4661 4662 @Override 4663 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4664 final int userId = UserHandle.getCallingUserId(); 4665 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4666 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4667 userId); 4668 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4669 false, false, false, userId); 4670 } 4671 4672 4673 private boolean isEphemeralAllowed( 4674 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4675 // Short circuit and return early if possible. 4676 if (DISABLE_EPHEMERAL_APPS) { 4677 return false; 4678 } 4679 final int callingUser = UserHandle.getCallingUserId(); 4680 if (callingUser != UserHandle.USER_SYSTEM) { 4681 return false; 4682 } 4683 if (mEphemeralResolverConnection == null) { 4684 return false; 4685 } 4686 if (intent.getComponent() != null) { 4687 return false; 4688 } 4689 if (intent.getPackage() != null) { 4690 return false; 4691 } 4692 final boolean isWebUri = hasWebURI(intent); 4693 if (!isWebUri) { 4694 return false; 4695 } 4696 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4697 synchronized (mPackages) { 4698 final int count = resolvedActivites.size(); 4699 for (int n = 0; n < count; n++) { 4700 ResolveInfo info = resolvedActivites.get(n); 4701 String packageName = info.activityInfo.packageName; 4702 PackageSetting ps = mSettings.mPackages.get(packageName); 4703 if (ps != null) { 4704 // Try to get the status from User settings first 4705 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4706 int status = (int) (packedStatus >> 32); 4707 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4708 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4709 if (DEBUG_EPHEMERAL) { 4710 Slog.v(TAG, "DENY ephemeral apps;" 4711 + " pkg: " + packageName + ", status: " + status); 4712 } 4713 return false; 4714 } 4715 } 4716 } 4717 } 4718 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4719 return true; 4720 } 4721 4722 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4723 int userId) { 4724 MessageDigest digest = null; 4725 try { 4726 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4727 } catch (NoSuchAlgorithmException e) { 4728 // If we can't create a digest, ignore ephemeral apps. 4729 return null; 4730 } 4731 4732 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4733 final byte[] digestBytes = digest.digest(hostBytes); 4734 int shaPrefix = 4735 digestBytes[0] << 24 4736 | digestBytes[1] << 16 4737 | digestBytes[2] << 8 4738 | digestBytes[3] << 0; 4739 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4740 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4741 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4742 // No hash prefix match; there are no ephemeral apps for this domain. 4743 return null; 4744 } 4745 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4746 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4747 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4748 continue; 4749 } 4750 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4751 // No filters; this should never happen. 4752 if (filters.isEmpty()) { 4753 continue; 4754 } 4755 // We have a domain match; resolve the filters to see if anything matches. 4756 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4757 for (int j = filters.size() - 1; j >= 0; --j) { 4758 final EphemeralResolveIntentInfo intentInfo = 4759 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4760 ephemeralResolver.addFilter(intentInfo); 4761 } 4762 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4763 intent, resolvedType, false /*defaultOnly*/, userId); 4764 if (!matchedResolveInfoList.isEmpty()) { 4765 return matchedResolveInfoList.get(0); 4766 } 4767 } 4768 // Hash or filter mis-match; no ephemeral apps for this domain. 4769 return null; 4770 } 4771 4772 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4773 int flags, List<ResolveInfo> query, int userId) { 4774 if (query != null) { 4775 final int N = query.size(); 4776 if (N == 1) { 4777 return query.get(0); 4778 } else if (N > 1) { 4779 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4780 // If there is more than one activity with the same priority, 4781 // then let the user decide between them. 4782 ResolveInfo r0 = query.get(0); 4783 ResolveInfo r1 = query.get(1); 4784 if (DEBUG_INTENT_MATCHING || debug) { 4785 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4786 + r1.activityInfo.name + "=" + r1.priority); 4787 } 4788 // If the first activity has a higher priority, or a different 4789 // default, then it is always desirable to pick it. 4790 if (r0.priority != r1.priority 4791 || r0.preferredOrder != r1.preferredOrder 4792 || r0.isDefault != r1.isDefault) { 4793 return query.get(0); 4794 } 4795 // If we have saved a preference for a preferred activity for 4796 // this Intent, use that. 4797 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4798 flags, query, r0.priority, true, false, debug, userId); 4799 if (ri != null) { 4800 return ri; 4801 } 4802 ri = new ResolveInfo(mResolveInfo); 4803 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4804 ri.activityInfo.applicationInfo = new ApplicationInfo( 4805 ri.activityInfo.applicationInfo); 4806 if (userId != 0) { 4807 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4808 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4809 } 4810 // Make sure that the resolver is displayable in car mode 4811 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4812 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4813 return ri; 4814 } 4815 } 4816 return null; 4817 } 4818 4819 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4820 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4821 final int N = query.size(); 4822 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4823 .get(userId); 4824 // Get the list of persistent preferred activities that handle the intent 4825 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4826 List<PersistentPreferredActivity> pprefs = ppir != null 4827 ? ppir.queryIntent(intent, resolvedType, 4828 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4829 : null; 4830 if (pprefs != null && pprefs.size() > 0) { 4831 final int M = pprefs.size(); 4832 for (int i=0; i<M; i++) { 4833 final PersistentPreferredActivity ppa = pprefs.get(i); 4834 if (DEBUG_PREFERRED || debug) { 4835 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4836 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4837 + "\n component=" + ppa.mComponent); 4838 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4839 } 4840 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4841 flags | MATCH_DISABLED_COMPONENTS, userId); 4842 if (DEBUG_PREFERRED || debug) { 4843 Slog.v(TAG, "Found persistent preferred activity:"); 4844 if (ai != null) { 4845 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4846 } else { 4847 Slog.v(TAG, " null"); 4848 } 4849 } 4850 if (ai == null) { 4851 // This previously registered persistent preferred activity 4852 // component is no longer known. Ignore it and do NOT remove it. 4853 continue; 4854 } 4855 for (int j=0; j<N; j++) { 4856 final ResolveInfo ri = query.get(j); 4857 if (!ri.activityInfo.applicationInfo.packageName 4858 .equals(ai.applicationInfo.packageName)) { 4859 continue; 4860 } 4861 if (!ri.activityInfo.name.equals(ai.name)) { 4862 continue; 4863 } 4864 // Found a persistent preference that can handle the intent. 4865 if (DEBUG_PREFERRED || debug) { 4866 Slog.v(TAG, "Returning persistent preferred activity: " + 4867 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4868 } 4869 return ri; 4870 } 4871 } 4872 } 4873 return null; 4874 } 4875 4876 // TODO: handle preferred activities missing while user has amnesia 4877 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4878 List<ResolveInfo> query, int priority, boolean always, 4879 boolean removeMatches, boolean debug, int userId) { 4880 if (!sUserManager.exists(userId)) return null; 4881 flags = updateFlagsForResolve(flags, userId, intent); 4882 // writer 4883 synchronized (mPackages) { 4884 if (intent.getSelector() != null) { 4885 intent = intent.getSelector(); 4886 } 4887 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4888 4889 // Try to find a matching persistent preferred activity. 4890 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4891 debug, userId); 4892 4893 // If a persistent preferred activity matched, use it. 4894 if (pri != null) { 4895 return pri; 4896 } 4897 4898 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4899 // Get the list of preferred activities that handle the intent 4900 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4901 List<PreferredActivity> prefs = pir != null 4902 ? pir.queryIntent(intent, resolvedType, 4903 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4904 : null; 4905 if (prefs != null && prefs.size() > 0) { 4906 boolean changed = false; 4907 try { 4908 // First figure out how good the original match set is. 4909 // We will only allow preferred activities that came 4910 // from the same match quality. 4911 int match = 0; 4912 4913 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4914 4915 final int N = query.size(); 4916 for (int j=0; j<N; j++) { 4917 final ResolveInfo ri = query.get(j); 4918 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4919 + ": 0x" + Integer.toHexString(match)); 4920 if (ri.match > match) { 4921 match = ri.match; 4922 } 4923 } 4924 4925 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4926 + Integer.toHexString(match)); 4927 4928 match &= IntentFilter.MATCH_CATEGORY_MASK; 4929 final int M = prefs.size(); 4930 for (int i=0; i<M; i++) { 4931 final PreferredActivity pa = prefs.get(i); 4932 if (DEBUG_PREFERRED || debug) { 4933 Slog.v(TAG, "Checking PreferredActivity ds=" 4934 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4935 + "\n component=" + pa.mPref.mComponent); 4936 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4937 } 4938 if (pa.mPref.mMatch != match) { 4939 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4940 + Integer.toHexString(pa.mPref.mMatch)); 4941 continue; 4942 } 4943 // If it's not an "always" type preferred activity and that's what we're 4944 // looking for, skip it. 4945 if (always && !pa.mPref.mAlways) { 4946 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4947 continue; 4948 } 4949 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4950 flags | MATCH_DISABLED_COMPONENTS, userId); 4951 if (DEBUG_PREFERRED || debug) { 4952 Slog.v(TAG, "Found preferred activity:"); 4953 if (ai != null) { 4954 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4955 } else { 4956 Slog.v(TAG, " null"); 4957 } 4958 } 4959 if (ai == null) { 4960 // This previously registered preferred activity 4961 // component is no longer known. Most likely an update 4962 // to the app was installed and in the new version this 4963 // component no longer exists. Clean it up by removing 4964 // it from the preferred activities list, and skip it. 4965 Slog.w(TAG, "Removing dangling preferred activity: " 4966 + pa.mPref.mComponent); 4967 pir.removeFilter(pa); 4968 changed = true; 4969 continue; 4970 } 4971 for (int j=0; j<N; j++) { 4972 final ResolveInfo ri = query.get(j); 4973 if (!ri.activityInfo.applicationInfo.packageName 4974 .equals(ai.applicationInfo.packageName)) { 4975 continue; 4976 } 4977 if (!ri.activityInfo.name.equals(ai.name)) { 4978 continue; 4979 } 4980 4981 if (removeMatches) { 4982 pir.removeFilter(pa); 4983 changed = true; 4984 if (DEBUG_PREFERRED) { 4985 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4986 } 4987 break; 4988 } 4989 4990 // Okay we found a previously set preferred or last chosen app. 4991 // If the result set is different from when this 4992 // was created, we need to clear it and re-ask the 4993 // user their preference, if we're looking for an "always" type entry. 4994 if (always && !pa.mPref.sameSet(query)) { 4995 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4996 + intent + " type " + resolvedType); 4997 if (DEBUG_PREFERRED) { 4998 Slog.v(TAG, "Removing preferred activity since set changed " 4999 + pa.mPref.mComponent); 5000 } 5001 pir.removeFilter(pa); 5002 // Re-add the filter as a "last chosen" entry (!always) 5003 PreferredActivity lastChosen = new PreferredActivity( 5004 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5005 pir.addFilter(lastChosen); 5006 changed = true; 5007 return null; 5008 } 5009 5010 // Yay! Either the set matched or we're looking for the last chosen 5011 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5012 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5013 return ri; 5014 } 5015 } 5016 } finally { 5017 if (changed) { 5018 if (DEBUG_PREFERRED) { 5019 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5020 } 5021 scheduleWritePackageRestrictionsLocked(userId); 5022 } 5023 } 5024 } 5025 } 5026 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5027 return null; 5028 } 5029 5030 /* 5031 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5032 */ 5033 @Override 5034 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5035 int targetUserId) { 5036 mContext.enforceCallingOrSelfPermission( 5037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5038 List<CrossProfileIntentFilter> matches = 5039 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5040 if (matches != null) { 5041 int size = matches.size(); 5042 for (int i = 0; i < size; i++) { 5043 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5044 } 5045 } 5046 if (hasWebURI(intent)) { 5047 // cross-profile app linking works only towards the parent. 5048 final UserInfo parent = getProfileParent(sourceUserId); 5049 synchronized(mPackages) { 5050 int flags = updateFlagsForResolve(0, parent.id, intent); 5051 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5052 intent, resolvedType, flags, sourceUserId, parent.id); 5053 return xpDomainInfo != null; 5054 } 5055 } 5056 return false; 5057 } 5058 5059 private UserInfo getProfileParent(int userId) { 5060 final long identity = Binder.clearCallingIdentity(); 5061 try { 5062 return sUserManager.getProfileParent(userId); 5063 } finally { 5064 Binder.restoreCallingIdentity(identity); 5065 } 5066 } 5067 5068 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5069 String resolvedType, int userId) { 5070 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5071 if (resolver != null) { 5072 return resolver.queryIntent(intent, resolvedType, false, userId); 5073 } 5074 return null; 5075 } 5076 5077 @Override 5078 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5079 String resolvedType, int flags, int userId) { 5080 return new ParceledListSlice<>( 5081 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5082 } 5083 5084 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5085 String resolvedType, int flags, int userId) { 5086 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5087 flags = updateFlagsForResolve(flags, userId, intent); 5088 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5089 false /* requireFullPermission */, false /* checkShell */, 5090 "query intent activities"); 5091 ComponentName comp = intent.getComponent(); 5092 if (comp == null) { 5093 if (intent.getSelector() != null) { 5094 intent = intent.getSelector(); 5095 comp = intent.getComponent(); 5096 } 5097 } 5098 5099 if (comp != null) { 5100 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5101 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5102 if (ai != null) { 5103 final ResolveInfo ri = new ResolveInfo(); 5104 ri.activityInfo = ai; 5105 list.add(ri); 5106 } 5107 return list; 5108 } 5109 5110 // reader 5111 synchronized (mPackages) { 5112 final String pkgName = intent.getPackage(); 5113 if (pkgName == null) { 5114 List<CrossProfileIntentFilter> matchingFilters = 5115 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5116 // Check for results that need to skip the current profile. 5117 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5118 resolvedType, flags, userId); 5119 if (xpResolveInfo != null) { 5120 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5121 result.add(xpResolveInfo); 5122 return filterIfNotSystemUser(result, userId); 5123 } 5124 5125 // Check for results in the current profile. 5126 List<ResolveInfo> result = mActivities.queryIntent( 5127 intent, resolvedType, flags, userId); 5128 result = filterIfNotSystemUser(result, userId); 5129 5130 // Check for cross profile results. 5131 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5132 xpResolveInfo = queryCrossProfileIntents( 5133 matchingFilters, intent, resolvedType, flags, userId, 5134 hasNonNegativePriorityResult); 5135 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5136 boolean isVisibleToUser = filterIfNotSystemUser( 5137 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5138 if (isVisibleToUser) { 5139 result.add(xpResolveInfo); 5140 Collections.sort(result, mResolvePrioritySorter); 5141 } 5142 } 5143 if (hasWebURI(intent)) { 5144 CrossProfileDomainInfo xpDomainInfo = null; 5145 final UserInfo parent = getProfileParent(userId); 5146 if (parent != null) { 5147 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5148 flags, userId, parent.id); 5149 } 5150 if (xpDomainInfo != null) { 5151 if (xpResolveInfo != null) { 5152 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5153 // in the result. 5154 result.remove(xpResolveInfo); 5155 } 5156 if (result.size() == 0) { 5157 result.add(xpDomainInfo.resolveInfo); 5158 return result; 5159 } 5160 } else if (result.size() <= 1) { 5161 return result; 5162 } 5163 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5164 xpDomainInfo, userId); 5165 Collections.sort(result, mResolvePrioritySorter); 5166 } 5167 return result; 5168 } 5169 final PackageParser.Package pkg = mPackages.get(pkgName); 5170 if (pkg != null) { 5171 return filterIfNotSystemUser( 5172 mActivities.queryIntentForPackage( 5173 intent, resolvedType, flags, pkg.activities, userId), 5174 userId); 5175 } 5176 return new ArrayList<ResolveInfo>(); 5177 } 5178 } 5179 5180 private static class CrossProfileDomainInfo { 5181 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5182 ResolveInfo resolveInfo; 5183 /* Best domain verification status of the activities found in the other profile */ 5184 int bestDomainVerificationStatus; 5185 } 5186 5187 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5188 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5189 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5190 sourceUserId)) { 5191 return null; 5192 } 5193 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5194 resolvedType, flags, parentUserId); 5195 5196 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5197 return null; 5198 } 5199 CrossProfileDomainInfo result = null; 5200 int size = resultTargetUser.size(); 5201 for (int i = 0; i < size; i++) { 5202 ResolveInfo riTargetUser = resultTargetUser.get(i); 5203 // Intent filter verification is only for filters that specify a host. So don't return 5204 // those that handle all web uris. 5205 if (riTargetUser.handleAllWebDataURI) { 5206 continue; 5207 } 5208 String packageName = riTargetUser.activityInfo.packageName; 5209 PackageSetting ps = mSettings.mPackages.get(packageName); 5210 if (ps == null) { 5211 continue; 5212 } 5213 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5214 int status = (int)(verificationState >> 32); 5215 if (result == null) { 5216 result = new CrossProfileDomainInfo(); 5217 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5218 sourceUserId, parentUserId); 5219 result.bestDomainVerificationStatus = status; 5220 } else { 5221 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5222 result.bestDomainVerificationStatus); 5223 } 5224 } 5225 // Don't consider matches with status NEVER across profiles. 5226 if (result != null && result.bestDomainVerificationStatus 5227 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5228 return null; 5229 } 5230 return result; 5231 } 5232 5233 /** 5234 * Verification statuses are ordered from the worse to the best, except for 5235 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5236 */ 5237 private int bestDomainVerificationStatus(int status1, int status2) { 5238 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5239 return status2; 5240 } 5241 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5242 return status1; 5243 } 5244 return (int) MathUtils.max(status1, status2); 5245 } 5246 5247 private boolean isUserEnabled(int userId) { 5248 long callingId = Binder.clearCallingIdentity(); 5249 try { 5250 UserInfo userInfo = sUserManager.getUserInfo(userId); 5251 return userInfo != null && userInfo.isEnabled(); 5252 } finally { 5253 Binder.restoreCallingIdentity(callingId); 5254 } 5255 } 5256 5257 /** 5258 * Filter out activities with systemUserOnly flag set, when current user is not System. 5259 * 5260 * @return filtered list 5261 */ 5262 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5263 if (userId == UserHandle.USER_SYSTEM) { 5264 return resolveInfos; 5265 } 5266 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5267 ResolveInfo info = resolveInfos.get(i); 5268 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5269 resolveInfos.remove(i); 5270 } 5271 } 5272 return resolveInfos; 5273 } 5274 5275 /** 5276 * @param resolveInfos list of resolve infos in descending priority order 5277 * @return if the list contains a resolve info with non-negative priority 5278 */ 5279 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5280 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5281 } 5282 5283 private static boolean hasWebURI(Intent intent) { 5284 if (intent.getData() == null) { 5285 return false; 5286 } 5287 final String scheme = intent.getScheme(); 5288 if (TextUtils.isEmpty(scheme)) { 5289 return false; 5290 } 5291 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5292 } 5293 5294 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5295 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5296 int userId) { 5297 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5298 5299 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5300 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5301 candidates.size()); 5302 } 5303 5304 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5305 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5306 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5307 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5308 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5309 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5310 5311 synchronized (mPackages) { 5312 final int count = candidates.size(); 5313 // First, try to use linked apps. Partition the candidates into four lists: 5314 // one for the final results, one for the "do not use ever", one for "undefined status" 5315 // and finally one for "browser app type". 5316 for (int n=0; n<count; n++) { 5317 ResolveInfo info = candidates.get(n); 5318 String packageName = info.activityInfo.packageName; 5319 PackageSetting ps = mSettings.mPackages.get(packageName); 5320 if (ps != null) { 5321 // Add to the special match all list (Browser use case) 5322 if (info.handleAllWebDataURI) { 5323 matchAllList.add(info); 5324 continue; 5325 } 5326 // Try to get the status from User settings first 5327 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5328 int status = (int)(packedStatus >> 32); 5329 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5330 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5331 if (DEBUG_DOMAIN_VERIFICATION) { 5332 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5333 + " : linkgen=" + linkGeneration); 5334 } 5335 // Use link-enabled generation as preferredOrder, i.e. 5336 // prefer newly-enabled over earlier-enabled. 5337 info.preferredOrder = linkGeneration; 5338 alwaysList.add(info); 5339 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5340 if (DEBUG_DOMAIN_VERIFICATION) { 5341 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5342 } 5343 neverList.add(info); 5344 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5345 if (DEBUG_DOMAIN_VERIFICATION) { 5346 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5347 } 5348 alwaysAskList.add(info); 5349 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5350 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5351 if (DEBUG_DOMAIN_VERIFICATION) { 5352 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5353 } 5354 undefinedList.add(info); 5355 } 5356 } 5357 } 5358 5359 // We'll want to include browser possibilities in a few cases 5360 boolean includeBrowser = false; 5361 5362 // First try to add the "always" resolution(s) for the current user, if any 5363 if (alwaysList.size() > 0) { 5364 result.addAll(alwaysList); 5365 } else { 5366 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5367 result.addAll(undefinedList); 5368 // Maybe add one for the other profile. 5369 if (xpDomainInfo != null && ( 5370 xpDomainInfo.bestDomainVerificationStatus 5371 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5372 result.add(xpDomainInfo.resolveInfo); 5373 } 5374 includeBrowser = true; 5375 } 5376 5377 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5378 // If there were 'always' entries their preferred order has been set, so we also 5379 // back that off to make the alternatives equivalent 5380 if (alwaysAskList.size() > 0) { 5381 for (ResolveInfo i : result) { 5382 i.preferredOrder = 0; 5383 } 5384 result.addAll(alwaysAskList); 5385 includeBrowser = true; 5386 } 5387 5388 if (includeBrowser) { 5389 // Also add browsers (all of them or only the default one) 5390 if (DEBUG_DOMAIN_VERIFICATION) { 5391 Slog.v(TAG, " ...including browsers in candidate set"); 5392 } 5393 if ((matchFlags & MATCH_ALL) != 0) { 5394 result.addAll(matchAllList); 5395 } else { 5396 // Browser/generic handling case. If there's a default browser, go straight 5397 // to that (but only if there is no other higher-priority match). 5398 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5399 int maxMatchPrio = 0; 5400 ResolveInfo defaultBrowserMatch = null; 5401 final int numCandidates = matchAllList.size(); 5402 for (int n = 0; n < numCandidates; n++) { 5403 ResolveInfo info = matchAllList.get(n); 5404 // track the highest overall match priority... 5405 if (info.priority > maxMatchPrio) { 5406 maxMatchPrio = info.priority; 5407 } 5408 // ...and the highest-priority default browser match 5409 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5410 if (defaultBrowserMatch == null 5411 || (defaultBrowserMatch.priority < info.priority)) { 5412 if (debug) { 5413 Slog.v(TAG, "Considering default browser match " + info); 5414 } 5415 defaultBrowserMatch = info; 5416 } 5417 } 5418 } 5419 if (defaultBrowserMatch != null 5420 && defaultBrowserMatch.priority >= maxMatchPrio 5421 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5422 { 5423 if (debug) { 5424 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5425 } 5426 result.add(defaultBrowserMatch); 5427 } else { 5428 result.addAll(matchAllList); 5429 } 5430 } 5431 5432 // If there is nothing selected, add all candidates and remove the ones that the user 5433 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5434 if (result.size() == 0) { 5435 result.addAll(candidates); 5436 result.removeAll(neverList); 5437 } 5438 } 5439 } 5440 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5441 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5442 result.size()); 5443 for (ResolveInfo info : result) { 5444 Slog.v(TAG, " + " + info.activityInfo); 5445 } 5446 } 5447 return result; 5448 } 5449 5450 // Returns a packed value as a long: 5451 // 5452 // high 'int'-sized word: link status: undefined/ask/never/always. 5453 // low 'int'-sized word: relative priority among 'always' results. 5454 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5455 long result = ps.getDomainVerificationStatusForUser(userId); 5456 // if none available, get the master status 5457 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5458 if (ps.getIntentFilterVerificationInfo() != null) { 5459 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5460 } 5461 } 5462 return result; 5463 } 5464 5465 private ResolveInfo querySkipCurrentProfileIntents( 5466 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5467 int flags, int sourceUserId) { 5468 if (matchingFilters != null) { 5469 int size = matchingFilters.size(); 5470 for (int i = 0; i < size; i ++) { 5471 CrossProfileIntentFilter filter = matchingFilters.get(i); 5472 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5473 // Checking if there are activities in the target user that can handle the 5474 // intent. 5475 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5476 resolvedType, flags, sourceUserId); 5477 if (resolveInfo != null) { 5478 return resolveInfo; 5479 } 5480 } 5481 } 5482 } 5483 return null; 5484 } 5485 5486 // Return matching ResolveInfo in target user if any. 5487 private ResolveInfo queryCrossProfileIntents( 5488 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5489 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5490 if (matchingFilters != null) { 5491 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5492 // match the same intent. For performance reasons, it is better not to 5493 // run queryIntent twice for the same userId 5494 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5495 int size = matchingFilters.size(); 5496 for (int i = 0; i < size; i++) { 5497 CrossProfileIntentFilter filter = matchingFilters.get(i); 5498 int targetUserId = filter.getTargetUserId(); 5499 boolean skipCurrentProfile = 5500 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5501 boolean skipCurrentProfileIfNoMatchFound = 5502 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5503 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5504 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5505 // Checking if there are activities in the target user that can handle the 5506 // intent. 5507 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5508 resolvedType, flags, sourceUserId); 5509 if (resolveInfo != null) return resolveInfo; 5510 alreadyTriedUserIds.put(targetUserId, true); 5511 } 5512 } 5513 } 5514 return null; 5515 } 5516 5517 /** 5518 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5519 * will forward the intent to the filter's target user. 5520 * Otherwise, returns null. 5521 */ 5522 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5523 String resolvedType, int flags, int sourceUserId) { 5524 int targetUserId = filter.getTargetUserId(); 5525 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5526 resolvedType, flags, targetUserId); 5527 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5528 // If all the matches in the target profile are suspended, return null. 5529 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5530 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5531 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5532 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5533 targetUserId); 5534 } 5535 } 5536 } 5537 return null; 5538 } 5539 5540 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5541 int sourceUserId, int targetUserId) { 5542 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5543 long ident = Binder.clearCallingIdentity(); 5544 boolean targetIsProfile; 5545 try { 5546 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5547 } finally { 5548 Binder.restoreCallingIdentity(ident); 5549 } 5550 String className; 5551 if (targetIsProfile) { 5552 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5553 } else { 5554 className = FORWARD_INTENT_TO_PARENT; 5555 } 5556 ComponentName forwardingActivityComponentName = new ComponentName( 5557 mAndroidApplication.packageName, className); 5558 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5559 sourceUserId); 5560 if (!targetIsProfile) { 5561 forwardingActivityInfo.showUserIcon = targetUserId; 5562 forwardingResolveInfo.noResourceId = true; 5563 } 5564 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5565 forwardingResolveInfo.priority = 0; 5566 forwardingResolveInfo.preferredOrder = 0; 5567 forwardingResolveInfo.match = 0; 5568 forwardingResolveInfo.isDefault = true; 5569 forwardingResolveInfo.filter = filter; 5570 forwardingResolveInfo.targetUserId = targetUserId; 5571 return forwardingResolveInfo; 5572 } 5573 5574 @Override 5575 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5576 Intent[] specifics, String[] specificTypes, Intent intent, 5577 String resolvedType, int flags, int userId) { 5578 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5579 specificTypes, intent, resolvedType, flags, userId)); 5580 } 5581 5582 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5583 Intent[] specifics, String[] specificTypes, Intent intent, 5584 String resolvedType, int flags, int userId) { 5585 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5586 flags = updateFlagsForResolve(flags, userId, intent); 5587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5588 false /* requireFullPermission */, false /* checkShell */, 5589 "query intent activity options"); 5590 final String resultsAction = intent.getAction(); 5591 5592 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5593 | PackageManager.GET_RESOLVED_FILTER, userId); 5594 5595 if (DEBUG_INTENT_MATCHING) { 5596 Log.v(TAG, "Query " + intent + ": " + results); 5597 } 5598 5599 int specificsPos = 0; 5600 int N; 5601 5602 // todo: note that the algorithm used here is O(N^2). This 5603 // isn't a problem in our current environment, but if we start running 5604 // into situations where we have more than 5 or 10 matches then this 5605 // should probably be changed to something smarter... 5606 5607 // First we go through and resolve each of the specific items 5608 // that were supplied, taking care of removing any corresponding 5609 // duplicate items in the generic resolve list. 5610 if (specifics != null) { 5611 for (int i=0; i<specifics.length; i++) { 5612 final Intent sintent = specifics[i]; 5613 if (sintent == null) { 5614 continue; 5615 } 5616 5617 if (DEBUG_INTENT_MATCHING) { 5618 Log.v(TAG, "Specific #" + i + ": " + sintent); 5619 } 5620 5621 String action = sintent.getAction(); 5622 if (resultsAction != null && resultsAction.equals(action)) { 5623 // If this action was explicitly requested, then don't 5624 // remove things that have it. 5625 action = null; 5626 } 5627 5628 ResolveInfo ri = null; 5629 ActivityInfo ai = null; 5630 5631 ComponentName comp = sintent.getComponent(); 5632 if (comp == null) { 5633 ri = resolveIntent( 5634 sintent, 5635 specificTypes != null ? specificTypes[i] : null, 5636 flags, userId); 5637 if (ri == null) { 5638 continue; 5639 } 5640 if (ri == mResolveInfo) { 5641 // ACK! Must do something better with this. 5642 } 5643 ai = ri.activityInfo; 5644 comp = new ComponentName(ai.applicationInfo.packageName, 5645 ai.name); 5646 } else { 5647 ai = getActivityInfo(comp, flags, userId); 5648 if (ai == null) { 5649 continue; 5650 } 5651 } 5652 5653 // Look for any generic query activities that are duplicates 5654 // of this specific one, and remove them from the results. 5655 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5656 N = results.size(); 5657 int j; 5658 for (j=specificsPos; j<N; j++) { 5659 ResolveInfo sri = results.get(j); 5660 if ((sri.activityInfo.name.equals(comp.getClassName()) 5661 && sri.activityInfo.applicationInfo.packageName.equals( 5662 comp.getPackageName())) 5663 || (action != null && sri.filter.matchAction(action))) { 5664 results.remove(j); 5665 if (DEBUG_INTENT_MATCHING) Log.v( 5666 TAG, "Removing duplicate item from " + j 5667 + " due to specific " + specificsPos); 5668 if (ri == null) { 5669 ri = sri; 5670 } 5671 j--; 5672 N--; 5673 } 5674 } 5675 5676 // Add this specific item to its proper place. 5677 if (ri == null) { 5678 ri = new ResolveInfo(); 5679 ri.activityInfo = ai; 5680 } 5681 results.add(specificsPos, ri); 5682 ri.specificIndex = i; 5683 specificsPos++; 5684 } 5685 } 5686 5687 // Now we go through the remaining generic results and remove any 5688 // duplicate actions that are found here. 5689 N = results.size(); 5690 for (int i=specificsPos; i<N-1; i++) { 5691 final ResolveInfo rii = results.get(i); 5692 if (rii.filter == null) { 5693 continue; 5694 } 5695 5696 // Iterate over all of the actions of this result's intent 5697 // filter... typically this should be just one. 5698 final Iterator<String> it = rii.filter.actionsIterator(); 5699 if (it == null) { 5700 continue; 5701 } 5702 while (it.hasNext()) { 5703 final String action = it.next(); 5704 if (resultsAction != null && resultsAction.equals(action)) { 5705 // If this action was explicitly requested, then don't 5706 // remove things that have it. 5707 continue; 5708 } 5709 for (int j=i+1; j<N; j++) { 5710 final ResolveInfo rij = results.get(j); 5711 if (rij.filter != null && rij.filter.hasAction(action)) { 5712 results.remove(j); 5713 if (DEBUG_INTENT_MATCHING) Log.v( 5714 TAG, "Removing duplicate item from " + j 5715 + " due to action " + action + " at " + i); 5716 j--; 5717 N--; 5718 } 5719 } 5720 } 5721 5722 // If the caller didn't request filter information, drop it now 5723 // so we don't have to marshall/unmarshall it. 5724 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5725 rii.filter = null; 5726 } 5727 } 5728 5729 // Filter out the caller activity if so requested. 5730 if (caller != null) { 5731 N = results.size(); 5732 for (int i=0; i<N; i++) { 5733 ActivityInfo ainfo = results.get(i).activityInfo; 5734 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5735 && caller.getClassName().equals(ainfo.name)) { 5736 results.remove(i); 5737 break; 5738 } 5739 } 5740 } 5741 5742 // If the caller didn't request filter information, 5743 // drop them now so we don't have to 5744 // marshall/unmarshall it. 5745 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5746 N = results.size(); 5747 for (int i=0; i<N; i++) { 5748 results.get(i).filter = null; 5749 } 5750 } 5751 5752 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5753 return results; 5754 } 5755 5756 @Override 5757 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5758 String resolvedType, int flags, int userId) { 5759 return new ParceledListSlice<>( 5760 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5761 } 5762 5763 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5764 String resolvedType, int flags, int userId) { 5765 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5766 flags = updateFlagsForResolve(flags, userId, intent); 5767 ComponentName comp = intent.getComponent(); 5768 if (comp == null) { 5769 if (intent.getSelector() != null) { 5770 intent = intent.getSelector(); 5771 comp = intent.getComponent(); 5772 } 5773 } 5774 if (comp != null) { 5775 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5776 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5777 if (ai != null) { 5778 ResolveInfo ri = new ResolveInfo(); 5779 ri.activityInfo = ai; 5780 list.add(ri); 5781 } 5782 return list; 5783 } 5784 5785 // reader 5786 synchronized (mPackages) { 5787 String pkgName = intent.getPackage(); 5788 if (pkgName == null) { 5789 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5790 } 5791 final PackageParser.Package pkg = mPackages.get(pkgName); 5792 if (pkg != null) { 5793 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5794 userId); 5795 } 5796 return Collections.emptyList(); 5797 } 5798 } 5799 5800 @Override 5801 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5802 if (!sUserManager.exists(userId)) return null; 5803 flags = updateFlagsForResolve(flags, userId, intent); 5804 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5805 if (query != null) { 5806 if (query.size() >= 1) { 5807 // If there is more than one service with the same priority, 5808 // just arbitrarily pick the first one. 5809 return query.get(0); 5810 } 5811 } 5812 return null; 5813 } 5814 5815 @Override 5816 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5817 String resolvedType, int flags, int userId) { 5818 return new ParceledListSlice<>( 5819 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5820 } 5821 5822 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5823 String resolvedType, int flags, int userId) { 5824 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5825 flags = updateFlagsForResolve(flags, userId, intent); 5826 ComponentName comp = intent.getComponent(); 5827 if (comp == null) { 5828 if (intent.getSelector() != null) { 5829 intent = intent.getSelector(); 5830 comp = intent.getComponent(); 5831 } 5832 } 5833 if (comp != null) { 5834 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5835 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5836 if (si != null) { 5837 final ResolveInfo ri = new ResolveInfo(); 5838 ri.serviceInfo = si; 5839 list.add(ri); 5840 } 5841 return list; 5842 } 5843 5844 // reader 5845 synchronized (mPackages) { 5846 String pkgName = intent.getPackage(); 5847 if (pkgName == null) { 5848 return mServices.queryIntent(intent, resolvedType, flags, userId); 5849 } 5850 final PackageParser.Package pkg = mPackages.get(pkgName); 5851 if (pkg != null) { 5852 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5853 userId); 5854 } 5855 return Collections.emptyList(); 5856 } 5857 } 5858 5859 @Override 5860 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5861 String resolvedType, int flags, int userId) { 5862 return new ParceledListSlice<>( 5863 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5864 } 5865 5866 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5867 Intent intent, String resolvedType, int flags, int userId) { 5868 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5869 flags = updateFlagsForResolve(flags, userId, intent); 5870 ComponentName comp = intent.getComponent(); 5871 if (comp == null) { 5872 if (intent.getSelector() != null) { 5873 intent = intent.getSelector(); 5874 comp = intent.getComponent(); 5875 } 5876 } 5877 if (comp != null) { 5878 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5879 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5880 if (pi != null) { 5881 final ResolveInfo ri = new ResolveInfo(); 5882 ri.providerInfo = pi; 5883 list.add(ri); 5884 } 5885 return list; 5886 } 5887 5888 // reader 5889 synchronized (mPackages) { 5890 String pkgName = intent.getPackage(); 5891 if (pkgName == null) { 5892 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5893 } 5894 final PackageParser.Package pkg = mPackages.get(pkgName); 5895 if (pkg != null) { 5896 return mProviders.queryIntentForPackage( 5897 intent, resolvedType, flags, pkg.providers, userId); 5898 } 5899 return Collections.emptyList(); 5900 } 5901 } 5902 5903 @Override 5904 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5905 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5906 flags = updateFlagsForPackage(flags, userId, null); 5907 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5908 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5909 true /* requireFullPermission */, false /* checkShell */, 5910 "get installed packages"); 5911 5912 // writer 5913 synchronized (mPackages) { 5914 ArrayList<PackageInfo> list; 5915 if (listUninstalled) { 5916 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5917 for (PackageSetting ps : mSettings.mPackages.values()) { 5918 PackageInfo pi; 5919 if (ps.pkg != null) { 5920 pi = generatePackageInfo(ps.pkg, flags, userId); 5921 } else { 5922 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5923 } 5924 if (pi != null) { 5925 list.add(pi); 5926 } 5927 } 5928 } else { 5929 list = new ArrayList<PackageInfo>(mPackages.size()); 5930 for (PackageParser.Package p : mPackages.values()) { 5931 PackageInfo pi = generatePackageInfo(p, flags, userId); 5932 if (pi != null) { 5933 list.add(pi); 5934 } 5935 } 5936 } 5937 5938 return new ParceledListSlice<PackageInfo>(list); 5939 } 5940 } 5941 5942 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5943 String[] permissions, boolean[] tmp, int flags, int userId) { 5944 int numMatch = 0; 5945 final PermissionsState permissionsState = ps.getPermissionsState(); 5946 for (int i=0; i<permissions.length; i++) { 5947 final String permission = permissions[i]; 5948 if (permissionsState.hasPermission(permission, userId)) { 5949 tmp[i] = true; 5950 numMatch++; 5951 } else { 5952 tmp[i] = false; 5953 } 5954 } 5955 if (numMatch == 0) { 5956 return; 5957 } 5958 PackageInfo pi; 5959 if (ps.pkg != null) { 5960 pi = generatePackageInfo(ps.pkg, flags, userId); 5961 } else { 5962 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5963 } 5964 // The above might return null in cases of uninstalled apps or install-state 5965 // skew across users/profiles. 5966 if (pi != null) { 5967 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5968 if (numMatch == permissions.length) { 5969 pi.requestedPermissions = permissions; 5970 } else { 5971 pi.requestedPermissions = new String[numMatch]; 5972 numMatch = 0; 5973 for (int i=0; i<permissions.length; i++) { 5974 if (tmp[i]) { 5975 pi.requestedPermissions[numMatch] = permissions[i]; 5976 numMatch++; 5977 } 5978 } 5979 } 5980 } 5981 list.add(pi); 5982 } 5983 } 5984 5985 @Override 5986 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5987 String[] permissions, int flags, int userId) { 5988 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5989 flags = updateFlagsForPackage(flags, userId, permissions); 5990 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5991 5992 // writer 5993 synchronized (mPackages) { 5994 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5995 boolean[] tmpBools = new boolean[permissions.length]; 5996 if (listUninstalled) { 5997 for (PackageSetting ps : mSettings.mPackages.values()) { 5998 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5999 } 6000 } else { 6001 for (PackageParser.Package pkg : mPackages.values()) { 6002 PackageSetting ps = (PackageSetting)pkg.mExtras; 6003 if (ps != null) { 6004 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6005 userId); 6006 } 6007 } 6008 } 6009 6010 return new ParceledListSlice<PackageInfo>(list); 6011 } 6012 } 6013 6014 @Override 6015 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6016 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6017 flags = updateFlagsForApplication(flags, userId, null); 6018 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6019 6020 // writer 6021 synchronized (mPackages) { 6022 ArrayList<ApplicationInfo> list; 6023 if (listUninstalled) { 6024 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6025 for (PackageSetting ps : mSettings.mPackages.values()) { 6026 ApplicationInfo ai; 6027 if (ps.pkg != null) { 6028 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6029 ps.readUserState(userId), userId); 6030 } else { 6031 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6032 } 6033 if (ai != null) { 6034 list.add(ai); 6035 } 6036 } 6037 } else { 6038 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6039 for (PackageParser.Package p : mPackages.values()) { 6040 if (p.mExtras != null) { 6041 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6042 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6043 if (ai != null) { 6044 list.add(ai); 6045 } 6046 } 6047 } 6048 } 6049 6050 return new ParceledListSlice<ApplicationInfo>(list); 6051 } 6052 } 6053 6054 @Override 6055 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6056 if (DISABLE_EPHEMERAL_APPS) { 6057 return null; 6058 } 6059 6060 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6061 "getEphemeralApplications"); 6062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6063 true /* requireFullPermission */, false /* checkShell */, 6064 "getEphemeralApplications"); 6065 synchronized (mPackages) { 6066 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6067 .getEphemeralApplicationsLPw(userId); 6068 if (ephemeralApps != null) { 6069 return new ParceledListSlice<>(ephemeralApps); 6070 } 6071 } 6072 return null; 6073 } 6074 6075 @Override 6076 public boolean isEphemeralApplication(String packageName, int userId) { 6077 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6078 true /* requireFullPermission */, false /* checkShell */, 6079 "isEphemeral"); 6080 if (DISABLE_EPHEMERAL_APPS) { 6081 return false; 6082 } 6083 6084 if (!isCallerSameApp(packageName)) { 6085 return false; 6086 } 6087 synchronized (mPackages) { 6088 PackageParser.Package pkg = mPackages.get(packageName); 6089 if (pkg != null) { 6090 return pkg.applicationInfo.isEphemeralApp(); 6091 } 6092 } 6093 return false; 6094 } 6095 6096 @Override 6097 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6098 if (DISABLE_EPHEMERAL_APPS) { 6099 return null; 6100 } 6101 6102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6103 true /* requireFullPermission */, false /* checkShell */, 6104 "getCookie"); 6105 if (!isCallerSameApp(packageName)) { 6106 return null; 6107 } 6108 synchronized (mPackages) { 6109 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6110 packageName, userId); 6111 } 6112 } 6113 6114 @Override 6115 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6116 if (DISABLE_EPHEMERAL_APPS) { 6117 return true; 6118 } 6119 6120 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6121 true /* requireFullPermission */, true /* checkShell */, 6122 "setCookie"); 6123 if (!isCallerSameApp(packageName)) { 6124 return false; 6125 } 6126 synchronized (mPackages) { 6127 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6128 packageName, cookie, userId); 6129 } 6130 } 6131 6132 @Override 6133 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6134 if (DISABLE_EPHEMERAL_APPS) { 6135 return null; 6136 } 6137 6138 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6139 "getEphemeralApplicationIcon"); 6140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6141 true /* requireFullPermission */, false /* checkShell */, 6142 "getEphemeralApplicationIcon"); 6143 synchronized (mPackages) { 6144 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6145 packageName, userId); 6146 } 6147 } 6148 6149 private boolean isCallerSameApp(String packageName) { 6150 PackageParser.Package pkg = mPackages.get(packageName); 6151 return pkg != null 6152 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6153 } 6154 6155 @Override 6156 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6157 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6158 } 6159 6160 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6161 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6162 6163 // reader 6164 synchronized (mPackages) { 6165 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6166 final int userId = UserHandle.getCallingUserId(); 6167 while (i.hasNext()) { 6168 final PackageParser.Package p = i.next(); 6169 if (p.applicationInfo == null) continue; 6170 6171 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6172 && !p.applicationInfo.isDirectBootAware(); 6173 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6174 && p.applicationInfo.isDirectBootAware(); 6175 6176 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6177 && (!mSafeMode || isSystemApp(p)) 6178 && (matchesUnaware || matchesAware)) { 6179 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6180 if (ps != null) { 6181 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6182 ps.readUserState(userId), userId); 6183 if (ai != null) { 6184 finalList.add(ai); 6185 } 6186 } 6187 } 6188 } 6189 } 6190 6191 return finalList; 6192 } 6193 6194 @Override 6195 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6196 if (!sUserManager.exists(userId)) return null; 6197 flags = updateFlagsForComponent(flags, userId, name); 6198 // reader 6199 synchronized (mPackages) { 6200 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6201 PackageSetting ps = provider != null 6202 ? mSettings.mPackages.get(provider.owner.packageName) 6203 : null; 6204 return ps != null 6205 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6206 ? PackageParser.generateProviderInfo(provider, flags, 6207 ps.readUserState(userId), userId) 6208 : null; 6209 } 6210 } 6211 6212 /** 6213 * @deprecated 6214 */ 6215 @Deprecated 6216 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6217 // reader 6218 synchronized (mPackages) { 6219 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6220 .entrySet().iterator(); 6221 final int userId = UserHandle.getCallingUserId(); 6222 while (i.hasNext()) { 6223 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6224 PackageParser.Provider p = entry.getValue(); 6225 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6226 6227 if (ps != null && p.syncable 6228 && (!mSafeMode || (p.info.applicationInfo.flags 6229 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6230 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6231 ps.readUserState(userId), userId); 6232 if (info != null) { 6233 outNames.add(entry.getKey()); 6234 outInfo.add(info); 6235 } 6236 } 6237 } 6238 } 6239 } 6240 6241 @Override 6242 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6243 int uid, int flags) { 6244 final int userId = processName != null ? UserHandle.getUserId(uid) 6245 : UserHandle.getCallingUserId(); 6246 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6247 flags = updateFlagsForComponent(flags, userId, processName); 6248 6249 ArrayList<ProviderInfo> finalList = null; 6250 // reader 6251 synchronized (mPackages) { 6252 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6253 while (i.hasNext()) { 6254 final PackageParser.Provider p = i.next(); 6255 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6256 if (ps != null && p.info.authority != null 6257 && (processName == null 6258 || (p.info.processName.equals(processName) 6259 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6260 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6261 if (finalList == null) { 6262 finalList = new ArrayList<ProviderInfo>(3); 6263 } 6264 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6265 ps.readUserState(userId), userId); 6266 if (info != null) { 6267 finalList.add(info); 6268 } 6269 } 6270 } 6271 } 6272 6273 if (finalList != null) { 6274 Collections.sort(finalList, mProviderInitOrderSorter); 6275 return new ParceledListSlice<ProviderInfo>(finalList); 6276 } 6277 6278 return ParceledListSlice.emptyList(); 6279 } 6280 6281 @Override 6282 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6283 // reader 6284 synchronized (mPackages) { 6285 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6286 return PackageParser.generateInstrumentationInfo(i, flags); 6287 } 6288 } 6289 6290 @Override 6291 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6292 String targetPackage, int flags) { 6293 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6294 } 6295 6296 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6297 int flags) { 6298 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6299 6300 // reader 6301 synchronized (mPackages) { 6302 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6303 while (i.hasNext()) { 6304 final PackageParser.Instrumentation p = i.next(); 6305 if (targetPackage == null 6306 || targetPackage.equals(p.info.targetPackage)) { 6307 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6308 flags); 6309 if (ii != null) { 6310 finalList.add(ii); 6311 } 6312 } 6313 } 6314 } 6315 6316 return finalList; 6317 } 6318 6319 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6320 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6321 if (overlays == null) { 6322 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6323 return; 6324 } 6325 for (PackageParser.Package opkg : overlays.values()) { 6326 // Not much to do if idmap fails: we already logged the error 6327 // and we certainly don't want to abort installation of pkg simply 6328 // because an overlay didn't fit properly. For these reasons, 6329 // ignore the return value of createIdmapForPackagePairLI. 6330 createIdmapForPackagePairLI(pkg, opkg); 6331 } 6332 } 6333 6334 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6335 PackageParser.Package opkg) { 6336 if (!opkg.mTrustedOverlay) { 6337 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6338 opkg.baseCodePath + ": overlay not trusted"); 6339 return false; 6340 } 6341 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6342 if (overlaySet == null) { 6343 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6344 opkg.baseCodePath + " but target package has no known overlays"); 6345 return false; 6346 } 6347 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6348 // TODO: generate idmap for split APKs 6349 try { 6350 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6351 } catch (InstallerException e) { 6352 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6353 + opkg.baseCodePath); 6354 return false; 6355 } 6356 PackageParser.Package[] overlayArray = 6357 overlaySet.values().toArray(new PackageParser.Package[0]); 6358 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6359 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6360 return p1.mOverlayPriority - p2.mOverlayPriority; 6361 } 6362 }; 6363 Arrays.sort(overlayArray, cmp); 6364 6365 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6366 int i = 0; 6367 for (PackageParser.Package p : overlayArray) { 6368 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6369 } 6370 return true; 6371 } 6372 6373 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6375 try { 6376 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6377 } finally { 6378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6379 } 6380 } 6381 6382 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6383 final File[] files = dir.listFiles(); 6384 if (ArrayUtils.isEmpty(files)) { 6385 Log.d(TAG, "No files in app dir " + dir); 6386 return; 6387 } 6388 6389 if (DEBUG_PACKAGE_SCANNING) { 6390 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6391 + " flags=0x" + Integer.toHexString(parseFlags)); 6392 } 6393 6394 for (File file : files) { 6395 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6396 && !PackageInstallerService.isStageName(file.getName()); 6397 if (!isPackage) { 6398 // Ignore entries which are not packages 6399 continue; 6400 } 6401 try { 6402 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6403 scanFlags, currentTime, null); 6404 } catch (PackageManagerException e) { 6405 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6406 6407 // Delete invalid userdata apps 6408 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6409 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6410 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6411 removeCodePathLI(file); 6412 } 6413 } 6414 } 6415 } 6416 6417 private static File getSettingsProblemFile() { 6418 File dataDir = Environment.getDataDirectory(); 6419 File systemDir = new File(dataDir, "system"); 6420 File fname = new File(systemDir, "uiderrors.txt"); 6421 return fname; 6422 } 6423 6424 static void reportSettingsProblem(int priority, String msg) { 6425 logCriticalInfo(priority, msg); 6426 } 6427 6428 static void logCriticalInfo(int priority, String msg) { 6429 Slog.println(priority, TAG, msg); 6430 EventLogTags.writePmCriticalInfo(msg); 6431 try { 6432 File fname = getSettingsProblemFile(); 6433 FileOutputStream out = new FileOutputStream(fname, true); 6434 PrintWriter pw = new FastPrintWriter(out); 6435 SimpleDateFormat formatter = new SimpleDateFormat(); 6436 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6437 pw.println(dateString + ": " + msg); 6438 pw.close(); 6439 FileUtils.setPermissions( 6440 fname.toString(), 6441 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6442 -1, -1); 6443 } catch (java.io.IOException e) { 6444 } 6445 } 6446 6447 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6448 int parseFlags) throws PackageManagerException { 6449 if (ps != null 6450 && ps.codePath.equals(srcFile) 6451 && ps.timeStamp == srcFile.lastModified() 6452 && !isCompatSignatureUpdateNeeded(pkg) 6453 && !isRecoverSignatureUpdateNeeded(pkg)) { 6454 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6455 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6456 ArraySet<PublicKey> signingKs; 6457 synchronized (mPackages) { 6458 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6459 } 6460 if (ps.signatures.mSignatures != null 6461 && ps.signatures.mSignatures.length != 0 6462 && signingKs != null) { 6463 // Optimization: reuse the existing cached certificates 6464 // if the package appears to be unchanged. 6465 pkg.mSignatures = ps.signatures.mSignatures; 6466 pkg.mSigningKeys = signingKs; 6467 return; 6468 } 6469 6470 Slog.w(TAG, "PackageSetting for " + ps.name 6471 + " is missing signatures. Collecting certs again to recover them."); 6472 } else { 6473 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6474 } 6475 6476 try { 6477 PackageParser.collectCertificates(pkg, parseFlags); 6478 } catch (PackageParserException e) { 6479 throw PackageManagerException.from(e); 6480 } 6481 } 6482 6483 /** 6484 * Traces a package scan. 6485 * @see #scanPackageLI(File, int, int, long, UserHandle) 6486 */ 6487 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6488 long currentTime, UserHandle user) throws PackageManagerException { 6489 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6490 try { 6491 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6492 } finally { 6493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6494 } 6495 } 6496 6497 /** 6498 * Scans a package and returns the newly parsed package. 6499 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6500 */ 6501 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6502 long currentTime, UserHandle user) throws PackageManagerException { 6503 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6504 parseFlags |= mDefParseFlags; 6505 PackageParser pp = new PackageParser(); 6506 pp.setSeparateProcesses(mSeparateProcesses); 6507 pp.setOnlyCoreApps(mOnlyCore); 6508 pp.setDisplayMetrics(mMetrics); 6509 6510 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6511 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6512 } 6513 6514 final PackageParser.Package pkg; 6515 try { 6516 pkg = pp.parsePackage(scanFile, parseFlags); 6517 } catch (PackageParserException e) { 6518 throw PackageManagerException.from(e); 6519 } 6520 6521 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6522 } 6523 6524 /** 6525 * Scans a package and returns the newly parsed package. 6526 * @throws PackageManagerException on a parse error. 6527 */ 6528 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6529 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6530 throws PackageManagerException { 6531 // If the package has children and this is the first dive in the function 6532 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6533 // packages (parent and children) would be successfully scanned before the 6534 // actual scan since scanning mutates internal state and we want to atomically 6535 // install the package and its children. 6536 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6537 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6538 scanFlags |= SCAN_CHECK_ONLY; 6539 } 6540 } else { 6541 scanFlags &= ~SCAN_CHECK_ONLY; 6542 } 6543 6544 // Scan the parent 6545 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6546 scanFlags, currentTime, user); 6547 6548 // Scan the children 6549 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6550 for (int i = 0; i < childCount; i++) { 6551 PackageParser.Package childPackage = pkg.childPackages.get(i); 6552 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6553 currentTime, user); 6554 } 6555 6556 6557 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6558 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6559 } 6560 6561 return scannedPkg; 6562 } 6563 6564 /** 6565 * Scans a package and returns the newly parsed package. 6566 * @throws PackageManagerException on a parse error. 6567 */ 6568 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6569 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6570 throws PackageManagerException { 6571 PackageSetting ps = null; 6572 PackageSetting updatedPkg; 6573 // reader 6574 synchronized (mPackages) { 6575 // Look to see if we already know about this package. 6576 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6577 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6578 // This package has been renamed to its original name. Let's 6579 // use that. 6580 ps = mSettings.peekPackageLPr(oldName); 6581 } 6582 // If there was no original package, see one for the real package name. 6583 if (ps == null) { 6584 ps = mSettings.peekPackageLPr(pkg.packageName); 6585 } 6586 // Check to see if this package could be hiding/updating a system 6587 // package. Must look for it either under the original or real 6588 // package name depending on our state. 6589 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6590 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6591 6592 // If this is a package we don't know about on the system partition, we 6593 // may need to remove disabled child packages on the system partition 6594 // or may need to not add child packages if the parent apk is updated 6595 // on the data partition and no longer defines this child package. 6596 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6597 // If this is a parent package for an updated system app and this system 6598 // app got an OTA update which no longer defines some of the child packages 6599 // we have to prune them from the disabled system packages. 6600 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6601 if (disabledPs != null) { 6602 final int scannedChildCount = (pkg.childPackages != null) 6603 ? pkg.childPackages.size() : 0; 6604 final int disabledChildCount = disabledPs.childPackageNames != null 6605 ? disabledPs.childPackageNames.size() : 0; 6606 for (int i = 0; i < disabledChildCount; i++) { 6607 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6608 boolean disabledPackageAvailable = false; 6609 for (int j = 0; j < scannedChildCount; j++) { 6610 PackageParser.Package childPkg = pkg.childPackages.get(j); 6611 if (childPkg.packageName.equals(disabledChildPackageName)) { 6612 disabledPackageAvailable = true; 6613 break; 6614 } 6615 } 6616 if (!disabledPackageAvailable) { 6617 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6618 } 6619 } 6620 } 6621 } 6622 } 6623 6624 boolean updatedPkgBetter = false; 6625 // First check if this is a system package that may involve an update 6626 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6627 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6628 // it needs to drop FLAG_PRIVILEGED. 6629 if (locationIsPrivileged(scanFile)) { 6630 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6631 } else { 6632 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6633 } 6634 6635 if (ps != null && !ps.codePath.equals(scanFile)) { 6636 // The path has changed from what was last scanned... check the 6637 // version of the new path against what we have stored to determine 6638 // what to do. 6639 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6640 if (pkg.mVersionCode <= ps.versionCode) { 6641 // The system package has been updated and the code path does not match 6642 // Ignore entry. Skip it. 6643 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6644 + " ignored: updated version " + ps.versionCode 6645 + " better than this " + pkg.mVersionCode); 6646 if (!updatedPkg.codePath.equals(scanFile)) { 6647 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6648 + ps.name + " changing from " + updatedPkg.codePathString 6649 + " to " + scanFile); 6650 updatedPkg.codePath = scanFile; 6651 updatedPkg.codePathString = scanFile.toString(); 6652 updatedPkg.resourcePath = scanFile; 6653 updatedPkg.resourcePathString = scanFile.toString(); 6654 } 6655 updatedPkg.pkg = pkg; 6656 updatedPkg.versionCode = pkg.mVersionCode; 6657 6658 // Update the disabled system child packages to point to the package too. 6659 final int childCount = updatedPkg.childPackageNames != null 6660 ? updatedPkg.childPackageNames.size() : 0; 6661 for (int i = 0; i < childCount; i++) { 6662 String childPackageName = updatedPkg.childPackageNames.get(i); 6663 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6664 childPackageName); 6665 if (updatedChildPkg != null) { 6666 updatedChildPkg.pkg = pkg; 6667 updatedChildPkg.versionCode = pkg.mVersionCode; 6668 } 6669 } 6670 6671 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6672 + scanFile + " ignored: updated version " + ps.versionCode 6673 + " better than this " + pkg.mVersionCode); 6674 } else { 6675 // The current app on the system partition is better than 6676 // what we have updated to on the data partition; switch 6677 // back to the system partition version. 6678 // At this point, its safely assumed that package installation for 6679 // apps in system partition will go through. If not there won't be a working 6680 // version of the app 6681 // writer 6682 synchronized (mPackages) { 6683 // Just remove the loaded entries from package lists. 6684 mPackages.remove(ps.name); 6685 } 6686 6687 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6688 + " reverting from " + ps.codePathString 6689 + ": new version " + pkg.mVersionCode 6690 + " better than installed " + ps.versionCode); 6691 6692 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6693 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6694 synchronized (mInstallLock) { 6695 args.cleanUpResourcesLI(); 6696 } 6697 synchronized (mPackages) { 6698 mSettings.enableSystemPackageLPw(ps.name); 6699 } 6700 updatedPkgBetter = true; 6701 } 6702 } 6703 } 6704 6705 if (updatedPkg != null) { 6706 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6707 // initially 6708 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6709 6710 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6711 // flag set initially 6712 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6713 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6714 } 6715 } 6716 6717 // Verify certificates against what was last scanned 6718 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6719 6720 /* 6721 * A new system app appeared, but we already had a non-system one of the 6722 * same name installed earlier. 6723 */ 6724 boolean shouldHideSystemApp = false; 6725 if (updatedPkg == null && ps != null 6726 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6727 /* 6728 * Check to make sure the signatures match first. If they don't, 6729 * wipe the installed application and its data. 6730 */ 6731 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6732 != PackageManager.SIGNATURE_MATCH) { 6733 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6734 + " signatures don't match existing userdata copy; removing"); 6735 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6736 ps = null; 6737 } else { 6738 /* 6739 * If the newly-added system app is an older version than the 6740 * already installed version, hide it. It will be scanned later 6741 * and re-added like an update. 6742 */ 6743 if (pkg.mVersionCode <= ps.versionCode) { 6744 shouldHideSystemApp = true; 6745 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6746 + " but new version " + pkg.mVersionCode + " better than installed " 6747 + ps.versionCode + "; hiding system"); 6748 } else { 6749 /* 6750 * The newly found system app is a newer version that the 6751 * one previously installed. Simply remove the 6752 * already-installed application and replace it with our own 6753 * while keeping the application data. 6754 */ 6755 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6756 + " reverting from " + ps.codePathString + ": new version " 6757 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6758 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6759 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6760 synchronized (mInstallLock) { 6761 args.cleanUpResourcesLI(); 6762 } 6763 } 6764 } 6765 } 6766 6767 // The apk is forward locked (not public) if its code and resources 6768 // are kept in different files. (except for app in either system or 6769 // vendor path). 6770 // TODO grab this value from PackageSettings 6771 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6772 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6773 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6774 } 6775 } 6776 6777 // TODO: extend to support forward-locked splits 6778 String resourcePath = null; 6779 String baseResourcePath = null; 6780 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6781 if (ps != null && ps.resourcePathString != null) { 6782 resourcePath = ps.resourcePathString; 6783 baseResourcePath = ps.resourcePathString; 6784 } else { 6785 // Should not happen at all. Just log an error. 6786 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6787 } 6788 } else { 6789 resourcePath = pkg.codePath; 6790 baseResourcePath = pkg.baseCodePath; 6791 } 6792 6793 // Set application objects path explicitly. 6794 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6795 pkg.setApplicationInfoCodePath(pkg.codePath); 6796 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6797 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6798 pkg.setApplicationInfoResourcePath(resourcePath); 6799 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6800 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6801 6802 // Note that we invoke the following method only if we are about to unpack an application 6803 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6804 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6805 6806 /* 6807 * If the system app should be overridden by a previously installed 6808 * data, hide the system app now and let the /data/app scan pick it up 6809 * again. 6810 */ 6811 if (shouldHideSystemApp) { 6812 synchronized (mPackages) { 6813 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6814 } 6815 } 6816 6817 return scannedPkg; 6818 } 6819 6820 private static String fixProcessName(String defProcessName, 6821 String processName, int uid) { 6822 if (processName == null) { 6823 return defProcessName; 6824 } 6825 return processName; 6826 } 6827 6828 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6829 throws PackageManagerException { 6830 if (pkgSetting.signatures.mSignatures != null) { 6831 // Already existing package. Make sure signatures match 6832 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6833 == PackageManager.SIGNATURE_MATCH; 6834 if (!match) { 6835 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6836 == PackageManager.SIGNATURE_MATCH; 6837 } 6838 if (!match) { 6839 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6840 == PackageManager.SIGNATURE_MATCH; 6841 } 6842 if (!match) { 6843 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6844 + pkg.packageName + " signatures do not match the " 6845 + "previously installed version; ignoring!"); 6846 } 6847 } 6848 6849 // Check for shared user signatures 6850 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6851 // Already existing package. Make sure signatures match 6852 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6853 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6854 if (!match) { 6855 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6856 == PackageManager.SIGNATURE_MATCH; 6857 } 6858 if (!match) { 6859 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6860 == PackageManager.SIGNATURE_MATCH; 6861 } 6862 if (!match) { 6863 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6864 "Package " + pkg.packageName 6865 + " has no signatures that match those in shared user " 6866 + pkgSetting.sharedUser.name + "; ignoring!"); 6867 } 6868 } 6869 } 6870 6871 /** 6872 * Enforces that only the system UID or root's UID can call a method exposed 6873 * via Binder. 6874 * 6875 * @param message used as message if SecurityException is thrown 6876 * @throws SecurityException if the caller is not system or root 6877 */ 6878 private static final void enforceSystemOrRoot(String message) { 6879 final int uid = Binder.getCallingUid(); 6880 if (uid != Process.SYSTEM_UID && uid != 0) { 6881 throw new SecurityException(message); 6882 } 6883 } 6884 6885 @Override 6886 public void performFstrimIfNeeded() { 6887 enforceSystemOrRoot("Only the system can request fstrim"); 6888 6889 // Before everything else, see whether we need to fstrim. 6890 try { 6891 IMountService ms = PackageHelper.getMountService(); 6892 if (ms != null) { 6893 final boolean isUpgrade = isUpgrade(); 6894 boolean doTrim = isUpgrade; 6895 if (doTrim) { 6896 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6897 } else { 6898 final long interval = android.provider.Settings.Global.getLong( 6899 mContext.getContentResolver(), 6900 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6901 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6902 if (interval > 0) { 6903 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6904 if (timeSinceLast > interval) { 6905 doTrim = true; 6906 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6907 + "; running immediately"); 6908 } 6909 } 6910 } 6911 if (doTrim) { 6912 if (!isFirstBoot()) { 6913 try { 6914 ActivityManagerNative.getDefault().showBootMessage( 6915 mContext.getResources().getString( 6916 R.string.android_upgrading_fstrim), true); 6917 } catch (RemoteException e) { 6918 } 6919 } 6920 ms.runMaintenance(); 6921 } 6922 } else { 6923 Slog.e(TAG, "Mount service unavailable!"); 6924 } 6925 } catch (RemoteException e) { 6926 // Can't happen; MountService is local 6927 } 6928 } 6929 6930 @Override 6931 public void updatePackagesIfNeeded() { 6932 enforceSystemOrRoot("Only the system can request package update"); 6933 6934 // We need to re-extract after an OTA. 6935 boolean causeUpgrade = isUpgrade(); 6936 6937 // First boot or factory reset. 6938 // Note: we also handle devices that are upgrading to N right now as if it is their 6939 // first boot, as they do not have profile data. 6940 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6941 6942 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6943 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6944 6945 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 6946 return; 6947 } 6948 6949 List<PackageParser.Package> pkgs; 6950 synchronized (mPackages) { 6951 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6952 } 6953 6954 int curr = 0; 6955 int total = pkgs.size(); 6956 for (PackageParser.Package pkg : pkgs) { 6957 curr++; 6958 6959 if (DEBUG_DEXOPT) { 6960 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6961 } 6962 6963 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6964 // If the cache was pruned, any compiled odex files will likely be out of date 6965 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 6966 // Instead, force the extraction in this case. 6967 performDexOpt(pkg.packageName, null /* instructionSet */, 6968 false /* checkProfiles */, 6969 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 6970 causePrunedCache); 6971 } 6972 } 6973 } 6974 6975 @Override 6976 public void notifyPackageUse(String packageName) { 6977 synchronized (mPackages) { 6978 PackageParser.Package p = mPackages.get(packageName); 6979 if (p == null) { 6980 return; 6981 } 6982 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6983 } 6984 } 6985 6986 // TODO: this is not used nor needed. Delete it. 6987 @Override 6988 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6989 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 6990 getFullCompilerFilter(), false /* force */); 6991 } 6992 6993 @Override 6994 public boolean performDexOpt(String packageName, String instructionSet, 6995 boolean checkProfiles, int compileReason, boolean force) { 6996 return performDexOptTraced(packageName, instructionSet, checkProfiles, 6997 getCompilerFilterForReason(compileReason), force); 6998 } 6999 7000 @Override 7001 public boolean performDexOptMode(String packageName, String instructionSet, 7002 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7003 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7004 targetCompilerFilter, force); 7005 } 7006 7007 private boolean performDexOptTraced(String packageName, String instructionSet, 7008 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7009 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7010 try { 7011 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7012 targetCompilerFilter, force); 7013 } finally { 7014 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7015 } 7016 } 7017 7018 private boolean performDexOptInternal(String packageName, String instructionSet, 7019 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7020 PackageParser.Package p; 7021 final String targetInstructionSet; 7022 synchronized (mPackages) { 7023 p = mPackages.get(packageName); 7024 if (p == null) { 7025 return false; 7026 } 7027 mPackageUsage.write(false); 7028 7029 targetInstructionSet = instructionSet != null ? instructionSet : 7030 getPrimaryInstructionSet(p.applicationInfo); 7031 } 7032 long callingId = Binder.clearCallingIdentity(); 7033 try { 7034 synchronized (mInstallLock) { 7035 final String[] instructionSets = new String[] { targetInstructionSet }; 7036 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7037 checkProfiles, targetCompilerFilter, force); 7038 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7039 } 7040 } finally { 7041 Binder.restoreCallingIdentity(callingId); 7042 } 7043 } 7044 7045 public ArraySet<String> getOptimizablePackages() { 7046 ArraySet<String> pkgs = new ArraySet<String>(); 7047 synchronized (mPackages) { 7048 for (PackageParser.Package p : mPackages.values()) { 7049 if (PackageDexOptimizer.canOptimizePackage(p)) { 7050 pkgs.add(p.packageName); 7051 } 7052 } 7053 } 7054 return pkgs; 7055 } 7056 7057 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7058 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7059 boolean force) { 7060 // Select the dex optimizer based on the force parameter. 7061 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7062 // allocate an object here. 7063 PackageDexOptimizer pdo = force 7064 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7065 : mPackageDexOptimizer; 7066 7067 // Optimize all dependencies first. Note: we ignore the return value and march on 7068 // on errors. 7069 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7070 if (!deps.isEmpty()) { 7071 for (PackageParser.Package depPackage : deps) { 7072 // TODO: Analyze and investigate if we (should) profile libraries. 7073 // Currently this will do a full compilation of the library by default. 7074 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7075 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7076 } 7077 } 7078 7079 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7080 } 7081 7082 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7083 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7084 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7085 Set<String> collectedNames = new HashSet<>(); 7086 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7087 7088 retValue.remove(p); 7089 7090 return retValue; 7091 } else { 7092 return Collections.emptyList(); 7093 } 7094 } 7095 7096 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7097 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7098 if (!collectedNames.contains(p.packageName)) { 7099 collectedNames.add(p.packageName); 7100 collected.add(p); 7101 7102 if (p.usesLibraries != null) { 7103 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7104 } 7105 if (p.usesOptionalLibraries != null) { 7106 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7107 collectedNames); 7108 } 7109 } 7110 } 7111 7112 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7113 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7114 for (String libName : libs) { 7115 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7116 if (libPkg != null) { 7117 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7118 } 7119 } 7120 } 7121 7122 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7123 synchronized (mPackages) { 7124 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7125 if (lib != null && lib.apk != null) { 7126 return mPackages.get(lib.apk); 7127 } 7128 } 7129 return null; 7130 } 7131 7132 public void shutdown() { 7133 mPackageUsage.write(true); 7134 } 7135 7136 @Override 7137 public void forceDexOpt(String packageName) { 7138 enforceSystemOrRoot("forceDexOpt"); 7139 7140 PackageParser.Package pkg; 7141 synchronized (mPackages) { 7142 pkg = mPackages.get(packageName); 7143 if (pkg == null) { 7144 throw new IllegalArgumentException("Unknown package: " + packageName); 7145 } 7146 } 7147 7148 synchronized (mInstallLock) { 7149 final String[] instructionSets = new String[] { 7150 getPrimaryInstructionSet(pkg.applicationInfo) }; 7151 7152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7153 7154 // Whoever is calling forceDexOpt wants a fully compiled package. 7155 // Don't use profiles since that may cause compilation to be skipped. 7156 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7157 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7158 true /* force */); 7159 7160 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7161 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7162 throw new IllegalStateException("Failed to dexopt: " + res); 7163 } 7164 } 7165 } 7166 7167 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7168 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7169 Slog.w(TAG, "Unable to update from " + oldPkg.name 7170 + " to " + newPkg.packageName 7171 + ": old package not in system partition"); 7172 return false; 7173 } else if (mPackages.get(oldPkg.name) != null) { 7174 Slog.w(TAG, "Unable to update from " + oldPkg.name 7175 + " to " + newPkg.packageName 7176 + ": old package still exists"); 7177 return false; 7178 } 7179 return true; 7180 } 7181 7182 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7183 // TODO: triage flags as part of 26466827 7184 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7185 7186 boolean res = true; 7187 final int[] users = sUserManager.getUserIds(); 7188 for (int user : users) { 7189 try { 7190 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7191 } catch (InstallerException e) { 7192 Slog.w(TAG, "Failed to delete data directory", e); 7193 res = false; 7194 } 7195 } 7196 return res; 7197 } 7198 7199 void removeCodePathLI(File codePath) { 7200 if (codePath.isDirectory()) { 7201 try { 7202 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7203 } catch (InstallerException e) { 7204 Slog.w(TAG, "Failed to remove code path", e); 7205 } 7206 } else { 7207 codePath.delete(); 7208 } 7209 } 7210 7211 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7212 try { 7213 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7214 } catch (InstallerException e) { 7215 Slog.w(TAG, "Failed to destroy app data", e); 7216 } 7217 } 7218 7219 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7220 int appId, String seinfo) { 7221 try { 7222 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7223 } catch (InstallerException e) { 7224 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7225 } 7226 } 7227 7228 private void deleteProfilesLI(String packageName, boolean destroy) { 7229 final PackageParser.Package pkg; 7230 synchronized (mPackages) { 7231 pkg = mPackages.get(packageName); 7232 } 7233 if (pkg == null) { 7234 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7235 return; 7236 } 7237 deleteProfilesLI(pkg, destroy); 7238 } 7239 7240 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7241 try { 7242 if (destroy) { 7243 mInstaller.destroyAppProfiles(pkg.packageName); 7244 } else { 7245 mInstaller.clearAppProfiles(pkg.packageName); 7246 } 7247 } catch (InstallerException ex) { 7248 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7249 } 7250 } 7251 7252 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7253 final PackageParser.Package pkg; 7254 synchronized (mPackages) { 7255 pkg = mPackages.get(packageName); 7256 } 7257 if (pkg == null) { 7258 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7259 return; 7260 } 7261 deleteCodeCacheDirsLI(pkg); 7262 } 7263 7264 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7265 // TODO: triage flags as part of 26466827 7266 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7267 7268 int[] users = sUserManager.getUserIds(); 7269 int res = 0; 7270 for (int user : users) { 7271 // Remove the parent code cache 7272 try { 7273 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7274 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7275 } catch (InstallerException e) { 7276 Slog.w(TAG, "Failed to delete code cache directory", e); 7277 } 7278 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7279 for (int i = 0; i < childCount; i++) { 7280 PackageParser.Package childPkg = pkg.childPackages.get(i); 7281 // Remove the child code cache 7282 try { 7283 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7284 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7285 } catch (InstallerException e) { 7286 Slog.w(TAG, "Failed to delete code cache directory", e); 7287 } 7288 } 7289 } 7290 } 7291 7292 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7293 long lastUpdateTime) { 7294 // Set parent install/update time 7295 PackageSetting ps = (PackageSetting) pkg.mExtras; 7296 if (ps != null) { 7297 ps.firstInstallTime = firstInstallTime; 7298 ps.lastUpdateTime = lastUpdateTime; 7299 } 7300 // Set children install/update time 7301 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7302 for (int i = 0; i < childCount; i++) { 7303 PackageParser.Package childPkg = pkg.childPackages.get(i); 7304 ps = (PackageSetting) childPkg.mExtras; 7305 if (ps != null) { 7306 ps.firstInstallTime = firstInstallTime; 7307 ps.lastUpdateTime = lastUpdateTime; 7308 } 7309 } 7310 } 7311 7312 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7313 PackageParser.Package changingLib) { 7314 if (file.path != null) { 7315 usesLibraryFiles.add(file.path); 7316 return; 7317 } 7318 PackageParser.Package p = mPackages.get(file.apk); 7319 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7320 // If we are doing this while in the middle of updating a library apk, 7321 // then we need to make sure to use that new apk for determining the 7322 // dependencies here. (We haven't yet finished committing the new apk 7323 // to the package manager state.) 7324 if (p == null || p.packageName.equals(changingLib.packageName)) { 7325 p = changingLib; 7326 } 7327 } 7328 if (p != null) { 7329 usesLibraryFiles.addAll(p.getAllCodePaths()); 7330 } 7331 } 7332 7333 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7334 PackageParser.Package changingLib) throws PackageManagerException { 7335 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7336 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7337 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7338 for (int i=0; i<N; i++) { 7339 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7340 if (file == null) { 7341 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7342 "Package " + pkg.packageName + " requires unavailable shared library " 7343 + pkg.usesLibraries.get(i) + "; failing!"); 7344 } 7345 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7346 } 7347 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7348 for (int i=0; i<N; i++) { 7349 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7350 if (file == null) { 7351 Slog.w(TAG, "Package " + pkg.packageName 7352 + " desires unavailable shared library " 7353 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7354 } else { 7355 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7356 } 7357 } 7358 N = usesLibraryFiles.size(); 7359 if (N > 0) { 7360 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7361 } else { 7362 pkg.usesLibraryFiles = null; 7363 } 7364 } 7365 } 7366 7367 private static boolean hasString(List<String> list, List<String> which) { 7368 if (list == null) { 7369 return false; 7370 } 7371 for (int i=list.size()-1; i>=0; i--) { 7372 for (int j=which.size()-1; j>=0; j--) { 7373 if (which.get(j).equals(list.get(i))) { 7374 return true; 7375 } 7376 } 7377 } 7378 return false; 7379 } 7380 7381 private void updateAllSharedLibrariesLPw() { 7382 for (PackageParser.Package pkg : mPackages.values()) { 7383 try { 7384 updateSharedLibrariesLPw(pkg, null); 7385 } catch (PackageManagerException e) { 7386 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7387 } 7388 } 7389 } 7390 7391 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7392 PackageParser.Package changingPkg) { 7393 ArrayList<PackageParser.Package> res = null; 7394 for (PackageParser.Package pkg : mPackages.values()) { 7395 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7396 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7397 if (res == null) { 7398 res = new ArrayList<PackageParser.Package>(); 7399 } 7400 res.add(pkg); 7401 try { 7402 updateSharedLibrariesLPw(pkg, changingPkg); 7403 } catch (PackageManagerException e) { 7404 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7405 } 7406 } 7407 } 7408 return res; 7409 } 7410 7411 /** 7412 * Derive the value of the {@code cpuAbiOverride} based on the provided 7413 * value and an optional stored value from the package settings. 7414 */ 7415 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7416 String cpuAbiOverride = null; 7417 7418 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7419 cpuAbiOverride = null; 7420 } else if (abiOverride != null) { 7421 cpuAbiOverride = abiOverride; 7422 } else if (settings != null) { 7423 cpuAbiOverride = settings.cpuAbiOverrideString; 7424 } 7425 7426 return cpuAbiOverride; 7427 } 7428 7429 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7430 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7432 // If the package has children and this is the first dive in the function 7433 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7434 // whether all packages (parent and children) would be successfully scanned 7435 // before the actual scan since scanning mutates internal state and we want 7436 // to atomically install the package and its children. 7437 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7438 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7439 scanFlags |= SCAN_CHECK_ONLY; 7440 } 7441 } else { 7442 scanFlags &= ~SCAN_CHECK_ONLY; 7443 } 7444 7445 final PackageParser.Package scannedPkg; 7446 try { 7447 // Scan the parent 7448 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7449 // Scan the children 7450 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7451 for (int i = 0; i < childCount; i++) { 7452 PackageParser.Package childPkg = pkg.childPackages.get(i); 7453 scanPackageLI(childPkg, parseFlags, 7454 scanFlags, currentTime, user); 7455 } 7456 } finally { 7457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7458 } 7459 7460 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7461 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7462 } 7463 7464 return scannedPkg; 7465 } 7466 7467 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7468 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7469 boolean success = false; 7470 try { 7471 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7472 currentTime, user); 7473 success = true; 7474 return res; 7475 } finally { 7476 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7477 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7478 } 7479 } 7480 } 7481 7482 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7483 int scanFlags, long currentTime, UserHandle user) 7484 throws PackageManagerException { 7485 final File scanFile = new File(pkg.codePath); 7486 if (pkg.applicationInfo.getCodePath() == null || 7487 pkg.applicationInfo.getResourcePath() == null) { 7488 // Bail out. The resource and code paths haven't been set. 7489 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7490 "Code and resource paths haven't been set correctly"); 7491 } 7492 7493 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7494 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7495 } else { 7496 // Only allow system apps to be flagged as core apps. 7497 pkg.coreApp = false; 7498 } 7499 7500 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7501 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7502 } 7503 7504 if (mCustomResolverComponentName != null && 7505 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7506 setUpCustomResolverActivity(pkg); 7507 } 7508 7509 if (pkg.packageName.equals("android")) { 7510 synchronized (mPackages) { 7511 if (mAndroidApplication != null) { 7512 Slog.w(TAG, "*************************************************"); 7513 Slog.w(TAG, "Core android package being redefined. Skipping."); 7514 Slog.w(TAG, " file=" + scanFile); 7515 Slog.w(TAG, "*************************************************"); 7516 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7517 "Core android package being redefined. Skipping."); 7518 } 7519 7520 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7521 // Set up information for our fall-back user intent resolution activity. 7522 mPlatformPackage = pkg; 7523 pkg.mVersionCode = mSdkVersion; 7524 mAndroidApplication = pkg.applicationInfo; 7525 7526 if (!mResolverReplaced) { 7527 mResolveActivity.applicationInfo = mAndroidApplication; 7528 mResolveActivity.name = ResolverActivity.class.getName(); 7529 mResolveActivity.packageName = mAndroidApplication.packageName; 7530 mResolveActivity.processName = "system:ui"; 7531 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7532 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7533 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7534 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7535 mResolveActivity.exported = true; 7536 mResolveActivity.enabled = true; 7537 mResolveInfo.activityInfo = mResolveActivity; 7538 mResolveInfo.priority = 0; 7539 mResolveInfo.preferredOrder = 0; 7540 mResolveInfo.match = 0; 7541 mResolveComponentName = new ComponentName( 7542 mAndroidApplication.packageName, mResolveActivity.name); 7543 } 7544 } 7545 } 7546 } 7547 7548 if (DEBUG_PACKAGE_SCANNING) { 7549 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7550 Log.d(TAG, "Scanning package " + pkg.packageName); 7551 } 7552 7553 synchronized (mPackages) { 7554 if (mPackages.containsKey(pkg.packageName) 7555 || mSharedLibraries.containsKey(pkg.packageName)) { 7556 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7557 "Application package " + pkg.packageName 7558 + " already installed. Skipping duplicate."); 7559 } 7560 7561 // If we're only installing presumed-existing packages, require that the 7562 // scanned APK is both already known and at the path previously established 7563 // for it. Previously unknown packages we pick up normally, but if we have an 7564 // a priori expectation about this package's install presence, enforce it. 7565 // With a singular exception for new system packages. When an OTA contains 7566 // a new system package, we allow the codepath to change from a system location 7567 // to the user-installed location. If we don't allow this change, any newer, 7568 // user-installed version of the application will be ignored. 7569 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7570 if (mExpectingBetter.containsKey(pkg.packageName)) { 7571 logCriticalInfo(Log.WARN, 7572 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7573 } else { 7574 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7575 if (known != null) { 7576 if (DEBUG_PACKAGE_SCANNING) { 7577 Log.d(TAG, "Examining " + pkg.codePath 7578 + " and requiring known paths " + known.codePathString 7579 + " & " + known.resourcePathString); 7580 } 7581 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7582 || !pkg.applicationInfo.getResourcePath().equals( 7583 known.resourcePathString)) { 7584 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7585 "Application package " + pkg.packageName 7586 + " found at " + pkg.applicationInfo.getCodePath() 7587 + " but expected at " + known.codePathString 7588 + "; ignoring."); 7589 } 7590 } 7591 } 7592 } 7593 } 7594 7595 // Initialize package source and resource directories 7596 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7597 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7598 7599 SharedUserSetting suid = null; 7600 PackageSetting pkgSetting = null; 7601 7602 if (!isSystemApp(pkg)) { 7603 // Only system apps can use these features. 7604 pkg.mOriginalPackages = null; 7605 pkg.mRealPackage = null; 7606 pkg.mAdoptPermissions = null; 7607 } 7608 7609 // Getting the package setting may have a side-effect, so if we 7610 // are only checking if scan would succeed, stash a copy of the 7611 // old setting to restore at the end. 7612 PackageSetting nonMutatedPs = null; 7613 7614 // writer 7615 synchronized (mPackages) { 7616 if (pkg.mSharedUserId != null) { 7617 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7618 if (suid == null) { 7619 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7620 "Creating application package " + pkg.packageName 7621 + " for shared user failed"); 7622 } 7623 if (DEBUG_PACKAGE_SCANNING) { 7624 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7625 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7626 + "): packages=" + suid.packages); 7627 } 7628 } 7629 7630 // Check if we are renaming from an original package name. 7631 PackageSetting origPackage = null; 7632 String realName = null; 7633 if (pkg.mOriginalPackages != null) { 7634 // This package may need to be renamed to a previously 7635 // installed name. Let's check on that... 7636 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7637 if (pkg.mOriginalPackages.contains(renamed)) { 7638 // This package had originally been installed as the 7639 // original name, and we have already taken care of 7640 // transitioning to the new one. Just update the new 7641 // one to continue using the old name. 7642 realName = pkg.mRealPackage; 7643 if (!pkg.packageName.equals(renamed)) { 7644 // Callers into this function may have already taken 7645 // care of renaming the package; only do it here if 7646 // it is not already done. 7647 pkg.setPackageName(renamed); 7648 } 7649 7650 } else { 7651 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7652 if ((origPackage = mSettings.peekPackageLPr( 7653 pkg.mOriginalPackages.get(i))) != null) { 7654 // We do have the package already installed under its 7655 // original name... should we use it? 7656 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7657 // New package is not compatible with original. 7658 origPackage = null; 7659 continue; 7660 } else if (origPackage.sharedUser != null) { 7661 // Make sure uid is compatible between packages. 7662 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7663 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7664 + " to " + pkg.packageName + ": old uid " 7665 + origPackage.sharedUser.name 7666 + " differs from " + pkg.mSharedUserId); 7667 origPackage = null; 7668 continue; 7669 } 7670 } else { 7671 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7672 + pkg.packageName + " to old name " + origPackage.name); 7673 } 7674 break; 7675 } 7676 } 7677 } 7678 } 7679 7680 if (mTransferedPackages.contains(pkg.packageName)) { 7681 Slog.w(TAG, "Package " + pkg.packageName 7682 + " was transferred to another, but its .apk remains"); 7683 } 7684 7685 // See comments in nonMutatedPs declaration 7686 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7687 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7688 if (foundPs != null) { 7689 nonMutatedPs = new PackageSetting(foundPs); 7690 } 7691 } 7692 7693 // Just create the setting, don't add it yet. For already existing packages 7694 // the PkgSetting exists already and doesn't have to be created. 7695 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7696 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7697 pkg.applicationInfo.primaryCpuAbi, 7698 pkg.applicationInfo.secondaryCpuAbi, 7699 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7700 user, false); 7701 if (pkgSetting == null) { 7702 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7703 "Creating application package " + pkg.packageName + " failed"); 7704 } 7705 7706 if (pkgSetting.origPackage != null) { 7707 // If we are first transitioning from an original package, 7708 // fix up the new package's name now. We need to do this after 7709 // looking up the package under its new name, so getPackageLP 7710 // can take care of fiddling things correctly. 7711 pkg.setPackageName(origPackage.name); 7712 7713 // File a report about this. 7714 String msg = "New package " + pkgSetting.realName 7715 + " renamed to replace old package " + pkgSetting.name; 7716 reportSettingsProblem(Log.WARN, msg); 7717 7718 // Make a note of it. 7719 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7720 mTransferedPackages.add(origPackage.name); 7721 } 7722 7723 // No longer need to retain this. 7724 pkgSetting.origPackage = null; 7725 } 7726 7727 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7728 // Make a note of it. 7729 mTransferedPackages.add(pkg.packageName); 7730 } 7731 7732 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7733 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7734 } 7735 7736 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7737 // Check all shared libraries and map to their actual file path. 7738 // We only do this here for apps not on a system dir, because those 7739 // are the only ones that can fail an install due to this. We 7740 // will take care of the system apps by updating all of their 7741 // library paths after the scan is done. 7742 updateSharedLibrariesLPw(pkg, null); 7743 } 7744 7745 if (mFoundPolicyFile) { 7746 SELinuxMMAC.assignSeinfoValue(pkg); 7747 } 7748 7749 pkg.applicationInfo.uid = pkgSetting.appId; 7750 pkg.mExtras = pkgSetting; 7751 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7752 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7753 // We just determined the app is signed correctly, so bring 7754 // over the latest parsed certs. 7755 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7756 } else { 7757 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7758 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7759 "Package " + pkg.packageName + " upgrade keys do not match the " 7760 + "previously installed version"); 7761 } else { 7762 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7763 String msg = "System package " + pkg.packageName 7764 + " signature changed; retaining data."; 7765 reportSettingsProblem(Log.WARN, msg); 7766 } 7767 } 7768 } else { 7769 try { 7770 verifySignaturesLP(pkgSetting, pkg); 7771 // We just determined the app is signed correctly, so bring 7772 // over the latest parsed certs. 7773 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7774 } catch (PackageManagerException e) { 7775 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7776 throw e; 7777 } 7778 // The signature has changed, but this package is in the system 7779 // image... let's recover! 7780 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7781 // However... if this package is part of a shared user, but it 7782 // doesn't match the signature of the shared user, let's fail. 7783 // What this means is that you can't change the signatures 7784 // associated with an overall shared user, which doesn't seem all 7785 // that unreasonable. 7786 if (pkgSetting.sharedUser != null) { 7787 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7788 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7789 throw new PackageManagerException( 7790 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7791 "Signature mismatch for shared user: " 7792 + pkgSetting.sharedUser); 7793 } 7794 } 7795 // File a report about this. 7796 String msg = "System package " + pkg.packageName 7797 + " signature changed; retaining data."; 7798 reportSettingsProblem(Log.WARN, msg); 7799 } 7800 } 7801 // Verify that this new package doesn't have any content providers 7802 // that conflict with existing packages. Only do this if the 7803 // package isn't already installed, since we don't want to break 7804 // things that are installed. 7805 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7806 final int N = pkg.providers.size(); 7807 int i; 7808 for (i=0; i<N; i++) { 7809 PackageParser.Provider p = pkg.providers.get(i); 7810 if (p.info.authority != null) { 7811 String names[] = p.info.authority.split(";"); 7812 for (int j = 0; j < names.length; j++) { 7813 if (mProvidersByAuthority.containsKey(names[j])) { 7814 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7815 final String otherPackageName = 7816 ((other != null && other.getComponentName() != null) ? 7817 other.getComponentName().getPackageName() : "?"); 7818 throw new PackageManagerException( 7819 INSTALL_FAILED_CONFLICTING_PROVIDER, 7820 "Can't install because provider name " + names[j] 7821 + " (in package " + pkg.applicationInfo.packageName 7822 + ") is already used by " + otherPackageName); 7823 } 7824 } 7825 } 7826 } 7827 } 7828 7829 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7830 // This package wants to adopt ownership of permissions from 7831 // another package. 7832 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7833 final String origName = pkg.mAdoptPermissions.get(i); 7834 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7835 if (orig != null) { 7836 if (verifyPackageUpdateLPr(orig, pkg)) { 7837 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7838 + pkg.packageName); 7839 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7840 } 7841 } 7842 } 7843 } 7844 } 7845 7846 final String pkgName = pkg.packageName; 7847 7848 final long scanFileTime = scanFile.lastModified(); 7849 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7850 pkg.applicationInfo.processName = fixProcessName( 7851 pkg.applicationInfo.packageName, 7852 pkg.applicationInfo.processName, 7853 pkg.applicationInfo.uid); 7854 7855 if (pkg != mPlatformPackage) { 7856 // Get all of our default paths setup 7857 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7858 } 7859 7860 final String path = scanFile.getPath(); 7861 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7862 7863 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7864 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7865 7866 // Some system apps still use directory structure for native libraries 7867 // in which case we might end up not detecting abi solely based on apk 7868 // structure. Try to detect abi based on directory structure. 7869 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7870 pkg.applicationInfo.primaryCpuAbi == null) { 7871 setBundledAppAbisAndRoots(pkg, pkgSetting); 7872 setNativeLibraryPaths(pkg); 7873 } 7874 7875 } else { 7876 if ((scanFlags & SCAN_MOVE) != 0) { 7877 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7878 // but we already have this packages package info in the PackageSetting. We just 7879 // use that and derive the native library path based on the new codepath. 7880 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7881 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7882 } 7883 7884 // Set native library paths again. For moves, the path will be updated based on the 7885 // ABIs we've determined above. For non-moves, the path will be updated based on the 7886 // ABIs we determined during compilation, but the path will depend on the final 7887 // package path (after the rename away from the stage path). 7888 setNativeLibraryPaths(pkg); 7889 } 7890 7891 // This is a special case for the "system" package, where the ABI is 7892 // dictated by the zygote configuration (and init.rc). We should keep track 7893 // of this ABI so that we can deal with "normal" applications that run under 7894 // the same UID correctly. 7895 if (mPlatformPackage == pkg) { 7896 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7897 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7898 } 7899 7900 // If there's a mismatch between the abi-override in the package setting 7901 // and the abiOverride specified for the install. Warn about this because we 7902 // would've already compiled the app without taking the package setting into 7903 // account. 7904 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7905 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7906 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7907 " for package " + pkg.packageName); 7908 } 7909 } 7910 7911 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7912 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7913 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7914 7915 // Copy the derived override back to the parsed package, so that we can 7916 // update the package settings accordingly. 7917 pkg.cpuAbiOverride = cpuAbiOverride; 7918 7919 if (DEBUG_ABI_SELECTION) { 7920 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7921 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7922 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7923 } 7924 7925 // Push the derived path down into PackageSettings so we know what to 7926 // clean up at uninstall time. 7927 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7928 7929 if (DEBUG_ABI_SELECTION) { 7930 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7931 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7932 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7933 } 7934 7935 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7936 // We don't do this here during boot because we can do it all 7937 // at once after scanning all existing packages. 7938 // 7939 // We also do this *before* we perform dexopt on this package, so that 7940 // we can avoid redundant dexopts, and also to make sure we've got the 7941 // code and package path correct. 7942 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7943 pkg, true /* boot complete */); 7944 } 7945 7946 if (mFactoryTest && pkg.requestedPermissions.contains( 7947 android.Manifest.permission.FACTORY_TEST)) { 7948 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7949 } 7950 7951 ArrayList<PackageParser.Package> clientLibPkgs = null; 7952 7953 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7954 if (nonMutatedPs != null) { 7955 synchronized (mPackages) { 7956 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7957 } 7958 } 7959 return pkg; 7960 } 7961 7962 // Only privileged apps and updated privileged apps can add child packages. 7963 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7964 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7965 throw new PackageManagerException("Only privileged apps and updated " 7966 + "privileged apps can add child packages. Ignoring package " 7967 + pkg.packageName); 7968 } 7969 final int childCount = pkg.childPackages.size(); 7970 for (int i = 0; i < childCount; i++) { 7971 PackageParser.Package childPkg = pkg.childPackages.get(i); 7972 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7973 childPkg.packageName)) { 7974 throw new PackageManagerException("Cannot override a child package of " 7975 + "another disabled system app. Ignoring package " + pkg.packageName); 7976 } 7977 } 7978 } 7979 7980 // writer 7981 synchronized (mPackages) { 7982 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7983 // Only system apps can add new shared libraries. 7984 if (pkg.libraryNames != null) { 7985 for (int i=0; i<pkg.libraryNames.size(); i++) { 7986 String name = pkg.libraryNames.get(i); 7987 boolean allowed = false; 7988 if (pkg.isUpdatedSystemApp()) { 7989 // New library entries can only be added through the 7990 // system image. This is important to get rid of a lot 7991 // of nasty edge cases: for example if we allowed a non- 7992 // system update of the app to add a library, then uninstalling 7993 // the update would make the library go away, and assumptions 7994 // we made such as through app install filtering would now 7995 // have allowed apps on the device which aren't compatible 7996 // with it. Better to just have the restriction here, be 7997 // conservative, and create many fewer cases that can negatively 7998 // impact the user experience. 7999 final PackageSetting sysPs = mSettings 8000 .getDisabledSystemPkgLPr(pkg.packageName); 8001 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8002 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8003 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8004 allowed = true; 8005 break; 8006 } 8007 } 8008 } 8009 } else { 8010 allowed = true; 8011 } 8012 if (allowed) { 8013 if (!mSharedLibraries.containsKey(name)) { 8014 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8015 } else if (!name.equals(pkg.packageName)) { 8016 Slog.w(TAG, "Package " + pkg.packageName + " library " 8017 + name + " already exists; skipping"); 8018 } 8019 } else { 8020 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8021 + name + " that is not declared on system image; skipping"); 8022 } 8023 } 8024 if ((scanFlags & SCAN_BOOTING) == 0) { 8025 // If we are not booting, we need to update any applications 8026 // that are clients of our shared library. If we are booting, 8027 // this will all be done once the scan is complete. 8028 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8029 } 8030 } 8031 } 8032 } 8033 8034 // Request the ActivityManager to kill the process(only for existing packages) 8035 // so that we do not end up in a confused state while the user is still using the older 8036 // version of the application while the new one gets installed. 8037 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8038 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8039 if (killApp) { 8040 if (isReplacing) { 8041 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8042 8043 killApplication(pkg.applicationInfo.packageName, 8044 pkg.applicationInfo.uid, "replace pkg"); 8045 8046 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8047 } 8048 } 8049 8050 // Also need to kill any apps that are dependent on the library. 8051 if (clientLibPkgs != null) { 8052 for (int i=0; i<clientLibPkgs.size(); i++) { 8053 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8054 killApplication(clientPkg.applicationInfo.packageName, 8055 clientPkg.applicationInfo.uid, "update lib"); 8056 } 8057 } 8058 8059 // Make sure we're not adding any bogus keyset info 8060 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8061 ksms.assertScannedPackageValid(pkg); 8062 8063 // writer 8064 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8065 8066 boolean createIdmapFailed = false; 8067 synchronized (mPackages) { 8068 // We don't expect installation to fail beyond this point 8069 8070 // Add the new setting to mSettings 8071 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8072 // Add the new setting to mPackages 8073 mPackages.put(pkg.applicationInfo.packageName, pkg); 8074 // Make sure we don't accidentally delete its data. 8075 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8076 while (iter.hasNext()) { 8077 PackageCleanItem item = iter.next(); 8078 if (pkgName.equals(item.packageName)) { 8079 iter.remove(); 8080 } 8081 } 8082 8083 // Take care of first install / last update times. 8084 if (currentTime != 0) { 8085 if (pkgSetting.firstInstallTime == 0) { 8086 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8087 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8088 pkgSetting.lastUpdateTime = currentTime; 8089 } 8090 } else if (pkgSetting.firstInstallTime == 0) { 8091 // We need *something*. Take time time stamp of the file. 8092 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8093 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8094 if (scanFileTime != pkgSetting.timeStamp) { 8095 // A package on the system image has changed; consider this 8096 // to be an update. 8097 pkgSetting.lastUpdateTime = scanFileTime; 8098 } 8099 } 8100 8101 // Add the package's KeySets to the global KeySetManagerService 8102 ksms.addScannedPackageLPw(pkg); 8103 8104 int N = pkg.providers.size(); 8105 StringBuilder r = null; 8106 int i; 8107 for (i=0; i<N; i++) { 8108 PackageParser.Provider p = pkg.providers.get(i); 8109 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8110 p.info.processName, pkg.applicationInfo.uid); 8111 mProviders.addProvider(p); 8112 p.syncable = p.info.isSyncable; 8113 if (p.info.authority != null) { 8114 String names[] = p.info.authority.split(";"); 8115 p.info.authority = null; 8116 for (int j = 0; j < names.length; j++) { 8117 if (j == 1 && p.syncable) { 8118 // We only want the first authority for a provider to possibly be 8119 // syncable, so if we already added this provider using a different 8120 // authority clear the syncable flag. We copy the provider before 8121 // changing it because the mProviders object contains a reference 8122 // to a provider that we don't want to change. 8123 // Only do this for the second authority since the resulting provider 8124 // object can be the same for all future authorities for this provider. 8125 p = new PackageParser.Provider(p); 8126 p.syncable = false; 8127 } 8128 if (!mProvidersByAuthority.containsKey(names[j])) { 8129 mProvidersByAuthority.put(names[j], p); 8130 if (p.info.authority == null) { 8131 p.info.authority = names[j]; 8132 } else { 8133 p.info.authority = p.info.authority + ";" + names[j]; 8134 } 8135 if (DEBUG_PACKAGE_SCANNING) { 8136 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8137 Log.d(TAG, "Registered content provider: " + names[j] 8138 + ", className = " + p.info.name + ", isSyncable = " 8139 + p.info.isSyncable); 8140 } 8141 } else { 8142 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8143 Slog.w(TAG, "Skipping provider name " + names[j] + 8144 " (in package " + pkg.applicationInfo.packageName + 8145 "): name already used by " 8146 + ((other != null && other.getComponentName() != null) 8147 ? other.getComponentName().getPackageName() : "?")); 8148 } 8149 } 8150 } 8151 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8152 if (r == null) { 8153 r = new StringBuilder(256); 8154 } else { 8155 r.append(' '); 8156 } 8157 r.append(p.info.name); 8158 } 8159 } 8160 if (r != null) { 8161 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8162 } 8163 8164 N = pkg.services.size(); 8165 r = null; 8166 for (i=0; i<N; i++) { 8167 PackageParser.Service s = pkg.services.get(i); 8168 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8169 s.info.processName, pkg.applicationInfo.uid); 8170 mServices.addService(s); 8171 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8172 if (r == null) { 8173 r = new StringBuilder(256); 8174 } else { 8175 r.append(' '); 8176 } 8177 r.append(s.info.name); 8178 } 8179 } 8180 if (r != null) { 8181 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8182 } 8183 8184 N = pkg.receivers.size(); 8185 r = null; 8186 for (i=0; i<N; i++) { 8187 PackageParser.Activity a = pkg.receivers.get(i); 8188 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8189 a.info.processName, pkg.applicationInfo.uid); 8190 mReceivers.addActivity(a, "receiver"); 8191 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8192 if (r == null) { 8193 r = new StringBuilder(256); 8194 } else { 8195 r.append(' '); 8196 } 8197 r.append(a.info.name); 8198 } 8199 } 8200 if (r != null) { 8201 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8202 } 8203 8204 N = pkg.activities.size(); 8205 r = null; 8206 for (i=0; i<N; i++) { 8207 PackageParser.Activity a = pkg.activities.get(i); 8208 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8209 a.info.processName, pkg.applicationInfo.uid); 8210 mActivities.addActivity(a, "activity"); 8211 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8212 if (r == null) { 8213 r = new StringBuilder(256); 8214 } else { 8215 r.append(' '); 8216 } 8217 r.append(a.info.name); 8218 } 8219 } 8220 if (r != null) { 8221 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8222 } 8223 8224 N = pkg.permissionGroups.size(); 8225 r = null; 8226 for (i=0; i<N; i++) { 8227 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8228 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8229 if (cur == null) { 8230 mPermissionGroups.put(pg.info.name, pg); 8231 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8232 if (r == null) { 8233 r = new StringBuilder(256); 8234 } else { 8235 r.append(' '); 8236 } 8237 r.append(pg.info.name); 8238 } 8239 } else { 8240 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8241 + pg.info.packageName + " ignored: original from " 8242 + cur.info.packageName); 8243 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8244 if (r == null) { 8245 r = new StringBuilder(256); 8246 } else { 8247 r.append(' '); 8248 } 8249 r.append("DUP:"); 8250 r.append(pg.info.name); 8251 } 8252 } 8253 } 8254 if (r != null) { 8255 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8256 } 8257 8258 N = pkg.permissions.size(); 8259 r = null; 8260 for (i=0; i<N; i++) { 8261 PackageParser.Permission p = pkg.permissions.get(i); 8262 8263 // Assume by default that we did not install this permission into the system. 8264 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8265 8266 // Now that permission groups have a special meaning, we ignore permission 8267 // groups for legacy apps to prevent unexpected behavior. In particular, 8268 // permissions for one app being granted to someone just becase they happen 8269 // to be in a group defined by another app (before this had no implications). 8270 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8271 p.group = mPermissionGroups.get(p.info.group); 8272 // Warn for a permission in an unknown group. 8273 if (p.info.group != null && p.group == null) { 8274 Slog.w(TAG, "Permission " + p.info.name + " from package " 8275 + p.info.packageName + " in an unknown group " + p.info.group); 8276 } 8277 } 8278 8279 ArrayMap<String, BasePermission> permissionMap = 8280 p.tree ? mSettings.mPermissionTrees 8281 : mSettings.mPermissions; 8282 BasePermission bp = permissionMap.get(p.info.name); 8283 8284 // Allow system apps to redefine non-system permissions 8285 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8286 final boolean currentOwnerIsSystem = (bp.perm != null 8287 && isSystemApp(bp.perm.owner)); 8288 if (isSystemApp(p.owner)) { 8289 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8290 // It's a built-in permission and no owner, take ownership now 8291 bp.packageSetting = pkgSetting; 8292 bp.perm = p; 8293 bp.uid = pkg.applicationInfo.uid; 8294 bp.sourcePackage = p.info.packageName; 8295 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8296 } else if (!currentOwnerIsSystem) { 8297 String msg = "New decl " + p.owner + " of permission " 8298 + p.info.name + " is system; overriding " + bp.sourcePackage; 8299 reportSettingsProblem(Log.WARN, msg); 8300 bp = null; 8301 } 8302 } 8303 } 8304 8305 if (bp == null) { 8306 bp = new BasePermission(p.info.name, p.info.packageName, 8307 BasePermission.TYPE_NORMAL); 8308 permissionMap.put(p.info.name, bp); 8309 } 8310 8311 if (bp.perm == null) { 8312 if (bp.sourcePackage == null 8313 || bp.sourcePackage.equals(p.info.packageName)) { 8314 BasePermission tree = findPermissionTreeLP(p.info.name); 8315 if (tree == null 8316 || tree.sourcePackage.equals(p.info.packageName)) { 8317 bp.packageSetting = pkgSetting; 8318 bp.perm = p; 8319 bp.uid = pkg.applicationInfo.uid; 8320 bp.sourcePackage = p.info.packageName; 8321 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8322 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8323 if (r == null) { 8324 r = new StringBuilder(256); 8325 } else { 8326 r.append(' '); 8327 } 8328 r.append(p.info.name); 8329 } 8330 } else { 8331 Slog.w(TAG, "Permission " + p.info.name + " from package " 8332 + p.info.packageName + " ignored: base tree " 8333 + tree.name + " is from package " 8334 + tree.sourcePackage); 8335 } 8336 } else { 8337 Slog.w(TAG, "Permission " + p.info.name + " from package " 8338 + p.info.packageName + " ignored: original from " 8339 + bp.sourcePackage); 8340 } 8341 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8342 if (r == null) { 8343 r = new StringBuilder(256); 8344 } else { 8345 r.append(' '); 8346 } 8347 r.append("DUP:"); 8348 r.append(p.info.name); 8349 } 8350 if (bp.perm == p) { 8351 bp.protectionLevel = p.info.protectionLevel; 8352 } 8353 } 8354 8355 if (r != null) { 8356 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8357 } 8358 8359 N = pkg.instrumentation.size(); 8360 r = null; 8361 for (i=0; i<N; i++) { 8362 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8363 a.info.packageName = pkg.applicationInfo.packageName; 8364 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8365 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8366 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8367 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8368 a.info.dataDir = pkg.applicationInfo.dataDir; 8369 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8370 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8371 8372 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8373 // need other information about the application, like the ABI and what not ? 8374 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8375 mInstrumentation.put(a.getComponentName(), a); 8376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8377 if (r == null) { 8378 r = new StringBuilder(256); 8379 } else { 8380 r.append(' '); 8381 } 8382 r.append(a.info.name); 8383 } 8384 } 8385 if (r != null) { 8386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8387 } 8388 8389 if (pkg.protectedBroadcasts != null) { 8390 N = pkg.protectedBroadcasts.size(); 8391 for (i=0; i<N; i++) { 8392 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8393 } 8394 } 8395 8396 pkgSetting.setTimeStamp(scanFileTime); 8397 8398 // Create idmap files for pairs of (packages, overlay packages). 8399 // Note: "android", ie framework-res.apk, is handled by native layers. 8400 if (pkg.mOverlayTarget != null) { 8401 // This is an overlay package. 8402 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8403 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8404 mOverlays.put(pkg.mOverlayTarget, 8405 new ArrayMap<String, PackageParser.Package>()); 8406 } 8407 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8408 map.put(pkg.packageName, pkg); 8409 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8410 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8411 createIdmapFailed = true; 8412 } 8413 } 8414 } else if (mOverlays.containsKey(pkg.packageName) && 8415 !pkg.packageName.equals("android")) { 8416 // This is a regular package, with one or more known overlay packages. 8417 createIdmapsForPackageLI(pkg); 8418 } 8419 } 8420 8421 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8422 8423 if (createIdmapFailed) { 8424 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8425 "scanPackageLI failed to createIdmap"); 8426 } 8427 return pkg; 8428 } 8429 8430 /** 8431 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8432 * is derived purely on the basis of the contents of {@code scanFile} and 8433 * {@code cpuAbiOverride}. 8434 * 8435 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8436 */ 8437 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8438 String cpuAbiOverride, boolean extractLibs) 8439 throws PackageManagerException { 8440 // TODO: We can probably be smarter about this stuff. For installed apps, 8441 // we can calculate this information at install time once and for all. For 8442 // system apps, we can probably assume that this information doesn't change 8443 // after the first boot scan. As things stand, we do lots of unnecessary work. 8444 8445 // Give ourselves some initial paths; we'll come back for another 8446 // pass once we've determined ABI below. 8447 setNativeLibraryPaths(pkg); 8448 8449 // We would never need to extract libs for forward-locked and external packages, 8450 // since the container service will do it for us. We shouldn't attempt to 8451 // extract libs from system app when it was not updated. 8452 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8453 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8454 extractLibs = false; 8455 } 8456 8457 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8458 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8459 8460 NativeLibraryHelper.Handle handle = null; 8461 try { 8462 handle = NativeLibraryHelper.Handle.create(pkg); 8463 // TODO(multiArch): This can be null for apps that didn't go through the 8464 // usual installation process. We can calculate it again, like we 8465 // do during install time. 8466 // 8467 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8468 // unnecessary. 8469 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8470 8471 // Null out the abis so that they can be recalculated. 8472 pkg.applicationInfo.primaryCpuAbi = null; 8473 pkg.applicationInfo.secondaryCpuAbi = null; 8474 if (isMultiArch(pkg.applicationInfo)) { 8475 // Warn if we've set an abiOverride for multi-lib packages.. 8476 // By definition, we need to copy both 32 and 64 bit libraries for 8477 // such packages. 8478 if (pkg.cpuAbiOverride != null 8479 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8480 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8481 } 8482 8483 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8484 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8485 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8486 if (extractLibs) { 8487 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8488 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8489 useIsaSpecificSubdirs); 8490 } else { 8491 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8492 } 8493 } 8494 8495 maybeThrowExceptionForMultiArchCopy( 8496 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8497 8498 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8499 if (extractLibs) { 8500 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8501 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8502 useIsaSpecificSubdirs); 8503 } else { 8504 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8505 } 8506 } 8507 8508 maybeThrowExceptionForMultiArchCopy( 8509 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8510 8511 if (abi64 >= 0) { 8512 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8513 } 8514 8515 if (abi32 >= 0) { 8516 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8517 if (abi64 >= 0) { 8518 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8519 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8520 pkg.applicationInfo.primaryCpuAbi = abi; 8521 } else { 8522 pkg.applicationInfo.secondaryCpuAbi = abi; 8523 } 8524 } else { 8525 pkg.applicationInfo.primaryCpuAbi = abi; 8526 } 8527 } 8528 8529 } else { 8530 String[] abiList = (cpuAbiOverride != null) ? 8531 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8532 8533 // Enable gross and lame hacks for apps that are built with old 8534 // SDK tools. We must scan their APKs for renderscript bitcode and 8535 // not launch them if it's present. Don't bother checking on devices 8536 // that don't have 64 bit support. 8537 boolean needsRenderScriptOverride = false; 8538 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8539 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8540 abiList = Build.SUPPORTED_32_BIT_ABIS; 8541 needsRenderScriptOverride = true; 8542 } 8543 8544 final int copyRet; 8545 if (extractLibs) { 8546 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8547 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8548 } else { 8549 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8550 } 8551 8552 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8553 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8554 "Error unpackaging native libs for app, errorCode=" + copyRet); 8555 } 8556 8557 if (copyRet >= 0) { 8558 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8559 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8560 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8561 } else if (needsRenderScriptOverride) { 8562 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8563 } 8564 } 8565 } catch (IOException ioe) { 8566 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8567 } finally { 8568 IoUtils.closeQuietly(handle); 8569 } 8570 8571 // Now that we've calculated the ABIs and determined if it's an internal app, 8572 // we will go ahead and populate the nativeLibraryPath. 8573 setNativeLibraryPaths(pkg); 8574 } 8575 8576 /** 8577 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8578 * i.e, so that all packages can be run inside a single process if required. 8579 * 8580 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8581 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8582 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8583 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8584 * updating a package that belongs to a shared user. 8585 * 8586 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8587 * adds unnecessary complexity. 8588 */ 8589 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8590 PackageParser.Package scannedPackage, boolean bootComplete) { 8591 String requiredInstructionSet = null; 8592 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8593 requiredInstructionSet = VMRuntime.getInstructionSet( 8594 scannedPackage.applicationInfo.primaryCpuAbi); 8595 } 8596 8597 PackageSetting requirer = null; 8598 for (PackageSetting ps : packagesForUser) { 8599 // If packagesForUser contains scannedPackage, we skip it. This will happen 8600 // when scannedPackage is an update of an existing package. Without this check, 8601 // we will never be able to change the ABI of any package belonging to a shared 8602 // user, even if it's compatible with other packages. 8603 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8604 if (ps.primaryCpuAbiString == null) { 8605 continue; 8606 } 8607 8608 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8609 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8610 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8611 // this but there's not much we can do. 8612 String errorMessage = "Instruction set mismatch, " 8613 + ((requirer == null) ? "[caller]" : requirer) 8614 + " requires " + requiredInstructionSet + " whereas " + ps 8615 + " requires " + instructionSet; 8616 Slog.w(TAG, errorMessage); 8617 } 8618 8619 if (requiredInstructionSet == null) { 8620 requiredInstructionSet = instructionSet; 8621 requirer = ps; 8622 } 8623 } 8624 } 8625 8626 if (requiredInstructionSet != null) { 8627 String adjustedAbi; 8628 if (requirer != null) { 8629 // requirer != null implies that either scannedPackage was null or that scannedPackage 8630 // did not require an ABI, in which case we have to adjust scannedPackage to match 8631 // the ABI of the set (which is the same as requirer's ABI) 8632 adjustedAbi = requirer.primaryCpuAbiString; 8633 if (scannedPackage != null) { 8634 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8635 } 8636 } else { 8637 // requirer == null implies that we're updating all ABIs in the set to 8638 // match scannedPackage. 8639 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8640 } 8641 8642 for (PackageSetting ps : packagesForUser) { 8643 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8644 if (ps.primaryCpuAbiString != null) { 8645 continue; 8646 } 8647 8648 ps.primaryCpuAbiString = adjustedAbi; 8649 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8650 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8651 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8652 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8653 + " (requirer=" 8654 + (requirer == null ? "null" : requirer.pkg.packageName) 8655 + ", scannedPackage=" 8656 + (scannedPackage != null ? scannedPackage.packageName : "null") 8657 + ")"); 8658 try { 8659 mInstaller.rmdex(ps.codePathString, 8660 getDexCodeInstructionSet(getPreferredInstructionSet())); 8661 } catch (InstallerException ignored) { 8662 } 8663 } 8664 } 8665 } 8666 } 8667 } 8668 8669 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8670 synchronized (mPackages) { 8671 mResolverReplaced = true; 8672 // Set up information for custom user intent resolution activity. 8673 mResolveActivity.applicationInfo = pkg.applicationInfo; 8674 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8675 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8676 mResolveActivity.processName = pkg.applicationInfo.packageName; 8677 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8678 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8679 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8680 mResolveActivity.theme = 0; 8681 mResolveActivity.exported = true; 8682 mResolveActivity.enabled = true; 8683 mResolveInfo.activityInfo = mResolveActivity; 8684 mResolveInfo.priority = 0; 8685 mResolveInfo.preferredOrder = 0; 8686 mResolveInfo.match = 0; 8687 mResolveComponentName = mCustomResolverComponentName; 8688 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8689 mResolveComponentName); 8690 } 8691 } 8692 8693 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8694 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8695 8696 // Set up information for ephemeral installer activity 8697 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8698 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8699 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8700 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8701 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8702 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8703 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8704 mEphemeralInstallerActivity.theme = 0; 8705 mEphemeralInstallerActivity.exported = true; 8706 mEphemeralInstallerActivity.enabled = true; 8707 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8708 mEphemeralInstallerInfo.priority = 0; 8709 mEphemeralInstallerInfo.preferredOrder = 0; 8710 mEphemeralInstallerInfo.match = 0; 8711 8712 if (DEBUG_EPHEMERAL) { 8713 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8714 } 8715 } 8716 8717 private static String calculateBundledApkRoot(final String codePathString) { 8718 final File codePath = new File(codePathString); 8719 final File codeRoot; 8720 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8721 codeRoot = Environment.getRootDirectory(); 8722 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8723 codeRoot = Environment.getOemDirectory(); 8724 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8725 codeRoot = Environment.getVendorDirectory(); 8726 } else { 8727 // Unrecognized code path; take its top real segment as the apk root: 8728 // e.g. /something/app/blah.apk => /something 8729 try { 8730 File f = codePath.getCanonicalFile(); 8731 File parent = f.getParentFile(); // non-null because codePath is a file 8732 File tmp; 8733 while ((tmp = parent.getParentFile()) != null) { 8734 f = parent; 8735 parent = tmp; 8736 } 8737 codeRoot = f; 8738 Slog.w(TAG, "Unrecognized code path " 8739 + codePath + " - using " + codeRoot); 8740 } catch (IOException e) { 8741 // Can't canonicalize the code path -- shenanigans? 8742 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8743 return Environment.getRootDirectory().getPath(); 8744 } 8745 } 8746 return codeRoot.getPath(); 8747 } 8748 8749 /** 8750 * Derive and set the location of native libraries for the given package, 8751 * which varies depending on where and how the package was installed. 8752 */ 8753 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8754 final ApplicationInfo info = pkg.applicationInfo; 8755 final String codePath = pkg.codePath; 8756 final File codeFile = new File(codePath); 8757 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8758 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8759 8760 info.nativeLibraryRootDir = null; 8761 info.nativeLibraryRootRequiresIsa = false; 8762 info.nativeLibraryDir = null; 8763 info.secondaryNativeLibraryDir = null; 8764 8765 if (isApkFile(codeFile)) { 8766 // Monolithic install 8767 if (bundledApp) { 8768 // If "/system/lib64/apkname" exists, assume that is the per-package 8769 // native library directory to use; otherwise use "/system/lib/apkname". 8770 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8771 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8772 getPrimaryInstructionSet(info)); 8773 8774 // This is a bundled system app so choose the path based on the ABI. 8775 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8776 // is just the default path. 8777 final String apkName = deriveCodePathName(codePath); 8778 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8779 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8780 apkName).getAbsolutePath(); 8781 8782 if (info.secondaryCpuAbi != null) { 8783 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8784 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8785 secondaryLibDir, apkName).getAbsolutePath(); 8786 } 8787 } else if (asecApp) { 8788 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8789 .getAbsolutePath(); 8790 } else { 8791 final String apkName = deriveCodePathName(codePath); 8792 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8793 .getAbsolutePath(); 8794 } 8795 8796 info.nativeLibraryRootRequiresIsa = false; 8797 info.nativeLibraryDir = info.nativeLibraryRootDir; 8798 } else { 8799 // Cluster install 8800 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8801 info.nativeLibraryRootRequiresIsa = true; 8802 8803 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8804 getPrimaryInstructionSet(info)).getAbsolutePath(); 8805 8806 if (info.secondaryCpuAbi != null) { 8807 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8808 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8809 } 8810 } 8811 } 8812 8813 /** 8814 * Calculate the abis and roots for a bundled app. These can uniquely 8815 * be determined from the contents of the system partition, i.e whether 8816 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8817 * of this information, and instead assume that the system was built 8818 * sensibly. 8819 */ 8820 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8821 PackageSetting pkgSetting) { 8822 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8823 8824 // If "/system/lib64/apkname" exists, assume that is the per-package 8825 // native library directory to use; otherwise use "/system/lib/apkname". 8826 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8827 setBundledAppAbi(pkg, apkRoot, apkName); 8828 // pkgSetting might be null during rescan following uninstall of updates 8829 // to a bundled app, so accommodate that possibility. The settings in 8830 // that case will be established later from the parsed package. 8831 // 8832 // If the settings aren't null, sync them up with what we've just derived. 8833 // note that apkRoot isn't stored in the package settings. 8834 if (pkgSetting != null) { 8835 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8836 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8837 } 8838 } 8839 8840 /** 8841 * Deduces the ABI of a bundled app and sets the relevant fields on the 8842 * parsed pkg object. 8843 * 8844 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8845 * under which system libraries are installed. 8846 * @param apkName the name of the installed package. 8847 */ 8848 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8849 final File codeFile = new File(pkg.codePath); 8850 8851 final boolean has64BitLibs; 8852 final boolean has32BitLibs; 8853 if (isApkFile(codeFile)) { 8854 // Monolithic install 8855 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8856 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8857 } else { 8858 // Cluster install 8859 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8860 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8861 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8862 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8863 has64BitLibs = (new File(rootDir, isa)).exists(); 8864 } else { 8865 has64BitLibs = false; 8866 } 8867 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8868 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8869 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8870 has32BitLibs = (new File(rootDir, isa)).exists(); 8871 } else { 8872 has32BitLibs = false; 8873 } 8874 } 8875 8876 if (has64BitLibs && !has32BitLibs) { 8877 // The package has 64 bit libs, but not 32 bit libs. Its primary 8878 // ABI should be 64 bit. We can safely assume here that the bundled 8879 // native libraries correspond to the most preferred ABI in the list. 8880 8881 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8882 pkg.applicationInfo.secondaryCpuAbi = null; 8883 } else if (has32BitLibs && !has64BitLibs) { 8884 // The package has 32 bit libs but not 64 bit libs. Its primary 8885 // ABI should be 32 bit. 8886 8887 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8888 pkg.applicationInfo.secondaryCpuAbi = null; 8889 } else if (has32BitLibs && has64BitLibs) { 8890 // The application has both 64 and 32 bit bundled libraries. We check 8891 // here that the app declares multiArch support, and warn if it doesn't. 8892 // 8893 // We will be lenient here and record both ABIs. The primary will be the 8894 // ABI that's higher on the list, i.e, a device that's configured to prefer 8895 // 64 bit apps will see a 64 bit primary ABI, 8896 8897 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8898 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8899 } 8900 8901 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8902 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8903 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8904 } else { 8905 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8906 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8907 } 8908 } else { 8909 pkg.applicationInfo.primaryCpuAbi = null; 8910 pkg.applicationInfo.secondaryCpuAbi = null; 8911 } 8912 } 8913 8914 private void killPackage(PackageParser.Package pkg, String reason) { 8915 // Kill the parent package 8916 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8917 // Kill the child packages 8918 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8919 for (int i = 0; i < childCount; i++) { 8920 PackageParser.Package childPkg = pkg.childPackages.get(i); 8921 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8922 } 8923 } 8924 8925 private void killApplication(String pkgName, int appId, String reason) { 8926 // Request the ActivityManager to kill the process(only for existing packages) 8927 // so that we do not end up in a confused state while the user is still using the older 8928 // version of the application while the new one gets installed. 8929 IActivityManager am = ActivityManagerNative.getDefault(); 8930 if (am != null) { 8931 try { 8932 am.killApplicationWithAppId(pkgName, appId, reason); 8933 } catch (RemoteException e) { 8934 } 8935 } 8936 } 8937 8938 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8939 // Remove the parent package setting 8940 PackageSetting ps = (PackageSetting) pkg.mExtras; 8941 if (ps != null) { 8942 removePackageLI(ps, chatty); 8943 } 8944 // Remove the child package setting 8945 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8946 for (int i = 0; i < childCount; i++) { 8947 PackageParser.Package childPkg = pkg.childPackages.get(i); 8948 ps = (PackageSetting) childPkg.mExtras; 8949 if (ps != null) { 8950 removePackageLI(ps, chatty); 8951 } 8952 } 8953 } 8954 8955 void removePackageLI(PackageSetting ps, boolean chatty) { 8956 if (DEBUG_INSTALL) { 8957 if (chatty) 8958 Log.d(TAG, "Removing package " + ps.name); 8959 } 8960 8961 // writer 8962 synchronized (mPackages) { 8963 mPackages.remove(ps.name); 8964 final PackageParser.Package pkg = ps.pkg; 8965 if (pkg != null) { 8966 cleanPackageDataStructuresLILPw(pkg, chatty); 8967 } 8968 } 8969 } 8970 8971 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8972 if (DEBUG_INSTALL) { 8973 if (chatty) 8974 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8975 } 8976 8977 // writer 8978 synchronized (mPackages) { 8979 // Remove the parent package 8980 mPackages.remove(pkg.applicationInfo.packageName); 8981 cleanPackageDataStructuresLILPw(pkg, chatty); 8982 8983 // Remove the child packages 8984 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8985 for (int i = 0; i < childCount; i++) { 8986 PackageParser.Package childPkg = pkg.childPackages.get(i); 8987 mPackages.remove(childPkg.applicationInfo.packageName); 8988 cleanPackageDataStructuresLILPw(childPkg, chatty); 8989 } 8990 } 8991 } 8992 8993 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8994 int N = pkg.providers.size(); 8995 StringBuilder r = null; 8996 int i; 8997 for (i=0; i<N; i++) { 8998 PackageParser.Provider p = pkg.providers.get(i); 8999 mProviders.removeProvider(p); 9000 if (p.info.authority == null) { 9001 9002 /* There was another ContentProvider with this authority when 9003 * this app was installed so this authority is null, 9004 * Ignore it as we don't have to unregister the provider. 9005 */ 9006 continue; 9007 } 9008 String names[] = p.info.authority.split(";"); 9009 for (int j = 0; j < names.length; j++) { 9010 if (mProvidersByAuthority.get(names[j]) == p) { 9011 mProvidersByAuthority.remove(names[j]); 9012 if (DEBUG_REMOVE) { 9013 if (chatty) 9014 Log.d(TAG, "Unregistered content provider: " + names[j] 9015 + ", className = " + p.info.name + ", isSyncable = " 9016 + p.info.isSyncable); 9017 } 9018 } 9019 } 9020 if (DEBUG_REMOVE && chatty) { 9021 if (r == null) { 9022 r = new StringBuilder(256); 9023 } else { 9024 r.append(' '); 9025 } 9026 r.append(p.info.name); 9027 } 9028 } 9029 if (r != null) { 9030 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9031 } 9032 9033 N = pkg.services.size(); 9034 r = null; 9035 for (i=0; i<N; i++) { 9036 PackageParser.Service s = pkg.services.get(i); 9037 mServices.removeService(s); 9038 if (chatty) { 9039 if (r == null) { 9040 r = new StringBuilder(256); 9041 } else { 9042 r.append(' '); 9043 } 9044 r.append(s.info.name); 9045 } 9046 } 9047 if (r != null) { 9048 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9049 } 9050 9051 N = pkg.receivers.size(); 9052 r = null; 9053 for (i=0; i<N; i++) { 9054 PackageParser.Activity a = pkg.receivers.get(i); 9055 mReceivers.removeActivity(a, "receiver"); 9056 if (DEBUG_REMOVE && chatty) { 9057 if (r == null) { 9058 r = new StringBuilder(256); 9059 } else { 9060 r.append(' '); 9061 } 9062 r.append(a.info.name); 9063 } 9064 } 9065 if (r != null) { 9066 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9067 } 9068 9069 N = pkg.activities.size(); 9070 r = null; 9071 for (i=0; i<N; i++) { 9072 PackageParser.Activity a = pkg.activities.get(i); 9073 mActivities.removeActivity(a, "activity"); 9074 if (DEBUG_REMOVE && chatty) { 9075 if (r == null) { 9076 r = new StringBuilder(256); 9077 } else { 9078 r.append(' '); 9079 } 9080 r.append(a.info.name); 9081 } 9082 } 9083 if (r != null) { 9084 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9085 } 9086 9087 N = pkg.permissions.size(); 9088 r = null; 9089 for (i=0; i<N; i++) { 9090 PackageParser.Permission p = pkg.permissions.get(i); 9091 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9092 if (bp == null) { 9093 bp = mSettings.mPermissionTrees.get(p.info.name); 9094 } 9095 if (bp != null && bp.perm == p) { 9096 bp.perm = null; 9097 if (DEBUG_REMOVE && chatty) { 9098 if (r == null) { 9099 r = new StringBuilder(256); 9100 } else { 9101 r.append(' '); 9102 } 9103 r.append(p.info.name); 9104 } 9105 } 9106 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9107 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9108 if (appOpPkgs != null) { 9109 appOpPkgs.remove(pkg.packageName); 9110 } 9111 } 9112 } 9113 if (r != null) { 9114 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9115 } 9116 9117 N = pkg.requestedPermissions.size(); 9118 r = null; 9119 for (i=0; i<N; i++) { 9120 String perm = pkg.requestedPermissions.get(i); 9121 BasePermission bp = mSettings.mPermissions.get(perm); 9122 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9123 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9124 if (appOpPkgs != null) { 9125 appOpPkgs.remove(pkg.packageName); 9126 if (appOpPkgs.isEmpty()) { 9127 mAppOpPermissionPackages.remove(perm); 9128 } 9129 } 9130 } 9131 } 9132 if (r != null) { 9133 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9134 } 9135 9136 N = pkg.instrumentation.size(); 9137 r = null; 9138 for (i=0; i<N; i++) { 9139 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9140 mInstrumentation.remove(a.getComponentName()); 9141 if (DEBUG_REMOVE && chatty) { 9142 if (r == null) { 9143 r = new StringBuilder(256); 9144 } else { 9145 r.append(' '); 9146 } 9147 r.append(a.info.name); 9148 } 9149 } 9150 if (r != null) { 9151 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9152 } 9153 9154 r = null; 9155 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9156 // Only system apps can hold shared libraries. 9157 if (pkg.libraryNames != null) { 9158 for (i=0; i<pkg.libraryNames.size(); i++) { 9159 String name = pkg.libraryNames.get(i); 9160 SharedLibraryEntry cur = mSharedLibraries.get(name); 9161 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9162 mSharedLibraries.remove(name); 9163 if (DEBUG_REMOVE && chatty) { 9164 if (r == null) { 9165 r = new StringBuilder(256); 9166 } else { 9167 r.append(' '); 9168 } 9169 r.append(name); 9170 } 9171 } 9172 } 9173 } 9174 } 9175 if (r != null) { 9176 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9177 } 9178 } 9179 9180 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9181 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9182 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9183 return true; 9184 } 9185 } 9186 return false; 9187 } 9188 9189 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9190 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9191 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9192 9193 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9194 // Update the parent permissions 9195 updatePermissionsLPw(pkg.packageName, pkg, flags); 9196 // Update the child permissions 9197 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9198 for (int i = 0; i < childCount; i++) { 9199 PackageParser.Package childPkg = pkg.childPackages.get(i); 9200 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9201 } 9202 } 9203 9204 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9205 int flags) { 9206 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9207 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9208 } 9209 9210 private void updatePermissionsLPw(String changingPkg, 9211 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9212 // Make sure there are no dangling permission trees. 9213 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9214 while (it.hasNext()) { 9215 final BasePermission bp = it.next(); 9216 if (bp.packageSetting == null) { 9217 // We may not yet have parsed the package, so just see if 9218 // we still know about its settings. 9219 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9220 } 9221 if (bp.packageSetting == null) { 9222 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9223 + " from package " + bp.sourcePackage); 9224 it.remove(); 9225 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9226 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9227 Slog.i(TAG, "Removing old permission tree: " + bp.name 9228 + " from package " + bp.sourcePackage); 9229 flags |= UPDATE_PERMISSIONS_ALL; 9230 it.remove(); 9231 } 9232 } 9233 } 9234 9235 // Make sure all dynamic permissions have been assigned to a package, 9236 // and make sure there are no dangling permissions. 9237 it = mSettings.mPermissions.values().iterator(); 9238 while (it.hasNext()) { 9239 final BasePermission bp = it.next(); 9240 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9241 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9242 + bp.name + " pkg=" + bp.sourcePackage 9243 + " info=" + bp.pendingInfo); 9244 if (bp.packageSetting == null && bp.pendingInfo != null) { 9245 final BasePermission tree = findPermissionTreeLP(bp.name); 9246 if (tree != null && tree.perm != null) { 9247 bp.packageSetting = tree.packageSetting; 9248 bp.perm = new PackageParser.Permission(tree.perm.owner, 9249 new PermissionInfo(bp.pendingInfo)); 9250 bp.perm.info.packageName = tree.perm.info.packageName; 9251 bp.perm.info.name = bp.name; 9252 bp.uid = tree.uid; 9253 } 9254 } 9255 } 9256 if (bp.packageSetting == null) { 9257 // We may not yet have parsed the package, so just see if 9258 // we still know about its settings. 9259 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9260 } 9261 if (bp.packageSetting == null) { 9262 Slog.w(TAG, "Removing dangling permission: " + bp.name 9263 + " from package " + bp.sourcePackage); 9264 it.remove(); 9265 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9266 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9267 Slog.i(TAG, "Removing old permission: " + bp.name 9268 + " from package " + bp.sourcePackage); 9269 flags |= UPDATE_PERMISSIONS_ALL; 9270 it.remove(); 9271 } 9272 } 9273 } 9274 9275 // Now update the permissions for all packages, in particular 9276 // replace the granted permissions of the system packages. 9277 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9278 for (PackageParser.Package pkg : mPackages.values()) { 9279 if (pkg != pkgInfo) { 9280 // Only replace for packages on requested volume 9281 final String volumeUuid = getVolumeUuidForPackage(pkg); 9282 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9283 && Objects.equals(replaceVolumeUuid, volumeUuid); 9284 grantPermissionsLPw(pkg, replace, changingPkg); 9285 } 9286 } 9287 } 9288 9289 if (pkgInfo != null) { 9290 // Only replace for packages on requested volume 9291 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9292 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9293 && Objects.equals(replaceVolumeUuid, volumeUuid); 9294 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9295 } 9296 } 9297 9298 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9299 String packageOfInterest) { 9300 // IMPORTANT: There are two types of permissions: install and runtime. 9301 // Install time permissions are granted when the app is installed to 9302 // all device users and users added in the future. Runtime permissions 9303 // are granted at runtime explicitly to specific users. Normal and signature 9304 // protected permissions are install time permissions. Dangerous permissions 9305 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9306 // otherwise they are runtime permissions. This function does not manage 9307 // runtime permissions except for the case an app targeting Lollipop MR1 9308 // being upgraded to target a newer SDK, in which case dangerous permissions 9309 // are transformed from install time to runtime ones. 9310 9311 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9312 if (ps == null) { 9313 return; 9314 } 9315 9316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9317 9318 PermissionsState permissionsState = ps.getPermissionsState(); 9319 PermissionsState origPermissions = permissionsState; 9320 9321 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9322 9323 boolean runtimePermissionsRevoked = false; 9324 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9325 9326 boolean changedInstallPermission = false; 9327 9328 if (replace) { 9329 ps.installPermissionsFixed = false; 9330 if (!ps.isSharedUser()) { 9331 origPermissions = new PermissionsState(permissionsState); 9332 permissionsState.reset(); 9333 } else { 9334 // We need to know only about runtime permission changes since the 9335 // calling code always writes the install permissions state but 9336 // the runtime ones are written only if changed. The only cases of 9337 // changed runtime permissions here are promotion of an install to 9338 // runtime and revocation of a runtime from a shared user. 9339 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9340 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9341 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9342 runtimePermissionsRevoked = true; 9343 } 9344 } 9345 } 9346 9347 permissionsState.setGlobalGids(mGlobalGids); 9348 9349 final int N = pkg.requestedPermissions.size(); 9350 for (int i=0; i<N; i++) { 9351 final String name = pkg.requestedPermissions.get(i); 9352 final BasePermission bp = mSettings.mPermissions.get(name); 9353 9354 if (DEBUG_INSTALL) { 9355 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9356 } 9357 9358 if (bp == null || bp.packageSetting == null) { 9359 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9360 Slog.w(TAG, "Unknown permission " + name 9361 + " in package " + pkg.packageName); 9362 } 9363 continue; 9364 } 9365 9366 final String perm = bp.name; 9367 boolean allowedSig = false; 9368 int grant = GRANT_DENIED; 9369 9370 // Keep track of app op permissions. 9371 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9372 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9373 if (pkgs == null) { 9374 pkgs = new ArraySet<>(); 9375 mAppOpPermissionPackages.put(bp.name, pkgs); 9376 } 9377 pkgs.add(pkg.packageName); 9378 } 9379 9380 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9381 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9382 >= Build.VERSION_CODES.M; 9383 switch (level) { 9384 case PermissionInfo.PROTECTION_NORMAL: { 9385 // For all apps normal permissions are install time ones. 9386 grant = GRANT_INSTALL; 9387 } break; 9388 9389 case PermissionInfo.PROTECTION_DANGEROUS: { 9390 // If a permission review is required for legacy apps we represent 9391 // their permissions as always granted runtime ones since we need 9392 // to keep the review required permission flag per user while an 9393 // install permission's state is shared across all users. 9394 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9395 // For legacy apps dangerous permissions are install time ones. 9396 grant = GRANT_INSTALL; 9397 } else if (origPermissions.hasInstallPermission(bp.name)) { 9398 // For legacy apps that became modern, install becomes runtime. 9399 grant = GRANT_UPGRADE; 9400 } else if (mPromoteSystemApps 9401 && isSystemApp(ps) 9402 && mExistingSystemPackages.contains(ps.name)) { 9403 // For legacy system apps, install becomes runtime. 9404 // We cannot check hasInstallPermission() for system apps since those 9405 // permissions were granted implicitly and not persisted pre-M. 9406 grant = GRANT_UPGRADE; 9407 } else { 9408 // For modern apps keep runtime permissions unchanged. 9409 grant = GRANT_RUNTIME; 9410 } 9411 } break; 9412 9413 case PermissionInfo.PROTECTION_SIGNATURE: { 9414 // For all apps signature permissions are install time ones. 9415 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9416 if (allowedSig) { 9417 grant = GRANT_INSTALL; 9418 } 9419 } break; 9420 } 9421 9422 if (DEBUG_INSTALL) { 9423 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9424 } 9425 9426 if (grant != GRANT_DENIED) { 9427 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9428 // If this is an existing, non-system package, then 9429 // we can't add any new permissions to it. 9430 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9431 // Except... if this is a permission that was added 9432 // to the platform (note: need to only do this when 9433 // updating the platform). 9434 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9435 grant = GRANT_DENIED; 9436 } 9437 } 9438 } 9439 9440 switch (grant) { 9441 case GRANT_INSTALL: { 9442 // Revoke this as runtime permission to handle the case of 9443 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9444 for (int userId : UserManagerService.getInstance().getUserIds()) { 9445 if (origPermissions.getRuntimePermissionState( 9446 bp.name, userId) != null) { 9447 // Revoke the runtime permission and clear the flags. 9448 origPermissions.revokeRuntimePermission(bp, userId); 9449 origPermissions.updatePermissionFlags(bp, userId, 9450 PackageManager.MASK_PERMISSION_FLAGS, 0); 9451 // If we revoked a permission permission, we have to write. 9452 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9453 changedRuntimePermissionUserIds, userId); 9454 } 9455 } 9456 // Grant an install permission. 9457 if (permissionsState.grantInstallPermission(bp) != 9458 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9459 changedInstallPermission = true; 9460 } 9461 } break; 9462 9463 case GRANT_RUNTIME: { 9464 // Grant previously granted runtime permissions. 9465 for (int userId : UserManagerService.getInstance().getUserIds()) { 9466 PermissionState permissionState = origPermissions 9467 .getRuntimePermissionState(bp.name, userId); 9468 int flags = permissionState != null 9469 ? permissionState.getFlags() : 0; 9470 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9471 if (permissionsState.grantRuntimePermission(bp, userId) == 9472 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9473 // If we cannot put the permission as it was, we have to write. 9474 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9475 changedRuntimePermissionUserIds, userId); 9476 } 9477 // If the app supports runtime permissions no need for a review. 9478 if (Build.PERMISSIONS_REVIEW_REQUIRED 9479 && appSupportsRuntimePermissions 9480 && (flags & PackageManager 9481 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9482 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9483 // Since we changed the flags, we have to write. 9484 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9485 changedRuntimePermissionUserIds, userId); 9486 } 9487 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9488 && !appSupportsRuntimePermissions) { 9489 // For legacy apps that need a permission review, every new 9490 // runtime permission is granted but it is pending a review. 9491 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9492 permissionsState.grantRuntimePermission(bp, userId); 9493 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9494 // We changed the permission and flags, hence have to write. 9495 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9496 changedRuntimePermissionUserIds, userId); 9497 } 9498 } 9499 // Propagate the permission flags. 9500 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9501 } 9502 } break; 9503 9504 case GRANT_UPGRADE: { 9505 // Grant runtime permissions for a previously held install permission. 9506 PermissionState permissionState = origPermissions 9507 .getInstallPermissionState(bp.name); 9508 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9509 9510 if (origPermissions.revokeInstallPermission(bp) 9511 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9512 // We will be transferring the permission flags, so clear them. 9513 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9514 PackageManager.MASK_PERMISSION_FLAGS, 0); 9515 changedInstallPermission = true; 9516 } 9517 9518 // If the permission is not to be promoted to runtime we ignore it and 9519 // also its other flags as they are not applicable to install permissions. 9520 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9521 for (int userId : currentUserIds) { 9522 if (permissionsState.grantRuntimePermission(bp, userId) != 9523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9524 // Transfer the permission flags. 9525 permissionsState.updatePermissionFlags(bp, userId, 9526 flags, flags); 9527 // If we granted the permission, we have to write. 9528 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9529 changedRuntimePermissionUserIds, userId); 9530 } 9531 } 9532 } 9533 } break; 9534 9535 default: { 9536 if (packageOfInterest == null 9537 || packageOfInterest.equals(pkg.packageName)) { 9538 Slog.w(TAG, "Not granting permission " + perm 9539 + " to package " + pkg.packageName 9540 + " because it was previously installed without"); 9541 } 9542 } break; 9543 } 9544 } else { 9545 if (permissionsState.revokeInstallPermission(bp) != 9546 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9547 // Also drop the permission flags. 9548 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9549 PackageManager.MASK_PERMISSION_FLAGS, 0); 9550 changedInstallPermission = true; 9551 Slog.i(TAG, "Un-granting permission " + perm 9552 + " from package " + pkg.packageName 9553 + " (protectionLevel=" + bp.protectionLevel 9554 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9555 + ")"); 9556 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9557 // Don't print warning for app op permissions, since it is fine for them 9558 // not to be granted, there is a UI for the user to decide. 9559 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9560 Slog.w(TAG, "Not granting permission " + perm 9561 + " to package " + pkg.packageName 9562 + " (protectionLevel=" + bp.protectionLevel 9563 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9564 + ")"); 9565 } 9566 } 9567 } 9568 } 9569 9570 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9571 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9572 // This is the first that we have heard about this package, so the 9573 // permissions we have now selected are fixed until explicitly 9574 // changed. 9575 ps.installPermissionsFixed = true; 9576 } 9577 9578 // Persist the runtime permissions state for users with changes. If permissions 9579 // were revoked because no app in the shared user declares them we have to 9580 // write synchronously to avoid losing runtime permissions state. 9581 for (int userId : changedRuntimePermissionUserIds) { 9582 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9583 } 9584 9585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9586 } 9587 9588 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9589 boolean allowed = false; 9590 final int NP = PackageParser.NEW_PERMISSIONS.length; 9591 for (int ip=0; ip<NP; ip++) { 9592 final PackageParser.NewPermissionInfo npi 9593 = PackageParser.NEW_PERMISSIONS[ip]; 9594 if (npi.name.equals(perm) 9595 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9596 allowed = true; 9597 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9598 + pkg.packageName); 9599 break; 9600 } 9601 } 9602 return allowed; 9603 } 9604 9605 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9606 BasePermission bp, PermissionsState origPermissions) { 9607 boolean allowed; 9608 allowed = (compareSignatures( 9609 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9610 == PackageManager.SIGNATURE_MATCH) 9611 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9612 == PackageManager.SIGNATURE_MATCH); 9613 if (!allowed && (bp.protectionLevel 9614 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9615 if (isSystemApp(pkg)) { 9616 // For updated system applications, a system permission 9617 // is granted only if it had been defined by the original application. 9618 if (pkg.isUpdatedSystemApp()) { 9619 final PackageSetting sysPs = mSettings 9620 .getDisabledSystemPkgLPr(pkg.packageName); 9621 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9622 // If the original was granted this permission, we take 9623 // that grant decision as read and propagate it to the 9624 // update. 9625 if (sysPs.isPrivileged()) { 9626 allowed = true; 9627 } 9628 } else { 9629 // The system apk may have been updated with an older 9630 // version of the one on the data partition, but which 9631 // granted a new system permission that it didn't have 9632 // before. In this case we do want to allow the app to 9633 // now get the new permission if the ancestral apk is 9634 // privileged to get it. 9635 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9636 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9637 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9638 allowed = true; 9639 break; 9640 } 9641 } 9642 } 9643 // Also if a privileged parent package on the system image or any of 9644 // its children requested a privileged permission, the updated child 9645 // packages can also get the permission. 9646 if (pkg.parentPackage != null) { 9647 final PackageSetting disabledSysParentPs = mSettings 9648 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9649 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9650 && disabledSysParentPs.isPrivileged()) { 9651 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9652 allowed = true; 9653 } else if (disabledSysParentPs.pkg.childPackages != null) { 9654 final int count = disabledSysParentPs.pkg.childPackages.size(); 9655 for (int i = 0; i < count; i++) { 9656 PackageParser.Package disabledSysChildPkg = 9657 disabledSysParentPs.pkg.childPackages.get(i); 9658 if (isPackageRequestingPermission(disabledSysChildPkg, 9659 perm)) { 9660 allowed = true; 9661 break; 9662 } 9663 } 9664 } 9665 } 9666 } 9667 } 9668 } else { 9669 allowed = isPrivilegedApp(pkg); 9670 } 9671 } 9672 } 9673 if (!allowed) { 9674 if (!allowed && (bp.protectionLevel 9675 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9676 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9677 // If this was a previously normal/dangerous permission that got moved 9678 // to a system permission as part of the runtime permission redesign, then 9679 // we still want to blindly grant it to old apps. 9680 allowed = true; 9681 } 9682 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9683 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9684 // If this permission is to be granted to the system installer and 9685 // this app is an installer, then it gets the permission. 9686 allowed = true; 9687 } 9688 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9689 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9690 // If this permission is to be granted to the system verifier and 9691 // this app is a verifier, then it gets the permission. 9692 allowed = true; 9693 } 9694 if (!allowed && (bp.protectionLevel 9695 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9696 && isSystemApp(pkg)) { 9697 // Any pre-installed system app is allowed to get this permission. 9698 allowed = true; 9699 } 9700 if (!allowed && (bp.protectionLevel 9701 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9702 // For development permissions, a development permission 9703 // is granted only if it was already granted. 9704 allowed = origPermissions.hasInstallPermission(perm); 9705 } 9706 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9707 && pkg.packageName.equals(mSetupWizardPackage)) { 9708 // If this permission is to be granted to the system setup wizard and 9709 // this app is a setup wizard, then it gets the permission. 9710 allowed = true; 9711 } 9712 } 9713 return allowed; 9714 } 9715 9716 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9717 final int permCount = pkg.requestedPermissions.size(); 9718 for (int j = 0; j < permCount; j++) { 9719 String requestedPermission = pkg.requestedPermissions.get(j); 9720 if (permission.equals(requestedPermission)) { 9721 return true; 9722 } 9723 } 9724 return false; 9725 } 9726 9727 final class ActivityIntentResolver 9728 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9729 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9730 boolean defaultOnly, int userId) { 9731 if (!sUserManager.exists(userId)) return null; 9732 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9733 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9734 } 9735 9736 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9737 int userId) { 9738 if (!sUserManager.exists(userId)) return null; 9739 mFlags = flags; 9740 return super.queryIntent(intent, resolvedType, 9741 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9742 } 9743 9744 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9745 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9746 if (!sUserManager.exists(userId)) return null; 9747 if (packageActivities == null) { 9748 return null; 9749 } 9750 mFlags = flags; 9751 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9752 final int N = packageActivities.size(); 9753 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9754 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9755 9756 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9757 for (int i = 0; i < N; ++i) { 9758 intentFilters = packageActivities.get(i).intents; 9759 if (intentFilters != null && intentFilters.size() > 0) { 9760 PackageParser.ActivityIntentInfo[] array = 9761 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9762 intentFilters.toArray(array); 9763 listCut.add(array); 9764 } 9765 } 9766 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9767 } 9768 9769 public final void addActivity(PackageParser.Activity a, String type) { 9770 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9771 mActivities.put(a.getComponentName(), a); 9772 if (DEBUG_SHOW_INFO) 9773 Log.v( 9774 TAG, " " + type + " " + 9775 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9776 if (DEBUG_SHOW_INFO) 9777 Log.v(TAG, " Class=" + a.info.name); 9778 final int NI = a.intents.size(); 9779 for (int j=0; j<NI; j++) { 9780 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9781 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9782 intent.setPriority(0); 9783 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9784 + a.className + " with priority > 0, forcing to 0"); 9785 } 9786 if (DEBUG_SHOW_INFO) { 9787 Log.v(TAG, " IntentFilter:"); 9788 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9789 } 9790 if (!intent.debugCheck()) { 9791 Log.w(TAG, "==> For Activity " + a.info.name); 9792 } 9793 addFilter(intent); 9794 } 9795 } 9796 9797 public final void removeActivity(PackageParser.Activity a, String type) { 9798 mActivities.remove(a.getComponentName()); 9799 if (DEBUG_SHOW_INFO) { 9800 Log.v(TAG, " " + type + " " 9801 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9802 : a.info.name) + ":"); 9803 Log.v(TAG, " Class=" + a.info.name); 9804 } 9805 final int NI = a.intents.size(); 9806 for (int j=0; j<NI; j++) { 9807 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9808 if (DEBUG_SHOW_INFO) { 9809 Log.v(TAG, " IntentFilter:"); 9810 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9811 } 9812 removeFilter(intent); 9813 } 9814 } 9815 9816 @Override 9817 protected boolean allowFilterResult( 9818 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9819 ActivityInfo filterAi = filter.activity.info; 9820 for (int i=dest.size()-1; i>=0; i--) { 9821 ActivityInfo destAi = dest.get(i).activityInfo; 9822 if (destAi.name == filterAi.name 9823 && destAi.packageName == filterAi.packageName) { 9824 return false; 9825 } 9826 } 9827 return true; 9828 } 9829 9830 @Override 9831 protected ActivityIntentInfo[] newArray(int size) { 9832 return new ActivityIntentInfo[size]; 9833 } 9834 9835 @Override 9836 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9837 if (!sUserManager.exists(userId)) return true; 9838 PackageParser.Package p = filter.activity.owner; 9839 if (p != null) { 9840 PackageSetting ps = (PackageSetting)p.mExtras; 9841 if (ps != null) { 9842 // System apps are never considered stopped for purposes of 9843 // filtering, because there may be no way for the user to 9844 // actually re-launch them. 9845 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9846 && ps.getStopped(userId); 9847 } 9848 } 9849 return false; 9850 } 9851 9852 @Override 9853 protected boolean isPackageForFilter(String packageName, 9854 PackageParser.ActivityIntentInfo info) { 9855 return packageName.equals(info.activity.owner.packageName); 9856 } 9857 9858 @Override 9859 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9860 int match, int userId) { 9861 if (!sUserManager.exists(userId)) return null; 9862 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9863 return null; 9864 } 9865 final PackageParser.Activity activity = info.activity; 9866 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9867 if (ps == null) { 9868 return null; 9869 } 9870 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9871 ps.readUserState(userId), userId); 9872 if (ai == null) { 9873 return null; 9874 } 9875 final ResolveInfo res = new ResolveInfo(); 9876 res.activityInfo = ai; 9877 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9878 res.filter = info; 9879 } 9880 if (info != null) { 9881 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9882 } 9883 res.priority = info.getPriority(); 9884 res.preferredOrder = activity.owner.mPreferredOrder; 9885 //System.out.println("Result: " + res.activityInfo.className + 9886 // " = " + res.priority); 9887 res.match = match; 9888 res.isDefault = info.hasDefault; 9889 res.labelRes = info.labelRes; 9890 res.nonLocalizedLabel = info.nonLocalizedLabel; 9891 if (userNeedsBadging(userId)) { 9892 res.noResourceId = true; 9893 } else { 9894 res.icon = info.icon; 9895 } 9896 res.iconResourceId = info.icon; 9897 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9898 return res; 9899 } 9900 9901 @Override 9902 protected void sortResults(List<ResolveInfo> results) { 9903 Collections.sort(results, mResolvePrioritySorter); 9904 } 9905 9906 @Override 9907 protected void dumpFilter(PrintWriter out, String prefix, 9908 PackageParser.ActivityIntentInfo filter) { 9909 out.print(prefix); out.print( 9910 Integer.toHexString(System.identityHashCode(filter.activity))); 9911 out.print(' '); 9912 filter.activity.printComponentShortName(out); 9913 out.print(" filter "); 9914 out.println(Integer.toHexString(System.identityHashCode(filter))); 9915 } 9916 9917 @Override 9918 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9919 return filter.activity; 9920 } 9921 9922 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9923 PackageParser.Activity activity = (PackageParser.Activity)label; 9924 out.print(prefix); out.print( 9925 Integer.toHexString(System.identityHashCode(activity))); 9926 out.print(' '); 9927 activity.printComponentShortName(out); 9928 if (count > 1) { 9929 out.print(" ("); out.print(count); out.print(" filters)"); 9930 } 9931 out.println(); 9932 } 9933 9934// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9935// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9936// final List<ResolveInfo> retList = Lists.newArrayList(); 9937// while (i.hasNext()) { 9938// final ResolveInfo resolveInfo = i.next(); 9939// if (isEnabledLP(resolveInfo.activityInfo)) { 9940// retList.add(resolveInfo); 9941// } 9942// } 9943// return retList; 9944// } 9945 9946 // Keys are String (activity class name), values are Activity. 9947 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9948 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9949 private int mFlags; 9950 } 9951 9952 private final class ServiceIntentResolver 9953 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9954 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9955 boolean defaultOnly, int userId) { 9956 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9957 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9958 } 9959 9960 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9961 int userId) { 9962 if (!sUserManager.exists(userId)) return null; 9963 mFlags = flags; 9964 return super.queryIntent(intent, resolvedType, 9965 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9966 } 9967 9968 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9969 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9970 if (!sUserManager.exists(userId)) return null; 9971 if (packageServices == null) { 9972 return null; 9973 } 9974 mFlags = flags; 9975 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9976 final int N = packageServices.size(); 9977 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9978 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9979 9980 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9981 for (int i = 0; i < N; ++i) { 9982 intentFilters = packageServices.get(i).intents; 9983 if (intentFilters != null && intentFilters.size() > 0) { 9984 PackageParser.ServiceIntentInfo[] array = 9985 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9986 intentFilters.toArray(array); 9987 listCut.add(array); 9988 } 9989 } 9990 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9991 } 9992 9993 public final void addService(PackageParser.Service s) { 9994 mServices.put(s.getComponentName(), s); 9995 if (DEBUG_SHOW_INFO) { 9996 Log.v(TAG, " " 9997 + (s.info.nonLocalizedLabel != null 9998 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9999 Log.v(TAG, " Class=" + s.info.name); 10000 } 10001 final int NI = s.intents.size(); 10002 int j; 10003 for (j=0; j<NI; j++) { 10004 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10005 if (DEBUG_SHOW_INFO) { 10006 Log.v(TAG, " IntentFilter:"); 10007 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10008 } 10009 if (!intent.debugCheck()) { 10010 Log.w(TAG, "==> For Service " + s.info.name); 10011 } 10012 addFilter(intent); 10013 } 10014 } 10015 10016 public final void removeService(PackageParser.Service s) { 10017 mServices.remove(s.getComponentName()); 10018 if (DEBUG_SHOW_INFO) { 10019 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10020 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10021 Log.v(TAG, " Class=" + s.info.name); 10022 } 10023 final int NI = s.intents.size(); 10024 int j; 10025 for (j=0; j<NI; j++) { 10026 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10027 if (DEBUG_SHOW_INFO) { 10028 Log.v(TAG, " IntentFilter:"); 10029 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10030 } 10031 removeFilter(intent); 10032 } 10033 } 10034 10035 @Override 10036 protected boolean allowFilterResult( 10037 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10038 ServiceInfo filterSi = filter.service.info; 10039 for (int i=dest.size()-1; i>=0; i--) { 10040 ServiceInfo destAi = dest.get(i).serviceInfo; 10041 if (destAi.name == filterSi.name 10042 && destAi.packageName == filterSi.packageName) { 10043 return false; 10044 } 10045 } 10046 return true; 10047 } 10048 10049 @Override 10050 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10051 return new PackageParser.ServiceIntentInfo[size]; 10052 } 10053 10054 @Override 10055 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10056 if (!sUserManager.exists(userId)) return true; 10057 PackageParser.Package p = filter.service.owner; 10058 if (p != null) { 10059 PackageSetting ps = (PackageSetting)p.mExtras; 10060 if (ps != null) { 10061 // System apps are never considered stopped for purposes of 10062 // filtering, because there may be no way for the user to 10063 // actually re-launch them. 10064 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10065 && ps.getStopped(userId); 10066 } 10067 } 10068 return false; 10069 } 10070 10071 @Override 10072 protected boolean isPackageForFilter(String packageName, 10073 PackageParser.ServiceIntentInfo info) { 10074 return packageName.equals(info.service.owner.packageName); 10075 } 10076 10077 @Override 10078 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10079 int match, int userId) { 10080 if (!sUserManager.exists(userId)) return null; 10081 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10082 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10083 return null; 10084 } 10085 final PackageParser.Service service = info.service; 10086 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10087 if (ps == null) { 10088 return null; 10089 } 10090 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10091 ps.readUserState(userId), userId); 10092 if (si == null) { 10093 return null; 10094 } 10095 final ResolveInfo res = new ResolveInfo(); 10096 res.serviceInfo = si; 10097 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10098 res.filter = filter; 10099 } 10100 res.priority = info.getPriority(); 10101 res.preferredOrder = service.owner.mPreferredOrder; 10102 res.match = match; 10103 res.isDefault = info.hasDefault; 10104 res.labelRes = info.labelRes; 10105 res.nonLocalizedLabel = info.nonLocalizedLabel; 10106 res.icon = info.icon; 10107 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10108 return res; 10109 } 10110 10111 @Override 10112 protected void sortResults(List<ResolveInfo> results) { 10113 Collections.sort(results, mResolvePrioritySorter); 10114 } 10115 10116 @Override 10117 protected void dumpFilter(PrintWriter out, String prefix, 10118 PackageParser.ServiceIntentInfo filter) { 10119 out.print(prefix); out.print( 10120 Integer.toHexString(System.identityHashCode(filter.service))); 10121 out.print(' '); 10122 filter.service.printComponentShortName(out); 10123 out.print(" filter "); 10124 out.println(Integer.toHexString(System.identityHashCode(filter))); 10125 } 10126 10127 @Override 10128 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10129 return filter.service; 10130 } 10131 10132 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10133 PackageParser.Service service = (PackageParser.Service)label; 10134 out.print(prefix); out.print( 10135 Integer.toHexString(System.identityHashCode(service))); 10136 out.print(' '); 10137 service.printComponentShortName(out); 10138 if (count > 1) { 10139 out.print(" ("); out.print(count); out.print(" filters)"); 10140 } 10141 out.println(); 10142 } 10143 10144// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10145// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10146// final List<ResolveInfo> retList = Lists.newArrayList(); 10147// while (i.hasNext()) { 10148// final ResolveInfo resolveInfo = (ResolveInfo) i; 10149// if (isEnabledLP(resolveInfo.serviceInfo)) { 10150// retList.add(resolveInfo); 10151// } 10152// } 10153// return retList; 10154// } 10155 10156 // Keys are String (activity class name), values are Activity. 10157 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10158 = new ArrayMap<ComponentName, PackageParser.Service>(); 10159 private int mFlags; 10160 }; 10161 10162 private final class ProviderIntentResolver 10163 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10164 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10165 boolean defaultOnly, int userId) { 10166 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10167 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10168 } 10169 10170 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10171 int userId) { 10172 if (!sUserManager.exists(userId)) 10173 return null; 10174 mFlags = flags; 10175 return super.queryIntent(intent, resolvedType, 10176 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10177 } 10178 10179 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10180 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10181 if (!sUserManager.exists(userId)) 10182 return null; 10183 if (packageProviders == null) { 10184 return null; 10185 } 10186 mFlags = flags; 10187 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10188 final int N = packageProviders.size(); 10189 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10190 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10191 10192 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10193 for (int i = 0; i < N; ++i) { 10194 intentFilters = packageProviders.get(i).intents; 10195 if (intentFilters != null && intentFilters.size() > 0) { 10196 PackageParser.ProviderIntentInfo[] array = 10197 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10198 intentFilters.toArray(array); 10199 listCut.add(array); 10200 } 10201 } 10202 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10203 } 10204 10205 public final void addProvider(PackageParser.Provider p) { 10206 if (mProviders.containsKey(p.getComponentName())) { 10207 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10208 return; 10209 } 10210 10211 mProviders.put(p.getComponentName(), p); 10212 if (DEBUG_SHOW_INFO) { 10213 Log.v(TAG, " " 10214 + (p.info.nonLocalizedLabel != null 10215 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10216 Log.v(TAG, " Class=" + p.info.name); 10217 } 10218 final int NI = p.intents.size(); 10219 int j; 10220 for (j = 0; j < NI; j++) { 10221 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10222 if (DEBUG_SHOW_INFO) { 10223 Log.v(TAG, " IntentFilter:"); 10224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10225 } 10226 if (!intent.debugCheck()) { 10227 Log.w(TAG, "==> For Provider " + p.info.name); 10228 } 10229 addFilter(intent); 10230 } 10231 } 10232 10233 public final void removeProvider(PackageParser.Provider p) { 10234 mProviders.remove(p.getComponentName()); 10235 if (DEBUG_SHOW_INFO) { 10236 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10237 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10238 Log.v(TAG, " Class=" + p.info.name); 10239 } 10240 final int NI = p.intents.size(); 10241 int j; 10242 for (j = 0; j < NI; j++) { 10243 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10244 if (DEBUG_SHOW_INFO) { 10245 Log.v(TAG, " IntentFilter:"); 10246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10247 } 10248 removeFilter(intent); 10249 } 10250 } 10251 10252 @Override 10253 protected boolean allowFilterResult( 10254 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10255 ProviderInfo filterPi = filter.provider.info; 10256 for (int i = dest.size() - 1; i >= 0; i--) { 10257 ProviderInfo destPi = dest.get(i).providerInfo; 10258 if (destPi.name == filterPi.name 10259 && destPi.packageName == filterPi.packageName) { 10260 return false; 10261 } 10262 } 10263 return true; 10264 } 10265 10266 @Override 10267 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10268 return new PackageParser.ProviderIntentInfo[size]; 10269 } 10270 10271 @Override 10272 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10273 if (!sUserManager.exists(userId)) 10274 return true; 10275 PackageParser.Package p = filter.provider.owner; 10276 if (p != null) { 10277 PackageSetting ps = (PackageSetting) p.mExtras; 10278 if (ps != null) { 10279 // System apps are never considered stopped for purposes of 10280 // filtering, because there may be no way for the user to 10281 // actually re-launch them. 10282 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10283 && ps.getStopped(userId); 10284 } 10285 } 10286 return false; 10287 } 10288 10289 @Override 10290 protected boolean isPackageForFilter(String packageName, 10291 PackageParser.ProviderIntentInfo info) { 10292 return packageName.equals(info.provider.owner.packageName); 10293 } 10294 10295 @Override 10296 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10297 int match, int userId) { 10298 if (!sUserManager.exists(userId)) 10299 return null; 10300 final PackageParser.ProviderIntentInfo info = filter; 10301 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10302 return null; 10303 } 10304 final PackageParser.Provider provider = info.provider; 10305 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10306 if (ps == null) { 10307 return null; 10308 } 10309 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10310 ps.readUserState(userId), userId); 10311 if (pi == null) { 10312 return null; 10313 } 10314 final ResolveInfo res = new ResolveInfo(); 10315 res.providerInfo = pi; 10316 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10317 res.filter = filter; 10318 } 10319 res.priority = info.getPriority(); 10320 res.preferredOrder = provider.owner.mPreferredOrder; 10321 res.match = match; 10322 res.isDefault = info.hasDefault; 10323 res.labelRes = info.labelRes; 10324 res.nonLocalizedLabel = info.nonLocalizedLabel; 10325 res.icon = info.icon; 10326 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10327 return res; 10328 } 10329 10330 @Override 10331 protected void sortResults(List<ResolveInfo> results) { 10332 Collections.sort(results, mResolvePrioritySorter); 10333 } 10334 10335 @Override 10336 protected void dumpFilter(PrintWriter out, String prefix, 10337 PackageParser.ProviderIntentInfo filter) { 10338 out.print(prefix); 10339 out.print( 10340 Integer.toHexString(System.identityHashCode(filter.provider))); 10341 out.print(' '); 10342 filter.provider.printComponentShortName(out); 10343 out.print(" filter "); 10344 out.println(Integer.toHexString(System.identityHashCode(filter))); 10345 } 10346 10347 @Override 10348 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10349 return filter.provider; 10350 } 10351 10352 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10353 PackageParser.Provider provider = (PackageParser.Provider)label; 10354 out.print(prefix); out.print( 10355 Integer.toHexString(System.identityHashCode(provider))); 10356 out.print(' '); 10357 provider.printComponentShortName(out); 10358 if (count > 1) { 10359 out.print(" ("); out.print(count); out.print(" filters)"); 10360 } 10361 out.println(); 10362 } 10363 10364 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10365 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10366 private int mFlags; 10367 } 10368 10369 private static final class EphemeralIntentResolver 10370 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10371 @Override 10372 protected EphemeralResolveIntentInfo[] newArray(int size) { 10373 return new EphemeralResolveIntentInfo[size]; 10374 } 10375 10376 @Override 10377 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10378 return true; 10379 } 10380 10381 @Override 10382 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10383 int userId) { 10384 if (!sUserManager.exists(userId)) { 10385 return null; 10386 } 10387 return info.getEphemeralResolveInfo(); 10388 } 10389 } 10390 10391 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10392 new Comparator<ResolveInfo>() { 10393 public int compare(ResolveInfo r1, ResolveInfo r2) { 10394 int v1 = r1.priority; 10395 int v2 = r2.priority; 10396 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10397 if (v1 != v2) { 10398 return (v1 > v2) ? -1 : 1; 10399 } 10400 v1 = r1.preferredOrder; 10401 v2 = r2.preferredOrder; 10402 if (v1 != v2) { 10403 return (v1 > v2) ? -1 : 1; 10404 } 10405 if (r1.isDefault != r2.isDefault) { 10406 return r1.isDefault ? -1 : 1; 10407 } 10408 v1 = r1.match; 10409 v2 = r2.match; 10410 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10411 if (v1 != v2) { 10412 return (v1 > v2) ? -1 : 1; 10413 } 10414 if (r1.system != r2.system) { 10415 return r1.system ? -1 : 1; 10416 } 10417 if (r1.activityInfo != null) { 10418 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10419 } 10420 if (r1.serviceInfo != null) { 10421 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10422 } 10423 if (r1.providerInfo != null) { 10424 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10425 } 10426 return 0; 10427 } 10428 }; 10429 10430 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10431 new Comparator<ProviderInfo>() { 10432 public int compare(ProviderInfo p1, ProviderInfo p2) { 10433 final int v1 = p1.initOrder; 10434 final int v2 = p2.initOrder; 10435 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10436 } 10437 }; 10438 10439 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10440 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10441 final int[] userIds) { 10442 mHandler.post(new Runnable() { 10443 @Override 10444 public void run() { 10445 try { 10446 final IActivityManager am = ActivityManagerNative.getDefault(); 10447 if (am == null) return; 10448 final int[] resolvedUserIds; 10449 if (userIds == null) { 10450 resolvedUserIds = am.getRunningUserIds(); 10451 } else { 10452 resolvedUserIds = userIds; 10453 } 10454 for (int id : resolvedUserIds) { 10455 final Intent intent = new Intent(action, 10456 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10457 if (extras != null) { 10458 intent.putExtras(extras); 10459 } 10460 if (targetPkg != null) { 10461 intent.setPackage(targetPkg); 10462 } 10463 // Modify the UID when posting to other users 10464 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10465 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10466 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10467 intent.putExtra(Intent.EXTRA_UID, uid); 10468 } 10469 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10470 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10471 if (DEBUG_BROADCASTS) { 10472 RuntimeException here = new RuntimeException("here"); 10473 here.fillInStackTrace(); 10474 Slog.d(TAG, "Sending to user " + id + ": " 10475 + intent.toShortString(false, true, false, false) 10476 + " " + intent.getExtras(), here); 10477 } 10478 am.broadcastIntent(null, intent, null, finishedReceiver, 10479 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10480 null, finishedReceiver != null, false, id); 10481 } 10482 } catch (RemoteException ex) { 10483 } 10484 } 10485 }); 10486 } 10487 10488 /** 10489 * Check if the external storage media is available. This is true if there 10490 * is a mounted external storage medium or if the external storage is 10491 * emulated. 10492 */ 10493 private boolean isExternalMediaAvailable() { 10494 return mMediaMounted || Environment.isExternalStorageEmulated(); 10495 } 10496 10497 @Override 10498 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10499 // writer 10500 synchronized (mPackages) { 10501 if (!isExternalMediaAvailable()) { 10502 // If the external storage is no longer mounted at this point, 10503 // the caller may not have been able to delete all of this 10504 // packages files and can not delete any more. Bail. 10505 return null; 10506 } 10507 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10508 if (lastPackage != null) { 10509 pkgs.remove(lastPackage); 10510 } 10511 if (pkgs.size() > 0) { 10512 return pkgs.get(0); 10513 } 10514 } 10515 return null; 10516 } 10517 10518 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10519 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10520 userId, andCode ? 1 : 0, packageName); 10521 if (mSystemReady) { 10522 msg.sendToTarget(); 10523 } else { 10524 if (mPostSystemReadyMessages == null) { 10525 mPostSystemReadyMessages = new ArrayList<>(); 10526 } 10527 mPostSystemReadyMessages.add(msg); 10528 } 10529 } 10530 10531 void startCleaningPackages() { 10532 // reader 10533 if (!isExternalMediaAvailable()) { 10534 return; 10535 } 10536 synchronized (mPackages) { 10537 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10538 return; 10539 } 10540 } 10541 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10542 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10543 IActivityManager am = ActivityManagerNative.getDefault(); 10544 if (am != null) { 10545 try { 10546 am.startService(null, intent, null, mContext.getOpPackageName(), 10547 UserHandle.USER_SYSTEM); 10548 } catch (RemoteException e) { 10549 } 10550 } 10551 } 10552 10553 @Override 10554 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10555 int installFlags, String installerPackageName, int userId) { 10556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10557 10558 final int callingUid = Binder.getCallingUid(); 10559 enforceCrossUserPermission(callingUid, userId, 10560 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10561 10562 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10563 try { 10564 if (observer != null) { 10565 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10566 } 10567 } catch (RemoteException re) { 10568 } 10569 return; 10570 } 10571 10572 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10573 installFlags |= PackageManager.INSTALL_FROM_ADB; 10574 10575 } else { 10576 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10577 // about installerPackageName. 10578 10579 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10580 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10581 } 10582 10583 UserHandle user; 10584 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10585 user = UserHandle.ALL; 10586 } else { 10587 user = new UserHandle(userId); 10588 } 10589 10590 // Only system components can circumvent runtime permissions when installing. 10591 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10592 && mContext.checkCallingOrSelfPermission(Manifest.permission 10593 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10594 throw new SecurityException("You need the " 10595 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10596 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10597 } 10598 10599 final File originFile = new File(originPath); 10600 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10601 10602 final Message msg = mHandler.obtainMessage(INIT_COPY); 10603 final VerificationInfo verificationInfo = new VerificationInfo( 10604 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10605 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10606 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10607 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10608 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10609 msg.obj = params; 10610 10611 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10612 System.identityHashCode(msg.obj)); 10613 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10614 System.identityHashCode(msg.obj)); 10615 10616 mHandler.sendMessage(msg); 10617 } 10618 10619 void installStage(String packageName, File stagedDir, String stagedCid, 10620 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10621 String installerPackageName, int installerUid, UserHandle user) { 10622 if (DEBUG_EPHEMERAL) { 10623 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10624 Slog.d(TAG, "Ephemeral install of " + packageName); 10625 } 10626 } 10627 final VerificationInfo verificationInfo = new VerificationInfo( 10628 sessionParams.originatingUri, sessionParams.referrerUri, 10629 sessionParams.originatingUid, installerUid); 10630 10631 final OriginInfo origin; 10632 if (stagedDir != null) { 10633 origin = OriginInfo.fromStagedFile(stagedDir); 10634 } else { 10635 origin = OriginInfo.fromStagedContainer(stagedCid); 10636 } 10637 10638 final Message msg = mHandler.obtainMessage(INIT_COPY); 10639 final InstallParams params = new InstallParams(origin, null, observer, 10640 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10641 verificationInfo, user, sessionParams.abiOverride, 10642 sessionParams.grantedRuntimePermissions); 10643 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10644 msg.obj = params; 10645 10646 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10647 System.identityHashCode(msg.obj)); 10648 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10649 System.identityHashCode(msg.obj)); 10650 10651 mHandler.sendMessage(msg); 10652 } 10653 10654 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10655 int userId) { 10656 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10657 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10658 } 10659 10660 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10661 int appId, int userId) { 10662 Bundle extras = new Bundle(1); 10663 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10664 10665 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10666 packageName, extras, 0, null, null, new int[] {userId}); 10667 try { 10668 IActivityManager am = ActivityManagerNative.getDefault(); 10669 if (isSystem && am.isUserRunning(userId, 0)) { 10670 // The just-installed/enabled app is bundled on the system, so presumed 10671 // to be able to run automatically without needing an explicit launch. 10672 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10673 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10674 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10675 .setPackage(packageName); 10676 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10677 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10678 } 10679 } catch (RemoteException e) { 10680 // shouldn't happen 10681 Slog.w(TAG, "Unable to bootstrap installed package", e); 10682 } 10683 } 10684 10685 @Override 10686 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10687 int userId) { 10688 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10689 PackageSetting pkgSetting; 10690 final int uid = Binder.getCallingUid(); 10691 enforceCrossUserPermission(uid, userId, 10692 true /* requireFullPermission */, true /* checkShell */, 10693 "setApplicationHiddenSetting for user " + userId); 10694 10695 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10696 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10697 return false; 10698 } 10699 10700 long callingId = Binder.clearCallingIdentity(); 10701 try { 10702 boolean sendAdded = false; 10703 boolean sendRemoved = false; 10704 // writer 10705 synchronized (mPackages) { 10706 pkgSetting = mSettings.mPackages.get(packageName); 10707 if (pkgSetting == null) { 10708 return false; 10709 } 10710 if (pkgSetting.getHidden(userId) != hidden) { 10711 pkgSetting.setHidden(hidden, userId); 10712 mSettings.writePackageRestrictionsLPr(userId); 10713 if (hidden) { 10714 sendRemoved = true; 10715 } else { 10716 sendAdded = true; 10717 } 10718 } 10719 } 10720 if (sendAdded) { 10721 sendPackageAddedForUser(packageName, pkgSetting, userId); 10722 return true; 10723 } 10724 if (sendRemoved) { 10725 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10726 "hiding pkg"); 10727 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10728 return true; 10729 } 10730 } finally { 10731 Binder.restoreCallingIdentity(callingId); 10732 } 10733 return false; 10734 } 10735 10736 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10737 int userId) { 10738 final PackageRemovedInfo info = new PackageRemovedInfo(); 10739 info.removedPackage = packageName; 10740 info.removedUsers = new int[] {userId}; 10741 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10742 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10743 } 10744 10745 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10746 if (pkgList.length > 0) { 10747 Bundle extras = new Bundle(1); 10748 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10749 10750 sendPackageBroadcast( 10751 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10752 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10753 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10754 new int[] {userId}); 10755 } 10756 } 10757 10758 /** 10759 * Returns true if application is not found or there was an error. Otherwise it returns 10760 * the hidden state of the package for the given user. 10761 */ 10762 @Override 10763 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10765 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10766 true /* requireFullPermission */, false /* checkShell */, 10767 "getApplicationHidden for user " + userId); 10768 PackageSetting pkgSetting; 10769 long callingId = Binder.clearCallingIdentity(); 10770 try { 10771 // writer 10772 synchronized (mPackages) { 10773 pkgSetting = mSettings.mPackages.get(packageName); 10774 if (pkgSetting == null) { 10775 return true; 10776 } 10777 return pkgSetting.getHidden(userId); 10778 } 10779 } finally { 10780 Binder.restoreCallingIdentity(callingId); 10781 } 10782 } 10783 10784 /** 10785 * @hide 10786 */ 10787 @Override 10788 public int installExistingPackageAsUser(String packageName, int userId) { 10789 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10790 null); 10791 PackageSetting pkgSetting; 10792 final int uid = Binder.getCallingUid(); 10793 enforceCrossUserPermission(uid, userId, 10794 true /* requireFullPermission */, true /* checkShell */, 10795 "installExistingPackage for user " + userId); 10796 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10797 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10798 } 10799 10800 long callingId = Binder.clearCallingIdentity(); 10801 try { 10802 boolean installed = false; 10803 10804 // writer 10805 synchronized (mPackages) { 10806 pkgSetting = mSettings.mPackages.get(packageName); 10807 if (pkgSetting == null) { 10808 return PackageManager.INSTALL_FAILED_INVALID_URI; 10809 } 10810 if (!pkgSetting.getInstalled(userId)) { 10811 pkgSetting.setInstalled(true, userId); 10812 pkgSetting.setHidden(false, userId); 10813 mSettings.writePackageRestrictionsLPr(userId); 10814 installed = true; 10815 } 10816 } 10817 10818 if (installed) { 10819 if (pkgSetting.pkg != null) { 10820 prepareAppDataAfterInstall(pkgSetting.pkg); 10821 } 10822 sendPackageAddedForUser(packageName, pkgSetting, userId); 10823 } 10824 } finally { 10825 Binder.restoreCallingIdentity(callingId); 10826 } 10827 10828 return PackageManager.INSTALL_SUCCEEDED; 10829 } 10830 10831 boolean isUserRestricted(int userId, String restrictionKey) { 10832 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10833 if (restrictions.getBoolean(restrictionKey, false)) { 10834 Log.w(TAG, "User is restricted: " + restrictionKey); 10835 return true; 10836 } 10837 return false; 10838 } 10839 10840 @Override 10841 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10842 int userId) { 10843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10844 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10845 true /* requireFullPermission */, true /* checkShell */, 10846 "setPackagesSuspended for user " + userId); 10847 10848 if (ArrayUtils.isEmpty(packageNames)) { 10849 return packageNames; 10850 } 10851 10852 // List of package names for whom the suspended state has changed. 10853 List<String> changedPackages = new ArrayList<>(packageNames.length); 10854 // List of package names for whom the suspended state is not set as requested in this 10855 // method. 10856 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10857 for (int i = 0; i < packageNames.length; i++) { 10858 String packageName = packageNames[i]; 10859 long callingId = Binder.clearCallingIdentity(); 10860 try { 10861 boolean changed = false; 10862 final int appId; 10863 synchronized (mPackages) { 10864 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10865 if (pkgSetting == null) { 10866 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10867 + "\". Skipping suspending/un-suspending."); 10868 unactionedPackages.add(packageName); 10869 continue; 10870 } 10871 appId = pkgSetting.appId; 10872 if (pkgSetting.getSuspended(userId) != suspended) { 10873 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10874 unactionedPackages.add(packageName); 10875 continue; 10876 } 10877 pkgSetting.setSuspended(suspended, userId); 10878 mSettings.writePackageRestrictionsLPr(userId); 10879 changed = true; 10880 changedPackages.add(packageName); 10881 } 10882 } 10883 10884 if (changed && suspended) { 10885 killApplication(packageName, UserHandle.getUid(userId, appId), 10886 "suspending package"); 10887 } 10888 } finally { 10889 Binder.restoreCallingIdentity(callingId); 10890 } 10891 } 10892 10893 if (!changedPackages.isEmpty()) { 10894 sendPackagesSuspendedForUser(changedPackages.toArray( 10895 new String[changedPackages.size()]), userId, suspended); 10896 } 10897 10898 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10899 } 10900 10901 @Override 10902 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10903 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10904 true /* requireFullPermission */, false /* checkShell */, 10905 "isPackageSuspendedForUser for user " + userId); 10906 synchronized (mPackages) { 10907 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10908 return pkgSetting != null && pkgSetting.getSuspended(userId); 10909 } 10910 } 10911 10912 /** 10913 * TODO: cache and disallow blocking the active dialer. 10914 * 10915 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 10916 */ 10917 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10918 if (isPackageDeviceAdmin(packageName, userId)) { 10919 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10920 + "\": has an active device admin"); 10921 return false; 10922 } 10923 10924 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10925 if (packageName.equals(activeLauncherPackageName)) { 10926 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10927 + "\": contains the active launcher"); 10928 return false; 10929 } 10930 10931 if (packageName.equals(mRequiredInstallerPackage)) { 10932 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10933 + "\": required for package installation"); 10934 return false; 10935 } 10936 10937 if (packageName.equals(mRequiredVerifierPackage)) { 10938 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10939 + "\": required for package verification"); 10940 return false; 10941 } 10942 10943 final PackageParser.Package pkg = mPackages.get(packageName); 10944 if (pkg != null && isPrivilegedApp(pkg)) { 10945 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 10946 + "\": is a privileged app"); 10947 return false; 10948 } 10949 10950 return true; 10951 } 10952 10953 private String getActiveLauncherPackageName(int userId) { 10954 Intent intent = new Intent(Intent.ACTION_MAIN); 10955 intent.addCategory(Intent.CATEGORY_HOME); 10956 ResolveInfo resolveInfo = resolveIntent( 10957 intent, 10958 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10959 PackageManager.MATCH_DEFAULT_ONLY, 10960 userId); 10961 10962 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10963 } 10964 10965 @Override 10966 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10967 mContext.enforceCallingOrSelfPermission( 10968 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10969 "Only package verification agents can verify applications"); 10970 10971 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10972 final PackageVerificationResponse response = new PackageVerificationResponse( 10973 verificationCode, Binder.getCallingUid()); 10974 msg.arg1 = id; 10975 msg.obj = response; 10976 mHandler.sendMessage(msg); 10977 } 10978 10979 @Override 10980 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10981 long millisecondsToDelay) { 10982 mContext.enforceCallingOrSelfPermission( 10983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10984 "Only package verification agents can extend verification timeouts"); 10985 10986 final PackageVerificationState state = mPendingVerification.get(id); 10987 final PackageVerificationResponse response = new PackageVerificationResponse( 10988 verificationCodeAtTimeout, Binder.getCallingUid()); 10989 10990 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10991 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10992 } 10993 if (millisecondsToDelay < 0) { 10994 millisecondsToDelay = 0; 10995 } 10996 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10997 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10998 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10999 } 11000 11001 if ((state != null) && !state.timeoutExtended()) { 11002 state.extendTimeout(); 11003 11004 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11005 msg.arg1 = id; 11006 msg.obj = response; 11007 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11008 } 11009 } 11010 11011 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11012 int verificationCode, UserHandle user) { 11013 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11014 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11015 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11016 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11017 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11018 11019 mContext.sendBroadcastAsUser(intent, user, 11020 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11021 } 11022 11023 private ComponentName matchComponentForVerifier(String packageName, 11024 List<ResolveInfo> receivers) { 11025 ActivityInfo targetReceiver = null; 11026 11027 final int NR = receivers.size(); 11028 for (int i = 0; i < NR; i++) { 11029 final ResolveInfo info = receivers.get(i); 11030 if (info.activityInfo == null) { 11031 continue; 11032 } 11033 11034 if (packageName.equals(info.activityInfo.packageName)) { 11035 targetReceiver = info.activityInfo; 11036 break; 11037 } 11038 } 11039 11040 if (targetReceiver == null) { 11041 return null; 11042 } 11043 11044 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11045 } 11046 11047 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11048 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11049 if (pkgInfo.verifiers.length == 0) { 11050 return null; 11051 } 11052 11053 final int N = pkgInfo.verifiers.length; 11054 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11055 for (int i = 0; i < N; i++) { 11056 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11057 11058 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11059 receivers); 11060 if (comp == null) { 11061 continue; 11062 } 11063 11064 final int verifierUid = getUidForVerifier(verifierInfo); 11065 if (verifierUid == -1) { 11066 continue; 11067 } 11068 11069 if (DEBUG_VERIFY) { 11070 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11071 + " with the correct signature"); 11072 } 11073 sufficientVerifiers.add(comp); 11074 verificationState.addSufficientVerifier(verifierUid); 11075 } 11076 11077 return sufficientVerifiers; 11078 } 11079 11080 private int getUidForVerifier(VerifierInfo verifierInfo) { 11081 synchronized (mPackages) { 11082 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11083 if (pkg == null) { 11084 return -1; 11085 } else if (pkg.mSignatures.length != 1) { 11086 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11087 + " has more than one signature; ignoring"); 11088 return -1; 11089 } 11090 11091 /* 11092 * If the public key of the package's signature does not match 11093 * our expected public key, then this is a different package and 11094 * we should skip. 11095 */ 11096 11097 final byte[] expectedPublicKey; 11098 try { 11099 final Signature verifierSig = pkg.mSignatures[0]; 11100 final PublicKey publicKey = verifierSig.getPublicKey(); 11101 expectedPublicKey = publicKey.getEncoded(); 11102 } catch (CertificateException e) { 11103 return -1; 11104 } 11105 11106 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11107 11108 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11109 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11110 + " does not have the expected public key; ignoring"); 11111 return -1; 11112 } 11113 11114 return pkg.applicationInfo.uid; 11115 } 11116 } 11117 11118 @Override 11119 public void finishPackageInstall(int token) { 11120 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11121 11122 if (DEBUG_INSTALL) { 11123 Slog.v(TAG, "BM finishing package install for " + token); 11124 } 11125 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11126 11127 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11128 mHandler.sendMessage(msg); 11129 } 11130 11131 /** 11132 * Get the verification agent timeout. 11133 * 11134 * @return verification timeout in milliseconds 11135 */ 11136 private long getVerificationTimeout() { 11137 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11138 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11139 DEFAULT_VERIFICATION_TIMEOUT); 11140 } 11141 11142 /** 11143 * Get the default verification agent response code. 11144 * 11145 * @return default verification response code 11146 */ 11147 private int getDefaultVerificationResponse() { 11148 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11149 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11150 DEFAULT_VERIFICATION_RESPONSE); 11151 } 11152 11153 /** 11154 * Check whether or not package verification has been enabled. 11155 * 11156 * @return true if verification should be performed 11157 */ 11158 private boolean isVerificationEnabled(int userId, int installFlags) { 11159 if (!DEFAULT_VERIFY_ENABLE) { 11160 return false; 11161 } 11162 // Ephemeral apps don't get the full verification treatment 11163 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11164 if (DEBUG_EPHEMERAL) { 11165 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11166 } 11167 return false; 11168 } 11169 11170 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11171 11172 // Check if installing from ADB 11173 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11174 // Do not run verification in a test harness environment 11175 if (ActivityManager.isRunningInTestHarness()) { 11176 return false; 11177 } 11178 if (ensureVerifyAppsEnabled) { 11179 return true; 11180 } 11181 // Check if the developer does not want package verification for ADB installs 11182 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11183 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11184 return false; 11185 } 11186 } 11187 11188 if (ensureVerifyAppsEnabled) { 11189 return true; 11190 } 11191 11192 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11193 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11194 } 11195 11196 @Override 11197 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11198 throws RemoteException { 11199 mContext.enforceCallingOrSelfPermission( 11200 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11201 "Only intentfilter verification agents can verify applications"); 11202 11203 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11204 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11205 Binder.getCallingUid(), verificationCode, failedDomains); 11206 msg.arg1 = id; 11207 msg.obj = response; 11208 mHandler.sendMessage(msg); 11209 } 11210 11211 @Override 11212 public int getIntentVerificationStatus(String packageName, int userId) { 11213 synchronized (mPackages) { 11214 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11215 } 11216 } 11217 11218 @Override 11219 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11220 mContext.enforceCallingOrSelfPermission( 11221 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11222 11223 boolean result = false; 11224 synchronized (mPackages) { 11225 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11226 } 11227 if (result) { 11228 scheduleWritePackageRestrictionsLocked(userId); 11229 } 11230 return result; 11231 } 11232 11233 @Override 11234 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11235 String packageName) { 11236 synchronized (mPackages) { 11237 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11238 } 11239 } 11240 11241 @Override 11242 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11243 if (TextUtils.isEmpty(packageName)) { 11244 return ParceledListSlice.emptyList(); 11245 } 11246 synchronized (mPackages) { 11247 PackageParser.Package pkg = mPackages.get(packageName); 11248 if (pkg == null || pkg.activities == null) { 11249 return ParceledListSlice.emptyList(); 11250 } 11251 final int count = pkg.activities.size(); 11252 ArrayList<IntentFilter> result = new ArrayList<>(); 11253 for (int n=0; n<count; n++) { 11254 PackageParser.Activity activity = pkg.activities.get(n); 11255 if (activity.intents != null && activity.intents.size() > 0) { 11256 result.addAll(activity.intents); 11257 } 11258 } 11259 return new ParceledListSlice<>(result); 11260 } 11261 } 11262 11263 @Override 11264 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11265 mContext.enforceCallingOrSelfPermission( 11266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11267 11268 synchronized (mPackages) { 11269 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11270 if (packageName != null) { 11271 result |= updateIntentVerificationStatus(packageName, 11272 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11273 userId); 11274 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11275 packageName, userId); 11276 } 11277 return result; 11278 } 11279 } 11280 11281 @Override 11282 public String getDefaultBrowserPackageName(int userId) { 11283 synchronized (mPackages) { 11284 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11285 } 11286 } 11287 11288 /** 11289 * Get the "allow unknown sources" setting. 11290 * 11291 * @return the current "allow unknown sources" setting 11292 */ 11293 private int getUnknownSourcesSettings() { 11294 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11295 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11296 -1); 11297 } 11298 11299 @Override 11300 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11301 final int uid = Binder.getCallingUid(); 11302 // writer 11303 synchronized (mPackages) { 11304 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11305 if (targetPackageSetting == null) { 11306 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11307 } 11308 11309 PackageSetting installerPackageSetting; 11310 if (installerPackageName != null) { 11311 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11312 if (installerPackageSetting == null) { 11313 throw new IllegalArgumentException("Unknown installer package: " 11314 + installerPackageName); 11315 } 11316 } else { 11317 installerPackageSetting = null; 11318 } 11319 11320 Signature[] callerSignature; 11321 Object obj = mSettings.getUserIdLPr(uid); 11322 if (obj != null) { 11323 if (obj instanceof SharedUserSetting) { 11324 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11325 } else if (obj instanceof PackageSetting) { 11326 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11327 } else { 11328 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11329 } 11330 } else { 11331 throw new SecurityException("Unknown calling UID: " + uid); 11332 } 11333 11334 // Verify: can't set installerPackageName to a package that is 11335 // not signed with the same cert as the caller. 11336 if (installerPackageSetting != null) { 11337 if (compareSignatures(callerSignature, 11338 installerPackageSetting.signatures.mSignatures) 11339 != PackageManager.SIGNATURE_MATCH) { 11340 throw new SecurityException( 11341 "Caller does not have same cert as new installer package " 11342 + installerPackageName); 11343 } 11344 } 11345 11346 // Verify: if target already has an installer package, it must 11347 // be signed with the same cert as the caller. 11348 if (targetPackageSetting.installerPackageName != null) { 11349 PackageSetting setting = mSettings.mPackages.get( 11350 targetPackageSetting.installerPackageName); 11351 // If the currently set package isn't valid, then it's always 11352 // okay to change it. 11353 if (setting != null) { 11354 if (compareSignatures(callerSignature, 11355 setting.signatures.mSignatures) 11356 != PackageManager.SIGNATURE_MATCH) { 11357 throw new SecurityException( 11358 "Caller does not have same cert as old installer package " 11359 + targetPackageSetting.installerPackageName); 11360 } 11361 } 11362 } 11363 11364 // Okay! 11365 targetPackageSetting.installerPackageName = installerPackageName; 11366 scheduleWriteSettingsLocked(); 11367 } 11368 } 11369 11370 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11371 // Queue up an async operation since the package installation may take a little while. 11372 mHandler.post(new Runnable() { 11373 public void run() { 11374 mHandler.removeCallbacks(this); 11375 // Result object to be returned 11376 PackageInstalledInfo res = new PackageInstalledInfo(); 11377 res.setReturnCode(currentStatus); 11378 res.uid = -1; 11379 res.pkg = null; 11380 res.removedInfo = null; 11381 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11382 args.doPreInstall(res.returnCode); 11383 synchronized (mInstallLock) { 11384 installPackageTracedLI(args, res); 11385 } 11386 args.doPostInstall(res.returnCode, res.uid); 11387 } 11388 11389 // A restore should be performed at this point if (a) the install 11390 // succeeded, (b) the operation is not an update, and (c) the new 11391 // package has not opted out of backup participation. 11392 final boolean update = res.removedInfo != null 11393 && res.removedInfo.removedPackage != null; 11394 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11395 boolean doRestore = !update 11396 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11397 11398 // Set up the post-install work request bookkeeping. This will be used 11399 // and cleaned up by the post-install event handling regardless of whether 11400 // there's a restore pass performed. Token values are >= 1. 11401 int token; 11402 if (mNextInstallToken < 0) mNextInstallToken = 1; 11403 token = mNextInstallToken++; 11404 11405 PostInstallData data = new PostInstallData(args, res); 11406 mRunningInstalls.put(token, data); 11407 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11408 11409 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11410 // Pass responsibility to the Backup Manager. It will perform a 11411 // restore if appropriate, then pass responsibility back to the 11412 // Package Manager to run the post-install observer callbacks 11413 // and broadcasts. 11414 IBackupManager bm = IBackupManager.Stub.asInterface( 11415 ServiceManager.getService(Context.BACKUP_SERVICE)); 11416 if (bm != null) { 11417 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11418 + " to BM for possible restore"); 11419 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11420 try { 11421 // TODO: http://b/22388012 11422 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11423 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11424 } else { 11425 doRestore = false; 11426 } 11427 } catch (RemoteException e) { 11428 // can't happen; the backup manager is local 11429 } catch (Exception e) { 11430 Slog.e(TAG, "Exception trying to enqueue restore", e); 11431 doRestore = false; 11432 } 11433 } else { 11434 Slog.e(TAG, "Backup Manager not found!"); 11435 doRestore = false; 11436 } 11437 } 11438 11439 if (!doRestore) { 11440 // No restore possible, or the Backup Manager was mysteriously not 11441 // available -- just fire the post-install work request directly. 11442 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11443 11444 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11445 11446 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11447 mHandler.sendMessage(msg); 11448 } 11449 } 11450 }); 11451 } 11452 11453 private abstract class HandlerParams { 11454 private static final int MAX_RETRIES = 4; 11455 11456 /** 11457 * Number of times startCopy() has been attempted and had a non-fatal 11458 * error. 11459 */ 11460 private int mRetries = 0; 11461 11462 /** User handle for the user requesting the information or installation. */ 11463 private final UserHandle mUser; 11464 String traceMethod; 11465 int traceCookie; 11466 11467 HandlerParams(UserHandle user) { 11468 mUser = user; 11469 } 11470 11471 UserHandle getUser() { 11472 return mUser; 11473 } 11474 11475 HandlerParams setTraceMethod(String traceMethod) { 11476 this.traceMethod = traceMethod; 11477 return this; 11478 } 11479 11480 HandlerParams setTraceCookie(int traceCookie) { 11481 this.traceCookie = traceCookie; 11482 return this; 11483 } 11484 11485 final boolean startCopy() { 11486 boolean res; 11487 try { 11488 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11489 11490 if (++mRetries > MAX_RETRIES) { 11491 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11492 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11493 handleServiceError(); 11494 return false; 11495 } else { 11496 handleStartCopy(); 11497 res = true; 11498 } 11499 } catch (RemoteException e) { 11500 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11501 mHandler.sendEmptyMessage(MCS_RECONNECT); 11502 res = false; 11503 } 11504 handleReturnCode(); 11505 return res; 11506 } 11507 11508 final void serviceError() { 11509 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11510 handleServiceError(); 11511 handleReturnCode(); 11512 } 11513 11514 abstract void handleStartCopy() throws RemoteException; 11515 abstract void handleServiceError(); 11516 abstract void handleReturnCode(); 11517 } 11518 11519 class MeasureParams extends HandlerParams { 11520 private final PackageStats mStats; 11521 private boolean mSuccess; 11522 11523 private final IPackageStatsObserver mObserver; 11524 11525 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11526 super(new UserHandle(stats.userHandle)); 11527 mObserver = observer; 11528 mStats = stats; 11529 } 11530 11531 @Override 11532 public String toString() { 11533 return "MeasureParams{" 11534 + Integer.toHexString(System.identityHashCode(this)) 11535 + " " + mStats.packageName + "}"; 11536 } 11537 11538 @Override 11539 void handleStartCopy() throws RemoteException { 11540 synchronized (mInstallLock) { 11541 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11542 } 11543 11544 if (mSuccess) { 11545 final boolean mounted; 11546 if (Environment.isExternalStorageEmulated()) { 11547 mounted = true; 11548 } else { 11549 final String status = Environment.getExternalStorageState(); 11550 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11551 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11552 } 11553 11554 if (mounted) { 11555 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11556 11557 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11558 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11559 11560 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11561 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11562 11563 // Always subtract cache size, since it's a subdirectory 11564 mStats.externalDataSize -= mStats.externalCacheSize; 11565 11566 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11567 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11568 11569 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11570 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11571 } 11572 } 11573 } 11574 11575 @Override 11576 void handleReturnCode() { 11577 if (mObserver != null) { 11578 try { 11579 mObserver.onGetStatsCompleted(mStats, mSuccess); 11580 } catch (RemoteException e) { 11581 Slog.i(TAG, "Observer no longer exists."); 11582 } 11583 } 11584 } 11585 11586 @Override 11587 void handleServiceError() { 11588 Slog.e(TAG, "Could not measure application " + mStats.packageName 11589 + " external storage"); 11590 } 11591 } 11592 11593 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11594 throws RemoteException { 11595 long result = 0; 11596 for (File path : paths) { 11597 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11598 } 11599 return result; 11600 } 11601 11602 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11603 for (File path : paths) { 11604 try { 11605 mcs.clearDirectory(path.getAbsolutePath()); 11606 } catch (RemoteException e) { 11607 } 11608 } 11609 } 11610 11611 static class OriginInfo { 11612 /** 11613 * Location where install is coming from, before it has been 11614 * copied/renamed into place. This could be a single monolithic APK 11615 * file, or a cluster directory. This location may be untrusted. 11616 */ 11617 final File file; 11618 final String cid; 11619 11620 /** 11621 * Flag indicating that {@link #file} or {@link #cid} has already been 11622 * staged, meaning downstream users don't need to defensively copy the 11623 * contents. 11624 */ 11625 final boolean staged; 11626 11627 /** 11628 * Flag indicating that {@link #file} or {@link #cid} is an already 11629 * installed app that is being moved. 11630 */ 11631 final boolean existing; 11632 11633 final String resolvedPath; 11634 final File resolvedFile; 11635 11636 static OriginInfo fromNothing() { 11637 return new OriginInfo(null, null, false, false); 11638 } 11639 11640 static OriginInfo fromUntrustedFile(File file) { 11641 return new OriginInfo(file, null, false, false); 11642 } 11643 11644 static OriginInfo fromExistingFile(File file) { 11645 return new OriginInfo(file, null, false, true); 11646 } 11647 11648 static OriginInfo fromStagedFile(File file) { 11649 return new OriginInfo(file, null, true, false); 11650 } 11651 11652 static OriginInfo fromStagedContainer(String cid) { 11653 return new OriginInfo(null, cid, true, false); 11654 } 11655 11656 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11657 this.file = file; 11658 this.cid = cid; 11659 this.staged = staged; 11660 this.existing = existing; 11661 11662 if (cid != null) { 11663 resolvedPath = PackageHelper.getSdDir(cid); 11664 resolvedFile = new File(resolvedPath); 11665 } else if (file != null) { 11666 resolvedPath = file.getAbsolutePath(); 11667 resolvedFile = file; 11668 } else { 11669 resolvedPath = null; 11670 resolvedFile = null; 11671 } 11672 } 11673 } 11674 11675 static class MoveInfo { 11676 final int moveId; 11677 final String fromUuid; 11678 final String toUuid; 11679 final String packageName; 11680 final String dataAppName; 11681 final int appId; 11682 final String seinfo; 11683 final int targetSdkVersion; 11684 11685 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11686 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11687 this.moveId = moveId; 11688 this.fromUuid = fromUuid; 11689 this.toUuid = toUuid; 11690 this.packageName = packageName; 11691 this.dataAppName = dataAppName; 11692 this.appId = appId; 11693 this.seinfo = seinfo; 11694 this.targetSdkVersion = targetSdkVersion; 11695 } 11696 } 11697 11698 static class VerificationInfo { 11699 /** A constant used to indicate that a uid value is not present. */ 11700 public static final int NO_UID = -1; 11701 11702 /** URI referencing where the package was downloaded from. */ 11703 final Uri originatingUri; 11704 11705 /** HTTP referrer URI associated with the originatingURI. */ 11706 final Uri referrer; 11707 11708 /** UID of the application that the install request originated from. */ 11709 final int originatingUid; 11710 11711 /** UID of application requesting the install */ 11712 final int installerUid; 11713 11714 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11715 this.originatingUri = originatingUri; 11716 this.referrer = referrer; 11717 this.originatingUid = originatingUid; 11718 this.installerUid = installerUid; 11719 } 11720 } 11721 11722 class InstallParams extends HandlerParams { 11723 final OriginInfo origin; 11724 final MoveInfo move; 11725 final IPackageInstallObserver2 observer; 11726 int installFlags; 11727 final String installerPackageName; 11728 final String volumeUuid; 11729 private InstallArgs mArgs; 11730 private int mRet; 11731 final String packageAbiOverride; 11732 final String[] grantedRuntimePermissions; 11733 final VerificationInfo verificationInfo; 11734 11735 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11736 int installFlags, String installerPackageName, String volumeUuid, 11737 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11738 String[] grantedPermissions) { 11739 super(user); 11740 this.origin = origin; 11741 this.move = move; 11742 this.observer = observer; 11743 this.installFlags = installFlags; 11744 this.installerPackageName = installerPackageName; 11745 this.volumeUuid = volumeUuid; 11746 this.verificationInfo = verificationInfo; 11747 this.packageAbiOverride = packageAbiOverride; 11748 this.grantedRuntimePermissions = grantedPermissions; 11749 } 11750 11751 @Override 11752 public String toString() { 11753 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11754 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11755 } 11756 11757 private int installLocationPolicy(PackageInfoLite pkgLite) { 11758 String packageName = pkgLite.packageName; 11759 int installLocation = pkgLite.installLocation; 11760 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11761 // reader 11762 synchronized (mPackages) { 11763 // Currently installed package which the new package is attempting to replace or 11764 // null if no such package is installed. 11765 PackageParser.Package installedPkg = mPackages.get(packageName); 11766 // Package which currently owns the data which the new package will own if installed. 11767 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11768 // will be null whereas dataOwnerPkg will contain information about the package 11769 // which was uninstalled while keeping its data. 11770 PackageParser.Package dataOwnerPkg = installedPkg; 11771 if (dataOwnerPkg == null) { 11772 PackageSetting ps = mSettings.mPackages.get(packageName); 11773 if (ps != null) { 11774 dataOwnerPkg = ps.pkg; 11775 } 11776 } 11777 11778 if (dataOwnerPkg != null) { 11779 // If installed, the package will get access to data left on the device by its 11780 // predecessor. As a security measure, this is permited only if this is not a 11781 // version downgrade or if the predecessor package is marked as debuggable and 11782 // a downgrade is explicitly requested. 11783 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11784 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11785 try { 11786 checkDowngrade(dataOwnerPkg, pkgLite); 11787 } catch (PackageManagerException e) { 11788 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11789 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11790 } 11791 } 11792 } 11793 11794 if (installedPkg != null) { 11795 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11796 // Check for updated system application. 11797 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11798 if (onSd) { 11799 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11800 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11801 } 11802 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11803 } else { 11804 if (onSd) { 11805 // Install flag overrides everything. 11806 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11807 } 11808 // If current upgrade specifies particular preference 11809 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11810 // Application explicitly specified internal. 11811 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11812 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11813 // App explictly prefers external. Let policy decide 11814 } else { 11815 // Prefer previous location 11816 if (isExternal(installedPkg)) { 11817 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11818 } 11819 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11820 } 11821 } 11822 } else { 11823 // Invalid install. Return error code 11824 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11825 } 11826 } 11827 } 11828 // All the special cases have been taken care of. 11829 // Return result based on recommended install location. 11830 if (onSd) { 11831 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11832 } 11833 return pkgLite.recommendedInstallLocation; 11834 } 11835 11836 /* 11837 * Invoke remote method to get package information and install 11838 * location values. Override install location based on default 11839 * policy if needed and then create install arguments based 11840 * on the install location. 11841 */ 11842 public void handleStartCopy() throws RemoteException { 11843 int ret = PackageManager.INSTALL_SUCCEEDED; 11844 11845 // If we're already staged, we've firmly committed to an install location 11846 if (origin.staged) { 11847 if (origin.file != null) { 11848 installFlags |= PackageManager.INSTALL_INTERNAL; 11849 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11850 } else if (origin.cid != null) { 11851 installFlags |= PackageManager.INSTALL_EXTERNAL; 11852 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11853 } else { 11854 throw new IllegalStateException("Invalid stage location"); 11855 } 11856 } 11857 11858 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11859 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11860 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11861 PackageInfoLite pkgLite = null; 11862 11863 if (onInt && onSd) { 11864 // Check if both bits are set. 11865 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11866 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11867 } else if (onSd && ephemeral) { 11868 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11869 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11870 } else { 11871 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11872 packageAbiOverride); 11873 11874 if (DEBUG_EPHEMERAL && ephemeral) { 11875 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11876 } 11877 11878 /* 11879 * If we have too little free space, try to free cache 11880 * before giving up. 11881 */ 11882 if (!origin.staged && pkgLite.recommendedInstallLocation 11883 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11884 // TODO: focus freeing disk space on the target device 11885 final StorageManager storage = StorageManager.from(mContext); 11886 final long lowThreshold = storage.getStorageLowBytes( 11887 Environment.getDataDirectory()); 11888 11889 final long sizeBytes = mContainerService.calculateInstalledSize( 11890 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11891 11892 try { 11893 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11894 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11895 installFlags, packageAbiOverride); 11896 } catch (InstallerException e) { 11897 Slog.w(TAG, "Failed to free cache", e); 11898 } 11899 11900 /* 11901 * The cache free must have deleted the file we 11902 * downloaded to install. 11903 * 11904 * TODO: fix the "freeCache" call to not delete 11905 * the file we care about. 11906 */ 11907 if (pkgLite.recommendedInstallLocation 11908 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11909 pkgLite.recommendedInstallLocation 11910 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11911 } 11912 } 11913 } 11914 11915 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11916 int loc = pkgLite.recommendedInstallLocation; 11917 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11918 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11919 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11920 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11921 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11922 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11923 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11924 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11925 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11926 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11927 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11928 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11929 } else { 11930 // Override with defaults if needed. 11931 loc = installLocationPolicy(pkgLite); 11932 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11933 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11934 } else if (!onSd && !onInt) { 11935 // Override install location with flags 11936 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11937 // Set the flag to install on external media. 11938 installFlags |= PackageManager.INSTALL_EXTERNAL; 11939 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11940 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11941 if (DEBUG_EPHEMERAL) { 11942 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11943 } 11944 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11945 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11946 |PackageManager.INSTALL_INTERNAL); 11947 } else { 11948 // Make sure the flag for installing on external 11949 // media is unset 11950 installFlags |= PackageManager.INSTALL_INTERNAL; 11951 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11952 } 11953 } 11954 } 11955 } 11956 11957 final InstallArgs args = createInstallArgs(this); 11958 mArgs = args; 11959 11960 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11961 // TODO: http://b/22976637 11962 // Apps installed for "all" users use the device owner to verify the app 11963 UserHandle verifierUser = getUser(); 11964 if (verifierUser == UserHandle.ALL) { 11965 verifierUser = UserHandle.SYSTEM; 11966 } 11967 11968 /* 11969 * Determine if we have any installed package verifiers. If we 11970 * do, then we'll defer to them to verify the packages. 11971 */ 11972 final int requiredUid = mRequiredVerifierPackage == null ? -1 11973 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11974 verifierUser.getIdentifier()); 11975 if (!origin.existing && requiredUid != -1 11976 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11977 final Intent verification = new Intent( 11978 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11979 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11980 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11981 PACKAGE_MIME_TYPE); 11982 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11983 11984 // Query all live verifiers based on current user state 11985 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11986 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11987 11988 if (DEBUG_VERIFY) { 11989 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11990 + verification.toString() + " with " + pkgLite.verifiers.length 11991 + " optional verifiers"); 11992 } 11993 11994 final int verificationId = mPendingVerificationToken++; 11995 11996 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11997 11998 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11999 installerPackageName); 12000 12001 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12002 installFlags); 12003 12004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12005 pkgLite.packageName); 12006 12007 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12008 pkgLite.versionCode); 12009 12010 if (verificationInfo != null) { 12011 if (verificationInfo.originatingUri != null) { 12012 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12013 verificationInfo.originatingUri); 12014 } 12015 if (verificationInfo.referrer != null) { 12016 verification.putExtra(Intent.EXTRA_REFERRER, 12017 verificationInfo.referrer); 12018 } 12019 if (verificationInfo.originatingUid >= 0) { 12020 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12021 verificationInfo.originatingUid); 12022 } 12023 if (verificationInfo.installerUid >= 0) { 12024 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12025 verificationInfo.installerUid); 12026 } 12027 } 12028 12029 final PackageVerificationState verificationState = new PackageVerificationState( 12030 requiredUid, args); 12031 12032 mPendingVerification.append(verificationId, verificationState); 12033 12034 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12035 receivers, verificationState); 12036 12037 /* 12038 * If any sufficient verifiers were listed in the package 12039 * manifest, attempt to ask them. 12040 */ 12041 if (sufficientVerifiers != null) { 12042 final int N = sufficientVerifiers.size(); 12043 if (N == 0) { 12044 Slog.i(TAG, "Additional verifiers required, but none installed."); 12045 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12046 } else { 12047 for (int i = 0; i < N; i++) { 12048 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12049 12050 final Intent sufficientIntent = new Intent(verification); 12051 sufficientIntent.setComponent(verifierComponent); 12052 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12053 } 12054 } 12055 } 12056 12057 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12058 mRequiredVerifierPackage, receivers); 12059 if (ret == PackageManager.INSTALL_SUCCEEDED 12060 && mRequiredVerifierPackage != null) { 12061 Trace.asyncTraceBegin( 12062 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12063 /* 12064 * Send the intent to the required verification agent, 12065 * but only start the verification timeout after the 12066 * target BroadcastReceivers have run. 12067 */ 12068 verification.setComponent(requiredVerifierComponent); 12069 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12070 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12071 new BroadcastReceiver() { 12072 @Override 12073 public void onReceive(Context context, Intent intent) { 12074 final Message msg = mHandler 12075 .obtainMessage(CHECK_PENDING_VERIFICATION); 12076 msg.arg1 = verificationId; 12077 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12078 } 12079 }, null, 0, null, null); 12080 12081 /* 12082 * We don't want the copy to proceed until verification 12083 * succeeds, so null out this field. 12084 */ 12085 mArgs = null; 12086 } 12087 } else { 12088 /* 12089 * No package verification is enabled, so immediately start 12090 * the remote call to initiate copy using temporary file. 12091 */ 12092 ret = args.copyApk(mContainerService, true); 12093 } 12094 } 12095 12096 mRet = ret; 12097 } 12098 12099 @Override 12100 void handleReturnCode() { 12101 // If mArgs is null, then MCS couldn't be reached. When it 12102 // reconnects, it will try again to install. At that point, this 12103 // will succeed. 12104 if (mArgs != null) { 12105 processPendingInstall(mArgs, mRet); 12106 } 12107 } 12108 12109 @Override 12110 void handleServiceError() { 12111 mArgs = createInstallArgs(this); 12112 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12113 } 12114 12115 public boolean isForwardLocked() { 12116 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12117 } 12118 } 12119 12120 /** 12121 * Used during creation of InstallArgs 12122 * 12123 * @param installFlags package installation flags 12124 * @return true if should be installed on external storage 12125 */ 12126 private static boolean installOnExternalAsec(int installFlags) { 12127 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12128 return false; 12129 } 12130 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12131 return true; 12132 } 12133 return false; 12134 } 12135 12136 /** 12137 * Used during creation of InstallArgs 12138 * 12139 * @param installFlags package installation flags 12140 * @return true if should be installed as forward locked 12141 */ 12142 private static boolean installForwardLocked(int installFlags) { 12143 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12144 } 12145 12146 private InstallArgs createInstallArgs(InstallParams params) { 12147 if (params.move != null) { 12148 return new MoveInstallArgs(params); 12149 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12150 return new AsecInstallArgs(params); 12151 } else { 12152 return new FileInstallArgs(params); 12153 } 12154 } 12155 12156 /** 12157 * Create args that describe an existing installed package. Typically used 12158 * when cleaning up old installs, or used as a move source. 12159 */ 12160 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12161 String resourcePath, String[] instructionSets) { 12162 final boolean isInAsec; 12163 if (installOnExternalAsec(installFlags)) { 12164 /* Apps on SD card are always in ASEC containers. */ 12165 isInAsec = true; 12166 } else if (installForwardLocked(installFlags) 12167 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12168 /* 12169 * Forward-locked apps are only in ASEC containers if they're the 12170 * new style 12171 */ 12172 isInAsec = true; 12173 } else { 12174 isInAsec = false; 12175 } 12176 12177 if (isInAsec) { 12178 return new AsecInstallArgs(codePath, instructionSets, 12179 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12180 } else { 12181 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12182 } 12183 } 12184 12185 static abstract class InstallArgs { 12186 /** @see InstallParams#origin */ 12187 final OriginInfo origin; 12188 /** @see InstallParams#move */ 12189 final MoveInfo move; 12190 12191 final IPackageInstallObserver2 observer; 12192 // Always refers to PackageManager flags only 12193 final int installFlags; 12194 final String installerPackageName; 12195 final String volumeUuid; 12196 final UserHandle user; 12197 final String abiOverride; 12198 final String[] installGrantPermissions; 12199 /** If non-null, drop an async trace when the install completes */ 12200 final String traceMethod; 12201 final int traceCookie; 12202 12203 // The list of instruction sets supported by this app. This is currently 12204 // only used during the rmdex() phase to clean up resources. We can get rid of this 12205 // if we move dex files under the common app path. 12206 /* nullable */ String[] instructionSets; 12207 12208 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12209 int installFlags, String installerPackageName, String volumeUuid, 12210 UserHandle user, String[] instructionSets, 12211 String abiOverride, String[] installGrantPermissions, 12212 String traceMethod, int traceCookie) { 12213 this.origin = origin; 12214 this.move = move; 12215 this.installFlags = installFlags; 12216 this.observer = observer; 12217 this.installerPackageName = installerPackageName; 12218 this.volumeUuid = volumeUuid; 12219 this.user = user; 12220 this.instructionSets = instructionSets; 12221 this.abiOverride = abiOverride; 12222 this.installGrantPermissions = installGrantPermissions; 12223 this.traceMethod = traceMethod; 12224 this.traceCookie = traceCookie; 12225 } 12226 12227 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12228 abstract int doPreInstall(int status); 12229 12230 /** 12231 * Rename package into final resting place. All paths on the given 12232 * scanned package should be updated to reflect the rename. 12233 */ 12234 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12235 abstract int doPostInstall(int status, int uid); 12236 12237 /** @see PackageSettingBase#codePathString */ 12238 abstract String getCodePath(); 12239 /** @see PackageSettingBase#resourcePathString */ 12240 abstract String getResourcePath(); 12241 12242 // Need installer lock especially for dex file removal. 12243 abstract void cleanUpResourcesLI(); 12244 abstract boolean doPostDeleteLI(boolean delete); 12245 12246 /** 12247 * Called before the source arguments are copied. This is used mostly 12248 * for MoveParams when it needs to read the source file to put it in the 12249 * destination. 12250 */ 12251 int doPreCopy() { 12252 return PackageManager.INSTALL_SUCCEEDED; 12253 } 12254 12255 /** 12256 * Called after the source arguments are copied. This is used mostly for 12257 * MoveParams when it needs to read the source file to put it in the 12258 * destination. 12259 * 12260 * @return 12261 */ 12262 int doPostCopy(int uid) { 12263 return PackageManager.INSTALL_SUCCEEDED; 12264 } 12265 12266 protected boolean isFwdLocked() { 12267 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12268 } 12269 12270 protected boolean isExternalAsec() { 12271 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12272 } 12273 12274 protected boolean isEphemeral() { 12275 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12276 } 12277 12278 UserHandle getUser() { 12279 return user; 12280 } 12281 } 12282 12283 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12284 if (!allCodePaths.isEmpty()) { 12285 if (instructionSets == null) { 12286 throw new IllegalStateException("instructionSet == null"); 12287 } 12288 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12289 for (String codePath : allCodePaths) { 12290 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12291 try { 12292 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12293 } catch (InstallerException ignored) { 12294 } 12295 } 12296 } 12297 } 12298 } 12299 12300 /** 12301 * Logic to handle installation of non-ASEC applications, including copying 12302 * and renaming logic. 12303 */ 12304 class FileInstallArgs extends InstallArgs { 12305 private File codeFile; 12306 private File resourceFile; 12307 12308 // Example topology: 12309 // /data/app/com.example/base.apk 12310 // /data/app/com.example/split_foo.apk 12311 // /data/app/com.example/lib/arm/libfoo.so 12312 // /data/app/com.example/lib/arm64/libfoo.so 12313 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12314 12315 /** New install */ 12316 FileInstallArgs(InstallParams params) { 12317 super(params.origin, params.move, params.observer, params.installFlags, 12318 params.installerPackageName, params.volumeUuid, 12319 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12320 params.grantedRuntimePermissions, 12321 params.traceMethod, params.traceCookie); 12322 if (isFwdLocked()) { 12323 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12324 } 12325 } 12326 12327 /** Existing install */ 12328 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12329 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12330 null, null, null, 0); 12331 this.codeFile = (codePath != null) ? new File(codePath) : null; 12332 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12333 } 12334 12335 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12337 try { 12338 return doCopyApk(imcs, temp); 12339 } finally { 12340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12341 } 12342 } 12343 12344 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12345 if (origin.staged) { 12346 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12347 codeFile = origin.file; 12348 resourceFile = origin.file; 12349 return PackageManager.INSTALL_SUCCEEDED; 12350 } 12351 12352 try { 12353 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12354 final File tempDir = 12355 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12356 codeFile = tempDir; 12357 resourceFile = tempDir; 12358 } catch (IOException e) { 12359 Slog.w(TAG, "Failed to create copy file: " + e); 12360 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12361 } 12362 12363 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12364 @Override 12365 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12366 if (!FileUtils.isValidExtFilename(name)) { 12367 throw new IllegalArgumentException("Invalid filename: " + name); 12368 } 12369 try { 12370 final File file = new File(codeFile, name); 12371 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12372 O_RDWR | O_CREAT, 0644); 12373 Os.chmod(file.getAbsolutePath(), 0644); 12374 return new ParcelFileDescriptor(fd); 12375 } catch (ErrnoException e) { 12376 throw new RemoteException("Failed to open: " + e.getMessage()); 12377 } 12378 } 12379 }; 12380 12381 int ret = PackageManager.INSTALL_SUCCEEDED; 12382 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12383 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12384 Slog.e(TAG, "Failed to copy package"); 12385 return ret; 12386 } 12387 12388 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12389 NativeLibraryHelper.Handle handle = null; 12390 try { 12391 handle = NativeLibraryHelper.Handle.create(codeFile); 12392 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12393 abiOverride); 12394 } catch (IOException e) { 12395 Slog.e(TAG, "Copying native libraries failed", e); 12396 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12397 } finally { 12398 IoUtils.closeQuietly(handle); 12399 } 12400 12401 return ret; 12402 } 12403 12404 int doPreInstall(int status) { 12405 if (status != PackageManager.INSTALL_SUCCEEDED) { 12406 cleanUp(); 12407 } 12408 return status; 12409 } 12410 12411 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12412 if (status != PackageManager.INSTALL_SUCCEEDED) { 12413 cleanUp(); 12414 return false; 12415 } 12416 12417 final File targetDir = codeFile.getParentFile(); 12418 final File beforeCodeFile = codeFile; 12419 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12420 12421 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12422 try { 12423 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12424 } catch (ErrnoException e) { 12425 Slog.w(TAG, "Failed to rename", e); 12426 return false; 12427 } 12428 12429 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12430 Slog.w(TAG, "Failed to restorecon"); 12431 return false; 12432 } 12433 12434 // Reflect the rename internally 12435 codeFile = afterCodeFile; 12436 resourceFile = afterCodeFile; 12437 12438 // Reflect the rename in scanned details 12439 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12440 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12441 afterCodeFile, pkg.baseCodePath)); 12442 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12443 afterCodeFile, pkg.splitCodePaths)); 12444 12445 // Reflect the rename in app info 12446 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12447 pkg.setApplicationInfoCodePath(pkg.codePath); 12448 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12449 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12450 pkg.setApplicationInfoResourcePath(pkg.codePath); 12451 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12452 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12453 12454 return true; 12455 } 12456 12457 int doPostInstall(int status, int uid) { 12458 if (status != PackageManager.INSTALL_SUCCEEDED) { 12459 cleanUp(); 12460 } 12461 return status; 12462 } 12463 12464 @Override 12465 String getCodePath() { 12466 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12467 } 12468 12469 @Override 12470 String getResourcePath() { 12471 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12472 } 12473 12474 private boolean cleanUp() { 12475 if (codeFile == null || !codeFile.exists()) { 12476 return false; 12477 } 12478 12479 removeCodePathLI(codeFile); 12480 12481 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12482 resourceFile.delete(); 12483 } 12484 12485 return true; 12486 } 12487 12488 void cleanUpResourcesLI() { 12489 // Try enumerating all code paths before deleting 12490 List<String> allCodePaths = Collections.EMPTY_LIST; 12491 if (codeFile != null && codeFile.exists()) { 12492 try { 12493 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12494 allCodePaths = pkg.getAllCodePaths(); 12495 } catch (PackageParserException e) { 12496 // Ignored; we tried our best 12497 } 12498 } 12499 12500 cleanUp(); 12501 removeDexFiles(allCodePaths, instructionSets); 12502 } 12503 12504 boolean doPostDeleteLI(boolean delete) { 12505 // XXX err, shouldn't we respect the delete flag? 12506 cleanUpResourcesLI(); 12507 return true; 12508 } 12509 } 12510 12511 private boolean isAsecExternal(String cid) { 12512 final String asecPath = PackageHelper.getSdFilesystem(cid); 12513 return !asecPath.startsWith(mAsecInternalPath); 12514 } 12515 12516 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12517 PackageManagerException { 12518 if (copyRet < 0) { 12519 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12520 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12521 throw new PackageManagerException(copyRet, message); 12522 } 12523 } 12524 } 12525 12526 /** 12527 * Extract the MountService "container ID" from the full code path of an 12528 * .apk. 12529 */ 12530 static String cidFromCodePath(String fullCodePath) { 12531 int eidx = fullCodePath.lastIndexOf("/"); 12532 String subStr1 = fullCodePath.substring(0, eidx); 12533 int sidx = subStr1.lastIndexOf("/"); 12534 return subStr1.substring(sidx+1, eidx); 12535 } 12536 12537 /** 12538 * Logic to handle installation of ASEC applications, including copying and 12539 * renaming logic. 12540 */ 12541 class AsecInstallArgs extends InstallArgs { 12542 static final String RES_FILE_NAME = "pkg.apk"; 12543 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12544 12545 String cid; 12546 String packagePath; 12547 String resourcePath; 12548 12549 /** New install */ 12550 AsecInstallArgs(InstallParams params) { 12551 super(params.origin, params.move, params.observer, params.installFlags, 12552 params.installerPackageName, params.volumeUuid, 12553 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12554 params.grantedRuntimePermissions, 12555 params.traceMethod, params.traceCookie); 12556 } 12557 12558 /** Existing install */ 12559 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12560 boolean isExternal, boolean isForwardLocked) { 12561 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12562 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12563 instructionSets, null, null, null, 0); 12564 // Hackily pretend we're still looking at a full code path 12565 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12566 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12567 } 12568 12569 // Extract cid from fullCodePath 12570 int eidx = fullCodePath.lastIndexOf("/"); 12571 String subStr1 = fullCodePath.substring(0, eidx); 12572 int sidx = subStr1.lastIndexOf("/"); 12573 cid = subStr1.substring(sidx+1, eidx); 12574 setMountPath(subStr1); 12575 } 12576 12577 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12578 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12579 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12580 instructionSets, null, null, null, 0); 12581 this.cid = cid; 12582 setMountPath(PackageHelper.getSdDir(cid)); 12583 } 12584 12585 void createCopyFile() { 12586 cid = mInstallerService.allocateExternalStageCidLegacy(); 12587 } 12588 12589 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12590 if (origin.staged && origin.cid != null) { 12591 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12592 cid = origin.cid; 12593 setMountPath(PackageHelper.getSdDir(cid)); 12594 return PackageManager.INSTALL_SUCCEEDED; 12595 } 12596 12597 if (temp) { 12598 createCopyFile(); 12599 } else { 12600 /* 12601 * Pre-emptively destroy the container since it's destroyed if 12602 * copying fails due to it existing anyway. 12603 */ 12604 PackageHelper.destroySdDir(cid); 12605 } 12606 12607 final String newMountPath = imcs.copyPackageToContainer( 12608 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12609 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12610 12611 if (newMountPath != null) { 12612 setMountPath(newMountPath); 12613 return PackageManager.INSTALL_SUCCEEDED; 12614 } else { 12615 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12616 } 12617 } 12618 12619 @Override 12620 String getCodePath() { 12621 return packagePath; 12622 } 12623 12624 @Override 12625 String getResourcePath() { 12626 return resourcePath; 12627 } 12628 12629 int doPreInstall(int status) { 12630 if (status != PackageManager.INSTALL_SUCCEEDED) { 12631 // Destroy container 12632 PackageHelper.destroySdDir(cid); 12633 } else { 12634 boolean mounted = PackageHelper.isContainerMounted(cid); 12635 if (!mounted) { 12636 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12637 Process.SYSTEM_UID); 12638 if (newMountPath != null) { 12639 setMountPath(newMountPath); 12640 } else { 12641 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12642 } 12643 } 12644 } 12645 return status; 12646 } 12647 12648 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12649 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12650 String newMountPath = null; 12651 if (PackageHelper.isContainerMounted(cid)) { 12652 // Unmount the container 12653 if (!PackageHelper.unMountSdDir(cid)) { 12654 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12655 return false; 12656 } 12657 } 12658 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12659 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12660 " which might be stale. Will try to clean up."); 12661 // Clean up the stale container and proceed to recreate. 12662 if (!PackageHelper.destroySdDir(newCacheId)) { 12663 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12664 return false; 12665 } 12666 // Successfully cleaned up stale container. Try to rename again. 12667 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12668 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12669 + " inspite of cleaning it up."); 12670 return false; 12671 } 12672 } 12673 if (!PackageHelper.isContainerMounted(newCacheId)) { 12674 Slog.w(TAG, "Mounting container " + newCacheId); 12675 newMountPath = PackageHelper.mountSdDir(newCacheId, 12676 getEncryptKey(), Process.SYSTEM_UID); 12677 } else { 12678 newMountPath = PackageHelper.getSdDir(newCacheId); 12679 } 12680 if (newMountPath == null) { 12681 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12682 return false; 12683 } 12684 Log.i(TAG, "Succesfully renamed " + cid + 12685 " to " + newCacheId + 12686 " at new path: " + newMountPath); 12687 cid = newCacheId; 12688 12689 final File beforeCodeFile = new File(packagePath); 12690 setMountPath(newMountPath); 12691 final File afterCodeFile = new File(packagePath); 12692 12693 // Reflect the rename in scanned details 12694 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12695 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12696 afterCodeFile, pkg.baseCodePath)); 12697 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12698 afterCodeFile, pkg.splitCodePaths)); 12699 12700 // Reflect the rename in app info 12701 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12702 pkg.setApplicationInfoCodePath(pkg.codePath); 12703 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12704 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12705 pkg.setApplicationInfoResourcePath(pkg.codePath); 12706 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12707 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12708 12709 return true; 12710 } 12711 12712 private void setMountPath(String mountPath) { 12713 final File mountFile = new File(mountPath); 12714 12715 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12716 if (monolithicFile.exists()) { 12717 packagePath = monolithicFile.getAbsolutePath(); 12718 if (isFwdLocked()) { 12719 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12720 } else { 12721 resourcePath = packagePath; 12722 } 12723 } else { 12724 packagePath = mountFile.getAbsolutePath(); 12725 resourcePath = packagePath; 12726 } 12727 } 12728 12729 int doPostInstall(int status, int uid) { 12730 if (status != PackageManager.INSTALL_SUCCEEDED) { 12731 cleanUp(); 12732 } else { 12733 final int groupOwner; 12734 final String protectedFile; 12735 if (isFwdLocked()) { 12736 groupOwner = UserHandle.getSharedAppGid(uid); 12737 protectedFile = RES_FILE_NAME; 12738 } else { 12739 groupOwner = -1; 12740 protectedFile = null; 12741 } 12742 12743 if (uid < Process.FIRST_APPLICATION_UID 12744 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12745 Slog.e(TAG, "Failed to finalize " + cid); 12746 PackageHelper.destroySdDir(cid); 12747 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12748 } 12749 12750 boolean mounted = PackageHelper.isContainerMounted(cid); 12751 if (!mounted) { 12752 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12753 } 12754 } 12755 return status; 12756 } 12757 12758 private void cleanUp() { 12759 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12760 12761 // Destroy secure container 12762 PackageHelper.destroySdDir(cid); 12763 } 12764 12765 private List<String> getAllCodePaths() { 12766 final File codeFile = new File(getCodePath()); 12767 if (codeFile != null && codeFile.exists()) { 12768 try { 12769 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12770 return pkg.getAllCodePaths(); 12771 } catch (PackageParserException e) { 12772 // Ignored; we tried our best 12773 } 12774 } 12775 return Collections.EMPTY_LIST; 12776 } 12777 12778 void cleanUpResourcesLI() { 12779 // Enumerate all code paths before deleting 12780 cleanUpResourcesLI(getAllCodePaths()); 12781 } 12782 12783 private void cleanUpResourcesLI(List<String> allCodePaths) { 12784 cleanUp(); 12785 removeDexFiles(allCodePaths, instructionSets); 12786 } 12787 12788 String getPackageName() { 12789 return getAsecPackageName(cid); 12790 } 12791 12792 boolean doPostDeleteLI(boolean delete) { 12793 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12794 final List<String> allCodePaths = getAllCodePaths(); 12795 boolean mounted = PackageHelper.isContainerMounted(cid); 12796 if (mounted) { 12797 // Unmount first 12798 if (PackageHelper.unMountSdDir(cid)) { 12799 mounted = false; 12800 } 12801 } 12802 if (!mounted && delete) { 12803 cleanUpResourcesLI(allCodePaths); 12804 } 12805 return !mounted; 12806 } 12807 12808 @Override 12809 int doPreCopy() { 12810 if (isFwdLocked()) { 12811 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12812 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12813 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12814 } 12815 } 12816 12817 return PackageManager.INSTALL_SUCCEEDED; 12818 } 12819 12820 @Override 12821 int doPostCopy(int uid) { 12822 if (isFwdLocked()) { 12823 if (uid < Process.FIRST_APPLICATION_UID 12824 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12825 RES_FILE_NAME)) { 12826 Slog.e(TAG, "Failed to finalize " + cid); 12827 PackageHelper.destroySdDir(cid); 12828 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12829 } 12830 } 12831 12832 return PackageManager.INSTALL_SUCCEEDED; 12833 } 12834 } 12835 12836 /** 12837 * Logic to handle movement of existing installed applications. 12838 */ 12839 class MoveInstallArgs extends InstallArgs { 12840 private File codeFile; 12841 private File resourceFile; 12842 12843 /** New install */ 12844 MoveInstallArgs(InstallParams params) { 12845 super(params.origin, params.move, params.observer, params.installFlags, 12846 params.installerPackageName, params.volumeUuid, 12847 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12848 params.grantedRuntimePermissions, 12849 params.traceMethod, params.traceCookie); 12850 } 12851 12852 int copyApk(IMediaContainerService imcs, boolean temp) { 12853 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12854 + move.fromUuid + " to " + move.toUuid); 12855 synchronized (mInstaller) { 12856 try { 12857 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12858 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12859 } catch (InstallerException e) { 12860 Slog.w(TAG, "Failed to move app", e); 12861 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12862 } 12863 } 12864 12865 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12866 resourceFile = codeFile; 12867 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12868 12869 return PackageManager.INSTALL_SUCCEEDED; 12870 } 12871 12872 int doPreInstall(int status) { 12873 if (status != PackageManager.INSTALL_SUCCEEDED) { 12874 cleanUp(move.toUuid); 12875 } 12876 return status; 12877 } 12878 12879 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12880 if (status != PackageManager.INSTALL_SUCCEEDED) { 12881 cleanUp(move.toUuid); 12882 return false; 12883 } 12884 12885 // Reflect the move in app info 12886 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12887 pkg.setApplicationInfoCodePath(pkg.codePath); 12888 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12889 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12890 pkg.setApplicationInfoResourcePath(pkg.codePath); 12891 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12892 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12893 12894 return true; 12895 } 12896 12897 int doPostInstall(int status, int uid) { 12898 if (status == PackageManager.INSTALL_SUCCEEDED) { 12899 cleanUp(move.fromUuid); 12900 } else { 12901 cleanUp(move.toUuid); 12902 } 12903 return status; 12904 } 12905 12906 @Override 12907 String getCodePath() { 12908 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12909 } 12910 12911 @Override 12912 String getResourcePath() { 12913 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12914 } 12915 12916 private boolean cleanUp(String volumeUuid) { 12917 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12918 move.dataAppName); 12919 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12920 synchronized (mInstallLock) { 12921 // Clean up both app data and code 12922 removeDataDirsLI(volumeUuid, move.packageName); 12923 removeCodePathLI(codeFile); 12924 } 12925 return true; 12926 } 12927 12928 void cleanUpResourcesLI() { 12929 throw new UnsupportedOperationException(); 12930 } 12931 12932 boolean doPostDeleteLI(boolean delete) { 12933 throw new UnsupportedOperationException(); 12934 } 12935 } 12936 12937 static String getAsecPackageName(String packageCid) { 12938 int idx = packageCid.lastIndexOf("-"); 12939 if (idx == -1) { 12940 return packageCid; 12941 } 12942 return packageCid.substring(0, idx); 12943 } 12944 12945 // Utility method used to create code paths based on package name and available index. 12946 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12947 String idxStr = ""; 12948 int idx = 1; 12949 // Fall back to default value of idx=1 if prefix is not 12950 // part of oldCodePath 12951 if (oldCodePath != null) { 12952 String subStr = oldCodePath; 12953 // Drop the suffix right away 12954 if (suffix != null && subStr.endsWith(suffix)) { 12955 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12956 } 12957 // If oldCodePath already contains prefix find out the 12958 // ending index to either increment or decrement. 12959 int sidx = subStr.lastIndexOf(prefix); 12960 if (sidx != -1) { 12961 subStr = subStr.substring(sidx + prefix.length()); 12962 if (subStr != null) { 12963 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12964 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12965 } 12966 try { 12967 idx = Integer.parseInt(subStr); 12968 if (idx <= 1) { 12969 idx++; 12970 } else { 12971 idx--; 12972 } 12973 } catch(NumberFormatException e) { 12974 } 12975 } 12976 } 12977 } 12978 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12979 return prefix + idxStr; 12980 } 12981 12982 private File getNextCodePath(File targetDir, String packageName) { 12983 int suffix = 1; 12984 File result; 12985 do { 12986 result = new File(targetDir, packageName + "-" + suffix); 12987 suffix++; 12988 } while (result.exists()); 12989 return result; 12990 } 12991 12992 // Utility method that returns the relative package path with respect 12993 // to the installation directory. Like say for /data/data/com.test-1.apk 12994 // string com.test-1 is returned. 12995 static String deriveCodePathName(String codePath) { 12996 if (codePath == null) { 12997 return null; 12998 } 12999 final File codeFile = new File(codePath); 13000 final String name = codeFile.getName(); 13001 if (codeFile.isDirectory()) { 13002 return name; 13003 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13004 final int lastDot = name.lastIndexOf('.'); 13005 return name.substring(0, lastDot); 13006 } else { 13007 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13008 return null; 13009 } 13010 } 13011 13012 static class PackageInstalledInfo { 13013 String name; 13014 int uid; 13015 // The set of users that originally had this package installed. 13016 int[] origUsers; 13017 // The set of users that now have this package installed. 13018 int[] newUsers; 13019 PackageParser.Package pkg; 13020 int returnCode; 13021 String returnMsg; 13022 PackageRemovedInfo removedInfo; 13023 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13024 13025 public void setError(int code, String msg) { 13026 setReturnCode(code); 13027 setReturnMessage(msg); 13028 Slog.w(TAG, msg); 13029 } 13030 13031 public void setError(String msg, PackageParserException e) { 13032 setReturnCode(e.error); 13033 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13034 Slog.w(TAG, msg, e); 13035 } 13036 13037 public void setError(String msg, PackageManagerException e) { 13038 returnCode = e.error; 13039 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13040 Slog.w(TAG, msg, e); 13041 } 13042 13043 public void setReturnCode(int returnCode) { 13044 this.returnCode = returnCode; 13045 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13046 for (int i = 0; i < childCount; i++) { 13047 addedChildPackages.valueAt(i).returnCode = returnCode; 13048 } 13049 } 13050 13051 private void setReturnMessage(String returnMsg) { 13052 this.returnMsg = returnMsg; 13053 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13054 for (int i = 0; i < childCount; i++) { 13055 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13056 } 13057 } 13058 13059 // In some error cases we want to convey more info back to the observer 13060 String origPackage; 13061 String origPermission; 13062 } 13063 13064 /* 13065 * Install a non-existing package. 13066 */ 13067 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13068 UserHandle user, String installerPackageName, String volumeUuid, 13069 PackageInstalledInfo res) { 13070 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13071 13072 // Remember this for later, in case we need to rollback this install 13073 String pkgName = pkg.packageName; 13074 13075 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13076 13077 synchronized(mPackages) { 13078 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13079 // A package with the same name is already installed, though 13080 // it has been renamed to an older name. The package we 13081 // are trying to install should be installed as an update to 13082 // the existing one, but that has not been requested, so bail. 13083 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13084 + " without first uninstalling package running as " 13085 + mSettings.mRenamedPackages.get(pkgName)); 13086 return; 13087 } 13088 if (mPackages.containsKey(pkgName)) { 13089 // Don't allow installation over an existing package with the same name. 13090 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13091 + " without first uninstalling."); 13092 return; 13093 } 13094 } 13095 13096 try { 13097 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13098 System.currentTimeMillis(), user); 13099 13100 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13101 13102 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13103 prepareAppDataAfterInstall(newPackage); 13104 13105 } else { 13106 // Remove package from internal structures, but keep around any 13107 // data that might have already existed 13108 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13109 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13110 } 13111 } catch (PackageManagerException e) { 13112 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13113 } 13114 13115 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13116 } 13117 13118 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13119 // Can't rotate keys during boot or if sharedUser. 13120 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13121 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13122 return false; 13123 } 13124 // app is using upgradeKeySets; make sure all are valid 13125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13126 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13127 for (int i = 0; i < upgradeKeySets.length; i++) { 13128 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13129 Slog.wtf(TAG, "Package " 13130 + (oldPs.name != null ? oldPs.name : "<null>") 13131 + " contains upgrade-key-set reference to unknown key-set: " 13132 + upgradeKeySets[i] 13133 + " reverting to signatures check."); 13134 return false; 13135 } 13136 } 13137 return true; 13138 } 13139 13140 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13141 // Upgrade keysets are being used. Determine if new package has a superset of the 13142 // required keys. 13143 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13144 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13145 for (int i = 0; i < upgradeKeySets.length; i++) { 13146 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13147 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13148 return true; 13149 } 13150 } 13151 return false; 13152 } 13153 13154 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13155 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13156 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13157 13158 final PackageParser.Package oldPackage; 13159 final String pkgName = pkg.packageName; 13160 final int[] allUsers; 13161 final boolean weFroze; 13162 13163 // First find the old package info and check signatures 13164 synchronized(mPackages) { 13165 oldPackage = mPackages.get(pkgName); 13166 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13167 if (isEphemeral && !oldIsEphemeral) { 13168 // can't downgrade from full to ephemeral 13169 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13170 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13171 return; 13172 } 13173 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13175 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13176 if (!checkUpgradeKeySetLP(ps, pkg)) { 13177 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13178 "New package not signed by keys specified by upgrade-keysets: " 13179 + pkgName); 13180 return; 13181 } 13182 } else { 13183 // default to original signature matching 13184 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13185 != PackageManager.SIGNATURE_MATCH) { 13186 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13187 "New package has a different signature: " + pkgName); 13188 return; 13189 } 13190 } 13191 13192 // In case of rollback, remember per-user/profile install state 13193 allUsers = sUserManager.getUserIds(); 13194 13195 // Mark the app as frozen to prevent launching during the upgrade 13196 // process, and then kill all running instances 13197 if (!ps.frozen) { 13198 ps.frozen = true; 13199 weFroze = true; 13200 } else { 13201 weFroze = false; 13202 } 13203 } 13204 13205 try { 13206 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13207 installerPackageName, res); 13208 } finally { 13209 // Regardless of success or failure of upgrade steps above, always 13210 // unfreeze the package if we froze it 13211 if (weFroze) { 13212 unfreezePackage(pkgName); 13213 } 13214 } 13215 } 13216 13217 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13218 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13219 String installerPackageName, PackageInstalledInfo res) { 13220 // Update what is removed 13221 res.removedInfo = new PackageRemovedInfo(); 13222 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13223 res.removedInfo.removedPackage = oldPackage.packageName; 13224 res.removedInfo.isUpdate = true; 13225 final int childCount = (oldPackage.childPackages != null) 13226 ? oldPackage.childPackages.size() : 0; 13227 for (int i = 0; i < childCount; i++) { 13228 boolean childPackageUpdated = false; 13229 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13230 if (res.addedChildPackages != null) { 13231 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13232 if (childRes != null) { 13233 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13234 childRes.removedInfo.removedPackage = childPkg.packageName; 13235 childRes.removedInfo.isUpdate = true; 13236 childPackageUpdated = true; 13237 } 13238 } 13239 if (!childPackageUpdated) { 13240 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13241 childRemovedRes.removedPackage = childPkg.packageName; 13242 childRemovedRes.isUpdate = false; 13243 childRemovedRes.dataRemoved = true; 13244 synchronized (mPackages) { 13245 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13246 if (childPs != null) { 13247 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13248 } 13249 } 13250 if (res.removedInfo.removedChildPackages == null) { 13251 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13252 } 13253 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13254 } 13255 } 13256 13257 boolean sysPkg = (isSystemApp(oldPackage)); 13258 if (sysPkg) { 13259 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13260 user, allUsers, installerPackageName, res); 13261 } else { 13262 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13263 user, allUsers, installerPackageName, res); 13264 } 13265 } 13266 13267 public List<String> getPreviousCodePaths(String packageName) { 13268 final PackageSetting ps = mSettings.mPackages.get(packageName); 13269 final List<String> result = new ArrayList<String>(); 13270 if (ps != null && ps.oldCodePaths != null) { 13271 result.addAll(ps.oldCodePaths); 13272 } 13273 return result; 13274 } 13275 13276 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13277 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13278 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13279 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13280 + deletedPackage); 13281 13282 String pkgName = deletedPackage.packageName; 13283 boolean deletedPkg = true; 13284 boolean addedPkg = false; 13285 boolean updatedSettings = false; 13286 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13287 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13288 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13289 13290 final long origUpdateTime = (pkg.mExtras != null) 13291 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13292 13293 // First delete the existing package while retaining the data directory 13294 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13295 res.removedInfo, true, pkg)) { 13296 // If the existing package wasn't successfully deleted 13297 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13298 deletedPkg = false; 13299 } else { 13300 // Successfully deleted the old package; proceed with replace. 13301 13302 // If deleted package lived in a container, give users a chance to 13303 // relinquish resources before killing. 13304 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13305 if (DEBUG_INSTALL) { 13306 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13307 } 13308 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13309 final ArrayList<String> pkgList = new ArrayList<String>(1); 13310 pkgList.add(deletedPackage.applicationInfo.packageName); 13311 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13312 } 13313 13314 deleteCodeCacheDirsLI(pkg); 13315 deleteProfilesLI(pkg, /*destroy*/ false); 13316 13317 try { 13318 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13319 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13320 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13321 13322 // Update the in-memory copy of the previous code paths. 13323 PackageSetting ps = mSettings.mPackages.get(pkgName); 13324 if (!killApp) { 13325 if (ps.oldCodePaths == null) { 13326 ps.oldCodePaths = new ArraySet<>(); 13327 } 13328 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13329 if (deletedPackage.splitCodePaths != null) { 13330 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13331 } 13332 } else { 13333 ps.oldCodePaths = null; 13334 } 13335 if (ps.childPackageNames != null) { 13336 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13337 final String childPkgName = ps.childPackageNames.get(i); 13338 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13339 childPs.oldCodePaths = ps.oldCodePaths; 13340 } 13341 } 13342 prepareAppDataAfterInstall(newPackage); 13343 addedPkg = true; 13344 } catch (PackageManagerException e) { 13345 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13346 } 13347 } 13348 13349 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13350 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13351 13352 // Revert all internal state mutations and added folders for the failed install 13353 if (addedPkg) { 13354 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13355 res.removedInfo, true, null); 13356 } 13357 13358 // Restore the old package 13359 if (deletedPkg) { 13360 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13361 File restoreFile = new File(deletedPackage.codePath); 13362 // Parse old package 13363 boolean oldExternal = isExternal(deletedPackage); 13364 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13365 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13366 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13367 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13368 try { 13369 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13370 null); 13371 } catch (PackageManagerException e) { 13372 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13373 + e.getMessage()); 13374 return; 13375 } 13376 13377 synchronized (mPackages) { 13378 // Ensure the installer package name up to date 13379 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13380 13381 // Update permissions for restored package 13382 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13383 13384 mSettings.writeLPr(); 13385 } 13386 13387 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13388 } 13389 } else { 13390 synchronized (mPackages) { 13391 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13392 if (ps != null) { 13393 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13394 if (res.removedInfo.removedChildPackages != null) { 13395 final int childCount = res.removedInfo.removedChildPackages.size(); 13396 // Iterate in reverse as we may modify the collection 13397 for (int i = childCount - 1; i >= 0; i--) { 13398 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13399 if (res.addedChildPackages.containsKey(childPackageName)) { 13400 res.removedInfo.removedChildPackages.removeAt(i); 13401 } else { 13402 PackageRemovedInfo childInfo = res.removedInfo 13403 .removedChildPackages.valueAt(i); 13404 childInfo.removedForAllUsers = mPackages.get( 13405 childInfo.removedPackage) == null; 13406 } 13407 } 13408 } 13409 } 13410 } 13411 } 13412 } 13413 13414 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13415 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13416 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13417 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13418 + ", old=" + deletedPackage); 13419 13420 final boolean disabledSystem; 13421 13422 // Set the system/privileged flags as needed 13423 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13424 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13425 != 0) { 13426 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13427 } 13428 13429 // Kill package processes including services, providers, etc. 13430 killPackage(deletedPackage, "replace sys pkg"); 13431 13432 // Remove existing system package 13433 removePackageLI(deletedPackage, true); 13434 13435 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13436 if (!disabledSystem) { 13437 // We didn't need to disable the .apk as a current system package, 13438 // which means we are replacing another update that is already 13439 // installed. We need to make sure to delete the older one's .apk. 13440 res.removedInfo.args = createInstallArgsForExisting(0, 13441 deletedPackage.applicationInfo.getCodePath(), 13442 deletedPackage.applicationInfo.getResourcePath(), 13443 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13444 } else { 13445 res.removedInfo.args = null; 13446 } 13447 13448 // Successfully disabled the old package. Now proceed with re-installation 13449 deleteCodeCacheDirsLI(pkg); 13450 deleteProfilesLI(pkg, /*destroy*/ false); 13451 13452 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13453 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13454 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13455 13456 PackageParser.Package newPackage = null; 13457 try { 13458 // Add the package to the internal data structures 13459 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13460 13461 // Set the update and install times 13462 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13463 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13464 System.currentTimeMillis()); 13465 13466 // Check for shared user id changes 13467 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13468 deletedPackage, newPackage); 13469 if (invalidPackageName != null) { 13470 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13471 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13472 + " to " + invalidPackageName); 13473 } 13474 13475 // Update the package dynamic state if succeeded 13476 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13477 // Now that the install succeeded make sure we remove data 13478 // directories for any child package the update removed. 13479 final int deletedChildCount = (deletedPackage.childPackages != null) 13480 ? deletedPackage.childPackages.size() : 0; 13481 final int newChildCount = (newPackage.childPackages != null) 13482 ? newPackage.childPackages.size() : 0; 13483 for (int i = 0; i < deletedChildCount; i++) { 13484 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13485 boolean childPackageDeleted = true; 13486 for (int j = 0; j < newChildCount; j++) { 13487 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13488 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13489 childPackageDeleted = false; 13490 break; 13491 } 13492 } 13493 if (childPackageDeleted) { 13494 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13495 deletedChildPkg.packageName); 13496 if (ps != null && res.removedInfo.removedChildPackages != null) { 13497 PackageRemovedInfo removedChildRes = res.removedInfo 13498 .removedChildPackages.get(deletedChildPkg.packageName); 13499 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13500 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13501 } 13502 } 13503 } 13504 13505 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13506 prepareAppDataAfterInstall(newPackage); 13507 } 13508 } catch (PackageManagerException e) { 13509 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13510 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13511 } 13512 13513 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13514 // Re installation failed. Restore old information 13515 // Remove new pkg information 13516 if (newPackage != null) { 13517 removeInstalledPackageLI(newPackage, true); 13518 } 13519 // Add back the old system package 13520 try { 13521 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13522 } catch (PackageManagerException e) { 13523 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13524 } 13525 13526 synchronized (mPackages) { 13527 if (disabledSystem) { 13528 enableSystemPackageLPw(deletedPackage); 13529 } 13530 13531 // Ensure the installer package name up to date 13532 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13533 13534 // Update permissions for restored package 13535 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13536 13537 mSettings.writeLPr(); 13538 } 13539 13540 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13541 + " after failed upgrade"); 13542 } 13543 } 13544 13545 /** 13546 * Checks whether the parent or any of the child packages have a change shared 13547 * user. For a package to be a valid update the shred users of the parent and 13548 * the children should match. We may later support changing child shared users. 13549 * @param oldPkg The updated package. 13550 * @param newPkg The update package. 13551 * @return The shared user that change between the versions. 13552 */ 13553 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13554 PackageParser.Package newPkg) { 13555 // Check parent shared user 13556 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13557 return newPkg.packageName; 13558 } 13559 // Check child shared users 13560 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13561 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13562 for (int i = 0; i < newChildCount; i++) { 13563 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13564 // If this child was present, did it have the same shared user? 13565 for (int j = 0; j < oldChildCount; j++) { 13566 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13567 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13568 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13569 return newChildPkg.packageName; 13570 } 13571 } 13572 } 13573 return null; 13574 } 13575 13576 private void removeNativeBinariesLI(PackageSetting ps) { 13577 // Remove the lib path for the parent package 13578 if (ps != null) { 13579 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13580 // Remove the lib path for the child packages 13581 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13582 for (int i = 0; i < childCount; i++) { 13583 PackageSetting childPs = null; 13584 synchronized (mPackages) { 13585 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13586 } 13587 if (childPs != null) { 13588 NativeLibraryHelper.removeNativeBinariesLI(childPs 13589 .legacyNativeLibraryPathString); 13590 } 13591 } 13592 } 13593 } 13594 13595 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13596 // Enable the parent package 13597 mSettings.enableSystemPackageLPw(pkg.packageName); 13598 // Enable the child packages 13599 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13600 for (int i = 0; i < childCount; i++) { 13601 PackageParser.Package childPkg = pkg.childPackages.get(i); 13602 mSettings.enableSystemPackageLPw(childPkg.packageName); 13603 } 13604 } 13605 13606 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13607 PackageParser.Package newPkg) { 13608 // Disable the parent package (parent always replaced) 13609 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13610 // Disable the child packages 13611 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13612 for (int i = 0; i < childCount; i++) { 13613 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13614 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13615 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13616 } 13617 return disabled; 13618 } 13619 13620 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13621 String installerPackageName) { 13622 // Enable the parent package 13623 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13624 // Enable the child packages 13625 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13626 for (int i = 0; i < childCount; i++) { 13627 PackageParser.Package childPkg = pkg.childPackages.get(i); 13628 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13629 } 13630 } 13631 13632 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13633 // Collect all used permissions in the UID 13634 ArraySet<String> usedPermissions = new ArraySet<>(); 13635 final int packageCount = su.packages.size(); 13636 for (int i = 0; i < packageCount; i++) { 13637 PackageSetting ps = su.packages.valueAt(i); 13638 if (ps.pkg == null) { 13639 continue; 13640 } 13641 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13642 for (int j = 0; j < requestedPermCount; j++) { 13643 String permission = ps.pkg.requestedPermissions.get(j); 13644 BasePermission bp = mSettings.mPermissions.get(permission); 13645 if (bp != null) { 13646 usedPermissions.add(permission); 13647 } 13648 } 13649 } 13650 13651 PermissionsState permissionsState = su.getPermissionsState(); 13652 // Prune install permissions 13653 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13654 final int installPermCount = installPermStates.size(); 13655 for (int i = installPermCount - 1; i >= 0; i--) { 13656 PermissionState permissionState = installPermStates.get(i); 13657 if (!usedPermissions.contains(permissionState.getName())) { 13658 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13659 if (bp != null) { 13660 permissionsState.revokeInstallPermission(bp); 13661 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13662 PackageManager.MASK_PERMISSION_FLAGS, 0); 13663 } 13664 } 13665 } 13666 13667 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13668 13669 // Prune runtime permissions 13670 for (int userId : allUserIds) { 13671 List<PermissionState> runtimePermStates = permissionsState 13672 .getRuntimePermissionStates(userId); 13673 final int runtimePermCount = runtimePermStates.size(); 13674 for (int i = runtimePermCount - 1; i >= 0; i--) { 13675 PermissionState permissionState = runtimePermStates.get(i); 13676 if (!usedPermissions.contains(permissionState.getName())) { 13677 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13678 if (bp != null) { 13679 permissionsState.revokeRuntimePermission(bp, userId); 13680 permissionsState.updatePermissionFlags(bp, userId, 13681 PackageManager.MASK_PERMISSION_FLAGS, 0); 13682 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13683 runtimePermissionChangedUserIds, userId); 13684 } 13685 } 13686 } 13687 } 13688 13689 return runtimePermissionChangedUserIds; 13690 } 13691 13692 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13693 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13694 // Update the parent package setting 13695 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13696 res, user); 13697 // Update the child packages setting 13698 final int childCount = (newPackage.childPackages != null) 13699 ? newPackage.childPackages.size() : 0; 13700 for (int i = 0; i < childCount; i++) { 13701 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13702 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13703 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13704 childRes.origUsers, childRes, user); 13705 } 13706 } 13707 13708 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13709 String installerPackageName, int[] allUsers, int[] installedForUsers, 13710 PackageInstalledInfo res, UserHandle user) { 13711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13712 13713 String pkgName = newPackage.packageName; 13714 synchronized (mPackages) { 13715 //write settings. the installStatus will be incomplete at this stage. 13716 //note that the new package setting would have already been 13717 //added to mPackages. It hasn't been persisted yet. 13718 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13720 mSettings.writeLPr(); 13721 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13722 } 13723 13724 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13725 synchronized (mPackages) { 13726 updatePermissionsLPw(newPackage.packageName, newPackage, 13727 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13728 ? UPDATE_PERMISSIONS_ALL : 0)); 13729 // For system-bundled packages, we assume that installing an upgraded version 13730 // of the package implies that the user actually wants to run that new code, 13731 // so we enable the package. 13732 PackageSetting ps = mSettings.mPackages.get(pkgName); 13733 final int userId = user.getIdentifier(); 13734 if (ps != null) { 13735 if (isSystemApp(newPackage)) { 13736 if (DEBUG_INSTALL) { 13737 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13738 } 13739 // Enable system package for requested users 13740 if (res.origUsers != null) { 13741 for (int origUserId : res.origUsers) { 13742 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13743 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13744 origUserId, installerPackageName); 13745 } 13746 } 13747 } 13748 // Also convey the prior install/uninstall state 13749 if (allUsers != null && installedForUsers != null) { 13750 for (int currentUserId : allUsers) { 13751 final boolean installed = ArrayUtils.contains( 13752 installedForUsers, currentUserId); 13753 if (DEBUG_INSTALL) { 13754 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13755 } 13756 ps.setInstalled(installed, currentUserId); 13757 } 13758 // these install state changes will be persisted in the 13759 // upcoming call to mSettings.writeLPr(). 13760 } 13761 } 13762 // It's implied that when a user requests installation, they want the app to be 13763 // installed and enabled. 13764 if (userId != UserHandle.USER_ALL) { 13765 ps.setInstalled(true, userId); 13766 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13767 } 13768 } 13769 res.name = pkgName; 13770 res.uid = newPackage.applicationInfo.uid; 13771 res.pkg = newPackage; 13772 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13773 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13774 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13775 //to update install status 13776 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13777 mSettings.writeLPr(); 13778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13779 } 13780 13781 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13782 } 13783 13784 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13785 try { 13786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13787 installPackageLI(args, res); 13788 } finally { 13789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13790 } 13791 } 13792 13793 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13794 final int installFlags = args.installFlags; 13795 final String installerPackageName = args.installerPackageName; 13796 final String volumeUuid = args.volumeUuid; 13797 final File tmpPackageFile = new File(args.getCodePath()); 13798 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13799 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13800 || (args.volumeUuid != null)); 13801 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13802 boolean replace = false; 13803 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13804 if (args.move != null) { 13805 // moving a complete application; perform an initial scan on the new install location 13806 scanFlags |= SCAN_INITIAL; 13807 } 13808 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13809 scanFlags |= SCAN_DONT_KILL_APP; 13810 } 13811 13812 // Result object to be returned 13813 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13814 13815 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13816 13817 // Sanity check 13818 if (ephemeral && (forwardLocked || onExternal)) { 13819 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13820 + " external=" + onExternal); 13821 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13822 return; 13823 } 13824 13825 // Retrieve PackageSettings and parse package 13826 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13827 | PackageParser.PARSE_ENFORCE_CODE 13828 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13829 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13830 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13831 PackageParser pp = new PackageParser(); 13832 pp.setSeparateProcesses(mSeparateProcesses); 13833 pp.setDisplayMetrics(mMetrics); 13834 13835 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13836 final PackageParser.Package pkg; 13837 try { 13838 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13839 } catch (PackageParserException e) { 13840 res.setError("Failed parse during installPackageLI", e); 13841 return; 13842 } finally { 13843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13844 } 13845 13846 // If we are installing a clustered package add results for the children 13847 if (pkg.childPackages != null) { 13848 synchronized (mPackages) { 13849 final int childCount = pkg.childPackages.size(); 13850 for (int i = 0; i < childCount; i++) { 13851 PackageParser.Package childPkg = pkg.childPackages.get(i); 13852 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13853 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13854 childRes.pkg = childPkg; 13855 childRes.name = childPkg.packageName; 13856 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13857 if (childPs != null) { 13858 childRes.origUsers = childPs.queryInstalledUsers( 13859 sUserManager.getUserIds(), true); 13860 } 13861 if ((mPackages.containsKey(childPkg.packageName))) { 13862 childRes.removedInfo = new PackageRemovedInfo(); 13863 childRes.removedInfo.removedPackage = childPkg.packageName; 13864 } 13865 if (res.addedChildPackages == null) { 13866 res.addedChildPackages = new ArrayMap<>(); 13867 } 13868 res.addedChildPackages.put(childPkg.packageName, childRes); 13869 } 13870 } 13871 } 13872 13873 // If package doesn't declare API override, mark that we have an install 13874 // time CPU ABI override. 13875 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13876 pkg.cpuAbiOverride = args.abiOverride; 13877 } 13878 13879 String pkgName = res.name = pkg.packageName; 13880 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13881 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13882 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13883 return; 13884 } 13885 } 13886 13887 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13888 try { 13889 PackageParser.collectCertificates(pkg, parseFlags); 13890 } catch (PackageParserException e) { 13891 res.setError("Failed collect during installPackageLI", e); 13892 return; 13893 } finally { 13894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13895 } 13896 13897 // Get rid of all references to package scan path via parser. 13898 pp = null; 13899 String oldCodePath = null; 13900 boolean systemApp = false; 13901 synchronized (mPackages) { 13902 // Check if installing already existing package 13903 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13904 String oldName = mSettings.mRenamedPackages.get(pkgName); 13905 if (pkg.mOriginalPackages != null 13906 && pkg.mOriginalPackages.contains(oldName) 13907 && mPackages.containsKey(oldName)) { 13908 // This package is derived from an original package, 13909 // and this device has been updating from that original 13910 // name. We must continue using the original name, so 13911 // rename the new package here. 13912 pkg.setPackageName(oldName); 13913 pkgName = pkg.packageName; 13914 replace = true; 13915 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13916 + oldName + " pkgName=" + pkgName); 13917 } else if (mPackages.containsKey(pkgName)) { 13918 // This package, under its official name, already exists 13919 // on the device; we should replace it. 13920 replace = true; 13921 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13922 } 13923 13924 // Child packages are installed through the parent package 13925 if (pkg.parentPackage != null) { 13926 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13927 "Package " + pkg.packageName + " is child of package " 13928 + pkg.parentPackage.parentPackage + ". Child packages " 13929 + "can be updated only through the parent package."); 13930 return; 13931 } 13932 13933 if (replace) { 13934 // Prevent apps opting out from runtime permissions 13935 PackageParser.Package oldPackage = mPackages.get(pkgName); 13936 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13937 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13938 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13939 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13940 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13941 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13942 + " doesn't support runtime permissions but the old" 13943 + " target SDK " + oldTargetSdk + " does."); 13944 return; 13945 } 13946 13947 // Prevent installing of child packages 13948 if (oldPackage.parentPackage != null) { 13949 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13950 "Package " + pkg.packageName + " is child of package " 13951 + oldPackage.parentPackage + ". Child packages " 13952 + "can be updated only through the parent package."); 13953 return; 13954 } 13955 } 13956 } 13957 13958 PackageSetting ps = mSettings.mPackages.get(pkgName); 13959 if (ps != null) { 13960 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13961 13962 // Quick sanity check that we're signed correctly if updating; 13963 // we'll check this again later when scanning, but we want to 13964 // bail early here before tripping over redefined permissions. 13965 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13966 if (!checkUpgradeKeySetLP(ps, pkg)) { 13967 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13968 + pkg.packageName + " upgrade keys do not match the " 13969 + "previously installed version"); 13970 return; 13971 } 13972 } else { 13973 try { 13974 verifySignaturesLP(ps, pkg); 13975 } catch (PackageManagerException e) { 13976 res.setError(e.error, e.getMessage()); 13977 return; 13978 } 13979 } 13980 13981 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13982 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13983 systemApp = (ps.pkg.applicationInfo.flags & 13984 ApplicationInfo.FLAG_SYSTEM) != 0; 13985 } 13986 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13987 } 13988 13989 // Check whether the newly-scanned package wants to define an already-defined perm 13990 int N = pkg.permissions.size(); 13991 for (int i = N-1; i >= 0; i--) { 13992 PackageParser.Permission perm = pkg.permissions.get(i); 13993 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13994 if (bp != null) { 13995 // If the defining package is signed with our cert, it's okay. This 13996 // also includes the "updating the same package" case, of course. 13997 // "updating same package" could also involve key-rotation. 13998 final boolean sigsOk; 13999 if (bp.sourcePackage.equals(pkg.packageName) 14000 && (bp.packageSetting instanceof PackageSetting) 14001 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14002 scanFlags))) { 14003 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14004 } else { 14005 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14006 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14007 } 14008 if (!sigsOk) { 14009 // If the owning package is the system itself, we log but allow 14010 // install to proceed; we fail the install on all other permission 14011 // redefinitions. 14012 if (!bp.sourcePackage.equals("android")) { 14013 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14014 + pkg.packageName + " attempting to redeclare permission " 14015 + perm.info.name + " already owned by " + bp.sourcePackage); 14016 res.origPermission = perm.info.name; 14017 res.origPackage = bp.sourcePackage; 14018 return; 14019 } else { 14020 Slog.w(TAG, "Package " + pkg.packageName 14021 + " attempting to redeclare system permission " 14022 + perm.info.name + "; ignoring new declaration"); 14023 pkg.permissions.remove(i); 14024 } 14025 } 14026 } 14027 } 14028 } 14029 14030 if (systemApp) { 14031 if (onExternal) { 14032 // Abort update; system app can't be replaced with app on sdcard 14033 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14034 "Cannot install updates to system apps on sdcard"); 14035 return; 14036 } else if (ephemeral) { 14037 // Abort update; system app can't be replaced with an ephemeral app 14038 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14039 "Cannot update a system app with an ephemeral app"); 14040 return; 14041 } 14042 } 14043 14044 if (args.move != null) { 14045 // We did an in-place move, so dex is ready to roll 14046 scanFlags |= SCAN_NO_DEX; 14047 scanFlags |= SCAN_MOVE; 14048 14049 synchronized (mPackages) { 14050 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14051 if (ps == null) { 14052 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14053 "Missing settings for moved package " + pkgName); 14054 } 14055 14056 // We moved the entire application as-is, so bring over the 14057 // previously derived ABI information. 14058 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14059 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14060 } 14061 14062 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14063 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14064 scanFlags |= SCAN_NO_DEX; 14065 14066 try { 14067 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14068 args.abiOverride : pkg.cpuAbiOverride); 14069 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14070 true /* extract libs */); 14071 } catch (PackageManagerException pme) { 14072 Slog.e(TAG, "Error deriving application ABI", pme); 14073 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14074 return; 14075 } 14076 14077 14078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14079 // Do not run PackageDexOptimizer through the local performDexOpt 14080 // method because `pkg` is not in `mPackages` yet. 14081 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14082 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14083 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14084 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14085 String msg = "Extracking package failed for " + pkgName; 14086 res.setError(INSTALL_FAILED_DEXOPT, msg); 14087 return; 14088 } 14089 } 14090 14091 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14092 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14093 return; 14094 } 14095 14096 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14097 14098 if (replace) { 14099 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14100 installerPackageName, res); 14101 } else { 14102 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14103 args.user, installerPackageName, volumeUuid, res); 14104 } 14105 synchronized (mPackages) { 14106 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14107 if (ps != null) { 14108 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14109 } 14110 14111 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14112 for (int i = 0; i < childCount; i++) { 14113 PackageParser.Package childPkg = pkg.childPackages.get(i); 14114 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14115 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14116 if (childPs != null) { 14117 childRes.newUsers = childPs.queryInstalledUsers( 14118 sUserManager.getUserIds(), true); 14119 } 14120 } 14121 } 14122 } 14123 14124 private void startIntentFilterVerifications(int userId, boolean replacing, 14125 PackageParser.Package pkg) { 14126 if (mIntentFilterVerifierComponent == null) { 14127 Slog.w(TAG, "No IntentFilter verification will not be done as " 14128 + "there is no IntentFilterVerifier available!"); 14129 return; 14130 } 14131 14132 final int verifierUid = getPackageUid( 14133 mIntentFilterVerifierComponent.getPackageName(), 14134 MATCH_DEBUG_TRIAGED_MISSING, 14135 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14136 14137 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14138 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14139 mHandler.sendMessage(msg); 14140 14141 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14142 for (int i = 0; i < childCount; i++) { 14143 PackageParser.Package childPkg = pkg.childPackages.get(i); 14144 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14145 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14146 mHandler.sendMessage(msg); 14147 } 14148 } 14149 14150 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14151 PackageParser.Package pkg) { 14152 int size = pkg.activities.size(); 14153 if (size == 0) { 14154 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14155 "No activity, so no need to verify any IntentFilter!"); 14156 return; 14157 } 14158 14159 final boolean hasDomainURLs = hasDomainURLs(pkg); 14160 if (!hasDomainURLs) { 14161 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14162 "No domain URLs, so no need to verify any IntentFilter!"); 14163 return; 14164 } 14165 14166 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14167 + " if any IntentFilter from the " + size 14168 + " Activities needs verification ..."); 14169 14170 int count = 0; 14171 final String packageName = pkg.packageName; 14172 14173 synchronized (mPackages) { 14174 // If this is a new install and we see that we've already run verification for this 14175 // package, we have nothing to do: it means the state was restored from backup. 14176 if (!replacing) { 14177 IntentFilterVerificationInfo ivi = 14178 mSettings.getIntentFilterVerificationLPr(packageName); 14179 if (ivi != null) { 14180 if (DEBUG_DOMAIN_VERIFICATION) { 14181 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14182 + ivi.getStatusString()); 14183 } 14184 return; 14185 } 14186 } 14187 14188 // If any filters need to be verified, then all need to be. 14189 boolean needToVerify = false; 14190 for (PackageParser.Activity a : pkg.activities) { 14191 for (ActivityIntentInfo filter : a.intents) { 14192 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14193 if (DEBUG_DOMAIN_VERIFICATION) { 14194 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14195 } 14196 needToVerify = true; 14197 break; 14198 } 14199 } 14200 } 14201 14202 if (needToVerify) { 14203 final int verificationId = mIntentFilterVerificationToken++; 14204 for (PackageParser.Activity a : pkg.activities) { 14205 for (ActivityIntentInfo filter : a.intents) { 14206 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14207 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14208 "Verification needed for IntentFilter:" + filter.toString()); 14209 mIntentFilterVerifier.addOneIntentFilterVerification( 14210 verifierUid, userId, verificationId, filter, packageName); 14211 count++; 14212 } 14213 } 14214 } 14215 } 14216 } 14217 14218 if (count > 0) { 14219 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14220 + " IntentFilter verification" + (count > 1 ? "s" : "") 14221 + " for userId:" + userId); 14222 mIntentFilterVerifier.startVerifications(userId); 14223 } else { 14224 if (DEBUG_DOMAIN_VERIFICATION) { 14225 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14226 } 14227 } 14228 } 14229 14230 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14231 final ComponentName cn = filter.activity.getComponentName(); 14232 final String packageName = cn.getPackageName(); 14233 14234 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14235 packageName); 14236 if (ivi == null) { 14237 return true; 14238 } 14239 int status = ivi.getStatus(); 14240 switch (status) { 14241 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14242 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14243 return true; 14244 14245 default: 14246 // Nothing to do 14247 return false; 14248 } 14249 } 14250 14251 private static boolean isMultiArch(ApplicationInfo info) { 14252 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14253 } 14254 14255 private static boolean isExternal(PackageParser.Package pkg) { 14256 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14257 } 14258 14259 private static boolean isExternal(PackageSetting ps) { 14260 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14261 } 14262 14263 private static boolean isEphemeral(PackageParser.Package pkg) { 14264 return pkg.applicationInfo.isEphemeralApp(); 14265 } 14266 14267 private static boolean isEphemeral(PackageSetting ps) { 14268 return ps.pkg != null && isEphemeral(ps.pkg); 14269 } 14270 14271 private static boolean isSystemApp(PackageParser.Package pkg) { 14272 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14273 } 14274 14275 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14276 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14277 } 14278 14279 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14280 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14281 } 14282 14283 private static boolean isSystemApp(PackageSetting ps) { 14284 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14285 } 14286 14287 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14288 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14289 } 14290 14291 private int packageFlagsToInstallFlags(PackageSetting ps) { 14292 int installFlags = 0; 14293 if (isEphemeral(ps)) { 14294 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14295 } 14296 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14297 // This existing package was an external ASEC install when we have 14298 // the external flag without a UUID 14299 installFlags |= PackageManager.INSTALL_EXTERNAL; 14300 } 14301 if (ps.isForwardLocked()) { 14302 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14303 } 14304 return installFlags; 14305 } 14306 14307 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14308 if (isExternal(pkg)) { 14309 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14310 return StorageManager.UUID_PRIMARY_PHYSICAL; 14311 } else { 14312 return pkg.volumeUuid; 14313 } 14314 } else { 14315 return StorageManager.UUID_PRIVATE_INTERNAL; 14316 } 14317 } 14318 14319 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14320 if (isExternal(pkg)) { 14321 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14322 return mSettings.getExternalVersion(); 14323 } else { 14324 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14325 } 14326 } else { 14327 return mSettings.getInternalVersion(); 14328 } 14329 } 14330 14331 private void deleteTempPackageFiles() { 14332 final FilenameFilter filter = new FilenameFilter() { 14333 public boolean accept(File dir, String name) { 14334 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14335 } 14336 }; 14337 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14338 file.delete(); 14339 } 14340 } 14341 14342 @Override 14343 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14344 int flags) { 14345 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14346 flags); 14347 } 14348 14349 @Override 14350 public void deletePackage(final String packageName, 14351 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14352 mContext.enforceCallingOrSelfPermission( 14353 android.Manifest.permission.DELETE_PACKAGES, null); 14354 Preconditions.checkNotNull(packageName); 14355 Preconditions.checkNotNull(observer); 14356 final int uid = Binder.getCallingUid(); 14357 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14358 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14359 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14360 mContext.enforceCallingOrSelfPermission( 14361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14362 "deletePackage for user " + userId); 14363 } 14364 14365 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14366 try { 14367 observer.onPackageDeleted(packageName, 14368 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14369 } catch (RemoteException re) { 14370 } 14371 return; 14372 } 14373 14374 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14375 try { 14376 observer.onPackageDeleted(packageName, 14377 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14378 } catch (RemoteException re) { 14379 } 14380 return; 14381 } 14382 14383 if (DEBUG_REMOVE) { 14384 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14385 + " deleteAllUsers: " + deleteAllUsers ); 14386 } 14387 // Queue up an async operation since the package deletion may take a little while. 14388 mHandler.post(new Runnable() { 14389 public void run() { 14390 mHandler.removeCallbacks(this); 14391 int returnCode; 14392 if (!deleteAllUsers) { 14393 returnCode = deletePackageX(packageName, userId, flags); 14394 } else { 14395 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14396 // If nobody is blocking uninstall, proceed with delete for all users 14397 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14398 returnCode = deletePackageX(packageName, userId, flags); 14399 } else { 14400 // Otherwise uninstall individually for users with blockUninstalls=false 14401 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14402 for (int userId : users) { 14403 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14404 returnCode = deletePackageX(packageName, userId, userFlags); 14405 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14406 Slog.w(TAG, "Package delete failed for user " + userId 14407 + ", returnCode " + returnCode); 14408 } 14409 } 14410 } 14411 // The app has only been marked uninstalled for certain users. 14412 // We still need to report that delete was blocked 14413 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14414 } 14415 } 14416 try { 14417 observer.onPackageDeleted(packageName, returnCode, null); 14418 } catch (RemoteException e) { 14419 Log.i(TAG, "Observer no longer exists."); 14420 } //end catch 14421 } //end run 14422 }); 14423 } 14424 14425 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14426 int[] result = EMPTY_INT_ARRAY; 14427 for (int userId : userIds) { 14428 if (getBlockUninstallForUser(packageName, userId)) { 14429 result = ArrayUtils.appendInt(result, userId); 14430 } 14431 } 14432 return result; 14433 } 14434 14435 @Override 14436 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14437 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14438 } 14439 14440 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14441 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14442 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14443 try { 14444 if (dpm != null) { 14445 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14446 /* callingUserOnly =*/ false); 14447 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14448 : deviceOwnerComponentName.getPackageName(); 14449 // Does the package contains the device owner? 14450 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14451 // this check is probably not needed, since DO should be registered as a device 14452 // admin on some user too. (Original bug for this: b/17657954) 14453 if (packageName.equals(deviceOwnerPackageName)) { 14454 return true; 14455 } 14456 // Does it contain a device admin for any user? 14457 int[] users; 14458 if (userId == UserHandle.USER_ALL) { 14459 users = sUserManager.getUserIds(); 14460 } else { 14461 users = new int[]{userId}; 14462 } 14463 for (int i = 0; i < users.length; ++i) { 14464 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14465 return true; 14466 } 14467 } 14468 } 14469 } catch (RemoteException e) { 14470 } 14471 return false; 14472 } 14473 14474 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14475 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14476 } 14477 14478 /** 14479 * This method is an internal method that could be get invoked either 14480 * to delete an installed package or to clean up a failed installation. 14481 * After deleting an installed package, a broadcast is sent to notify any 14482 * listeners that the package has been installed. For cleaning up a failed 14483 * installation, the broadcast is not necessary since the package's 14484 * installation wouldn't have sent the initial broadcast either 14485 * The key steps in deleting a package are 14486 * deleting the package information in internal structures like mPackages, 14487 * deleting the packages base directories through installd 14488 * updating mSettings to reflect current status 14489 * persisting settings for later use 14490 * sending a broadcast if necessary 14491 */ 14492 private int deletePackageX(String packageName, int userId, int flags) { 14493 final PackageRemovedInfo info = new PackageRemovedInfo(); 14494 final boolean res; 14495 14496 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14497 ? UserHandle.ALL : new UserHandle(userId); 14498 14499 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14500 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14501 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14502 } 14503 14504 PackageSetting uninstalledPs = null; 14505 14506 // for the uninstall-updates case and restricted profiles, remember the per- 14507 // user handle installed state 14508 int[] allUsers; 14509 synchronized (mPackages) { 14510 uninstalledPs = mSettings.mPackages.get(packageName); 14511 if (uninstalledPs == null) { 14512 Slog.w(TAG, "Not removing non-existent package " + packageName); 14513 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14514 } 14515 allUsers = sUserManager.getUserIds(); 14516 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14517 } 14518 14519 synchronized (mInstallLock) { 14520 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14521 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14522 flags | REMOVE_CHATTY, info, true, null); 14523 synchronized (mPackages) { 14524 if (res) { 14525 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14526 } 14527 } 14528 } 14529 14530 if (res) { 14531 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14532 info.sendPackageRemovedBroadcasts(killApp); 14533 info.sendSystemPackageUpdatedBroadcasts(); 14534 info.sendSystemPackageAppearedBroadcasts(); 14535 } 14536 // Force a gc here. 14537 Runtime.getRuntime().gc(); 14538 // Delete the resources here after sending the broadcast to let 14539 // other processes clean up before deleting resources. 14540 if (info.args != null) { 14541 synchronized (mInstallLock) { 14542 info.args.doPostDeleteLI(true); 14543 } 14544 } 14545 14546 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14547 } 14548 14549 class PackageRemovedInfo { 14550 String removedPackage; 14551 int uid = -1; 14552 int removedAppId = -1; 14553 int[] origUsers; 14554 int[] removedUsers = null; 14555 boolean isRemovedPackageSystemUpdate = false; 14556 boolean isUpdate; 14557 boolean dataRemoved; 14558 boolean removedForAllUsers; 14559 // Clean up resources deleted packages. 14560 InstallArgs args = null; 14561 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14562 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14563 14564 void sendPackageRemovedBroadcasts(boolean killApp) { 14565 sendPackageRemovedBroadcastInternal(killApp); 14566 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14567 for (int i = 0; i < childCount; i++) { 14568 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14569 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14570 } 14571 } 14572 14573 void sendSystemPackageUpdatedBroadcasts() { 14574 if (isRemovedPackageSystemUpdate) { 14575 sendSystemPackageUpdatedBroadcastsInternal(); 14576 final int childCount = (removedChildPackages != null) 14577 ? removedChildPackages.size() : 0; 14578 for (int i = 0; i < childCount; i++) { 14579 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14580 if (childInfo.isRemovedPackageSystemUpdate) { 14581 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14582 } 14583 } 14584 } 14585 } 14586 14587 void sendSystemPackageAppearedBroadcasts() { 14588 final int packageCount = (appearedChildPackages != null) 14589 ? appearedChildPackages.size() : 0; 14590 for (int i = 0; i < packageCount; i++) { 14591 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14592 for (int userId : installedInfo.newUsers) { 14593 sendPackageAddedForUser(installedInfo.name, true, 14594 UserHandle.getAppId(installedInfo.uid), userId); 14595 } 14596 } 14597 } 14598 14599 private void sendSystemPackageUpdatedBroadcastsInternal() { 14600 Bundle extras = new Bundle(2); 14601 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14602 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14603 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14604 extras, 0, null, null, null); 14605 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14606 extras, 0, null, null, null); 14607 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14608 null, 0, removedPackage, null, null); 14609 } 14610 14611 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14612 Bundle extras = new Bundle(2); 14613 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14614 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14615 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14616 if (isUpdate || isRemovedPackageSystemUpdate) { 14617 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14618 } 14619 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14620 if (removedPackage != null) { 14621 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14622 extras, 0, null, null, removedUsers); 14623 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14624 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14625 removedPackage, extras, 0, null, null, removedUsers); 14626 } 14627 } 14628 if (removedAppId >= 0) { 14629 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14630 removedUsers); 14631 } 14632 } 14633 } 14634 14635 /* 14636 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14637 * flag is not set, the data directory is removed as well. 14638 * make sure this flag is set for partially installed apps. If not its meaningless to 14639 * delete a partially installed application. 14640 */ 14641 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14642 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14643 String packageName = ps.name; 14644 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14645 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14646 // Retrieve object to delete permissions for shared user later on 14647 final PackageSetting deletedPs; 14648 // reader 14649 synchronized (mPackages) { 14650 deletedPs = mSettings.mPackages.get(packageName); 14651 if (outInfo != null) { 14652 outInfo.removedPackage = packageName; 14653 outInfo.removedUsers = deletedPs != null 14654 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14655 : null; 14656 } 14657 } 14658 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14659 removeDataDirsLI(ps.volumeUuid, packageName); 14660 if (outInfo != null) { 14661 outInfo.dataRemoved = true; 14662 } 14663 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14664 } 14665 // writer 14666 synchronized (mPackages) { 14667 if (deletedPs != null) { 14668 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14669 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14670 clearDefaultBrowserIfNeeded(packageName); 14671 if (outInfo != null) { 14672 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14673 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14674 } 14675 updatePermissionsLPw(deletedPs.name, null, 0); 14676 if (deletedPs.sharedUser != null) { 14677 // Remove permissions associated with package. Since runtime 14678 // permissions are per user we have to kill the removed package 14679 // or packages running under the shared user of the removed 14680 // package if revoking the permissions requested only by the removed 14681 // package is successful and this causes a change in gids. 14682 for (int userId : UserManagerService.getInstance().getUserIds()) { 14683 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14684 userId); 14685 if (userIdToKill == UserHandle.USER_ALL 14686 || userIdToKill >= UserHandle.USER_SYSTEM) { 14687 // If gids changed for this user, kill all affected packages. 14688 mHandler.post(new Runnable() { 14689 @Override 14690 public void run() { 14691 // This has to happen with no lock held. 14692 killApplication(deletedPs.name, deletedPs.appId, 14693 KILL_APP_REASON_GIDS_CHANGED); 14694 } 14695 }); 14696 break; 14697 } 14698 } 14699 } 14700 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14701 } 14702 // make sure to preserve per-user disabled state if this removal was just 14703 // a downgrade of a system app to the factory package 14704 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14705 if (DEBUG_REMOVE) { 14706 Slog.d(TAG, "Propagating install state across downgrade"); 14707 } 14708 for (int userId : allUserHandles) { 14709 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14710 if (DEBUG_REMOVE) { 14711 Slog.d(TAG, " user " + userId + " => " + installed); 14712 } 14713 ps.setInstalled(installed, userId); 14714 } 14715 } 14716 } 14717 // can downgrade to reader 14718 if (writeSettings) { 14719 // Save settings now 14720 mSettings.writeLPr(); 14721 } 14722 } 14723 if (outInfo != null) { 14724 // A user ID was deleted here. Go through all users and remove it 14725 // from KeyStore. 14726 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14727 } 14728 } 14729 14730 static boolean locationIsPrivileged(File path) { 14731 try { 14732 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14733 .getCanonicalPath(); 14734 return path.getCanonicalPath().startsWith(privilegedAppDir); 14735 } catch (IOException e) { 14736 Slog.e(TAG, "Unable to access code path " + path); 14737 } 14738 return false; 14739 } 14740 14741 /* 14742 * Tries to delete system package. 14743 */ 14744 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14745 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14746 boolean writeSettings) { 14747 if (deletedPs.parentPackageName != null) { 14748 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14749 return false; 14750 } 14751 14752 final boolean applyUserRestrictions 14753 = (allUserHandles != null) && (outInfo.origUsers != null); 14754 final PackageSetting disabledPs; 14755 // Confirm if the system package has been updated 14756 // An updated system app can be deleted. This will also have to restore 14757 // the system pkg from system partition 14758 // reader 14759 synchronized (mPackages) { 14760 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14761 } 14762 14763 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14764 + " disabledPs=" + disabledPs); 14765 14766 if (disabledPs == null) { 14767 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14768 return false; 14769 } else if (DEBUG_REMOVE) { 14770 Slog.d(TAG, "Deleting system pkg from data partition"); 14771 } 14772 14773 if (DEBUG_REMOVE) { 14774 if (applyUserRestrictions) { 14775 Slog.d(TAG, "Remembering install states:"); 14776 for (int userId : allUserHandles) { 14777 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14778 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14779 } 14780 } 14781 } 14782 14783 // Delete the updated package 14784 outInfo.isRemovedPackageSystemUpdate = true; 14785 if (outInfo.removedChildPackages != null) { 14786 final int childCount = (deletedPs.childPackageNames != null) 14787 ? deletedPs.childPackageNames.size() : 0; 14788 for (int i = 0; i < childCount; i++) { 14789 String childPackageName = deletedPs.childPackageNames.get(i); 14790 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14791 .contains(childPackageName)) { 14792 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14793 childPackageName); 14794 if (childInfo != null) { 14795 childInfo.isRemovedPackageSystemUpdate = true; 14796 } 14797 } 14798 } 14799 } 14800 14801 if (disabledPs.versionCode < deletedPs.versionCode) { 14802 // Delete data for downgrades 14803 flags &= ~PackageManager.DELETE_KEEP_DATA; 14804 } else { 14805 // Preserve data by setting flag 14806 flags |= PackageManager.DELETE_KEEP_DATA; 14807 } 14808 14809 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14810 outInfo, writeSettings, disabledPs.pkg); 14811 if (!ret) { 14812 return false; 14813 } 14814 14815 // writer 14816 synchronized (mPackages) { 14817 // Reinstate the old system package 14818 enableSystemPackageLPw(disabledPs.pkg); 14819 // Remove any native libraries from the upgraded package. 14820 removeNativeBinariesLI(deletedPs); 14821 } 14822 14823 // Install the system package 14824 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14825 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14826 if (locationIsPrivileged(disabledPs.codePath)) { 14827 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14828 } 14829 14830 final PackageParser.Package newPkg; 14831 try { 14832 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14833 } catch (PackageManagerException e) { 14834 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14835 + e.getMessage()); 14836 return false; 14837 } 14838 14839 prepareAppDataAfterInstall(newPkg); 14840 14841 // writer 14842 synchronized (mPackages) { 14843 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14844 14845 // Propagate the permissions state as we do not want to drop on the floor 14846 // runtime permissions. The update permissions method below will take 14847 // care of removing obsolete permissions and grant install permissions. 14848 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14849 updatePermissionsLPw(newPkg.packageName, newPkg, 14850 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14851 14852 if (applyUserRestrictions) { 14853 if (DEBUG_REMOVE) { 14854 Slog.d(TAG, "Propagating install state across reinstall"); 14855 } 14856 for (int userId : allUserHandles) { 14857 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14858 if (DEBUG_REMOVE) { 14859 Slog.d(TAG, " user " + userId + " => " + installed); 14860 } 14861 ps.setInstalled(installed, userId); 14862 14863 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14864 } 14865 // Regardless of writeSettings we need to ensure that this restriction 14866 // state propagation is persisted 14867 mSettings.writeAllUsersPackageRestrictionsLPr(); 14868 } 14869 // can downgrade to reader here 14870 if (writeSettings) { 14871 mSettings.writeLPr(); 14872 } 14873 } 14874 return true; 14875 } 14876 14877 private boolean deleteInstalledPackageLI(PackageSetting ps, 14878 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14879 PackageRemovedInfo outInfo, boolean writeSettings, 14880 PackageParser.Package replacingPackage) { 14881 synchronized (mPackages) { 14882 if (outInfo != null) { 14883 outInfo.uid = ps.appId; 14884 } 14885 14886 if (outInfo != null && outInfo.removedChildPackages != null) { 14887 final int childCount = (ps.childPackageNames != null) 14888 ? ps.childPackageNames.size() : 0; 14889 for (int i = 0; i < childCount; i++) { 14890 String childPackageName = ps.childPackageNames.get(i); 14891 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14892 if (childPs == null) { 14893 return false; 14894 } 14895 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14896 childPackageName); 14897 if (childInfo != null) { 14898 childInfo.uid = childPs.appId; 14899 } 14900 } 14901 } 14902 } 14903 14904 // Delete package data from internal structures and also remove data if flag is set 14905 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14906 14907 // Delete the child packages data 14908 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14909 for (int i = 0; i < childCount; i++) { 14910 PackageSetting childPs; 14911 synchronized (mPackages) { 14912 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14913 } 14914 if (childPs != null) { 14915 PackageRemovedInfo childOutInfo = (outInfo != null 14916 && outInfo.removedChildPackages != null) 14917 ? outInfo.removedChildPackages.get(childPs.name) : null; 14918 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14919 && (replacingPackage != null 14920 && !replacingPackage.hasChildPackage(childPs.name)) 14921 ? flags & ~DELETE_KEEP_DATA : flags; 14922 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14923 deleteFlags, writeSettings); 14924 } 14925 } 14926 14927 // Delete application code and resources only for parent packages 14928 if (ps.parentPackageName == null) { 14929 if (deleteCodeAndResources && (outInfo != null)) { 14930 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14931 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14932 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14933 } 14934 } 14935 14936 return true; 14937 } 14938 14939 @Override 14940 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14941 int userId) { 14942 mContext.enforceCallingOrSelfPermission( 14943 android.Manifest.permission.DELETE_PACKAGES, null); 14944 synchronized (mPackages) { 14945 PackageSetting ps = mSettings.mPackages.get(packageName); 14946 if (ps == null) { 14947 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14948 return false; 14949 } 14950 if (!ps.getInstalled(userId)) { 14951 // Can't block uninstall for an app that is not installed or enabled. 14952 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14953 return false; 14954 } 14955 ps.setBlockUninstall(blockUninstall, userId); 14956 mSettings.writePackageRestrictionsLPr(userId); 14957 } 14958 return true; 14959 } 14960 14961 @Override 14962 public boolean getBlockUninstallForUser(String packageName, int userId) { 14963 synchronized (mPackages) { 14964 PackageSetting ps = mSettings.mPackages.get(packageName); 14965 if (ps == null) { 14966 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14967 return false; 14968 } 14969 return ps.getBlockUninstall(userId); 14970 } 14971 } 14972 14973 @Override 14974 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14975 int callingUid = Binder.getCallingUid(); 14976 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14977 throw new SecurityException( 14978 "setRequiredForSystemUser can only be run by the system or root"); 14979 } 14980 synchronized (mPackages) { 14981 PackageSetting ps = mSettings.mPackages.get(packageName); 14982 if (ps == null) { 14983 Log.w(TAG, "Package doesn't exist: " + packageName); 14984 return false; 14985 } 14986 if (systemUserApp) { 14987 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14988 } else { 14989 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14990 } 14991 mSettings.writeLPr(); 14992 } 14993 return true; 14994 } 14995 14996 /* 14997 * This method handles package deletion in general 14998 */ 14999 private boolean deletePackageLI(String packageName, UserHandle user, 15000 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15001 PackageRemovedInfo outInfo, boolean writeSettings, 15002 PackageParser.Package replacingPackage) { 15003 if (packageName == null) { 15004 Slog.w(TAG, "Attempt to delete null packageName."); 15005 return false; 15006 } 15007 15008 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15009 15010 PackageSetting ps; 15011 15012 synchronized (mPackages) { 15013 ps = mSettings.mPackages.get(packageName); 15014 if (ps == null) { 15015 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15016 return false; 15017 } 15018 15019 if (ps.parentPackageName != null && (!isSystemApp(ps) 15020 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15021 if (DEBUG_REMOVE) { 15022 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15023 + ((user == null) ? UserHandle.USER_ALL : user)); 15024 } 15025 final int removedUserId = (user != null) ? user.getIdentifier() 15026 : UserHandle.USER_ALL; 15027 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15028 return false; 15029 } 15030 markPackageUninstalledForUserLPw(ps, user); 15031 scheduleWritePackageRestrictionsLocked(user); 15032 return true; 15033 } 15034 } 15035 15036 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15037 && user.getIdentifier() != UserHandle.USER_ALL)) { 15038 // The caller is asking that the package only be deleted for a single 15039 // user. To do this, we just mark its uninstalled state and delete 15040 // its data. If this is a system app, we only allow this to happen if 15041 // they have set the special DELETE_SYSTEM_APP which requests different 15042 // semantics than normal for uninstalling system apps. 15043 markPackageUninstalledForUserLPw(ps, user); 15044 15045 if (!isSystemApp(ps)) { 15046 // Do not uninstall the APK if an app should be cached 15047 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15048 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15049 // Other user still have this package installed, so all 15050 // we need to do is clear this user's data and save that 15051 // it is uninstalled. 15052 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15053 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15054 return false; 15055 } 15056 scheduleWritePackageRestrictionsLocked(user); 15057 return true; 15058 } else { 15059 // We need to set it back to 'installed' so the uninstall 15060 // broadcasts will be sent correctly. 15061 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15062 ps.setInstalled(true, user.getIdentifier()); 15063 } 15064 } else { 15065 // This is a system app, so we assume that the 15066 // other users still have this package installed, so all 15067 // we need to do is clear this user's data and save that 15068 // it is uninstalled. 15069 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15070 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15071 return false; 15072 } 15073 scheduleWritePackageRestrictionsLocked(user); 15074 return true; 15075 } 15076 } 15077 15078 // If we are deleting a composite package for all users, keep track 15079 // of result for each child. 15080 if (ps.childPackageNames != null && outInfo != null) { 15081 synchronized (mPackages) { 15082 final int childCount = ps.childPackageNames.size(); 15083 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15084 for (int i = 0; i < childCount; i++) { 15085 String childPackageName = ps.childPackageNames.get(i); 15086 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15087 childInfo.removedPackage = childPackageName; 15088 outInfo.removedChildPackages.put(childPackageName, childInfo); 15089 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15090 if (childPs != null) { 15091 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15092 } 15093 } 15094 } 15095 } 15096 15097 boolean ret = false; 15098 if (isSystemApp(ps)) { 15099 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15100 // When an updated system application is deleted we delete the existing resources 15101 // as well and fall back to existing code in system partition 15102 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15103 } else { 15104 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15105 // Kill application pre-emptively especially for apps on sd. 15106 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15107 if (killApp) { 15108 killApplication(packageName, ps.appId, "uninstall pkg"); 15109 } 15110 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15111 outInfo, writeSettings, replacingPackage); 15112 } 15113 15114 // Take a note whether we deleted the package for all users 15115 if (outInfo != null) { 15116 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15117 if (outInfo.removedChildPackages != null) { 15118 synchronized (mPackages) { 15119 final int childCount = outInfo.removedChildPackages.size(); 15120 for (int i = 0; i < childCount; i++) { 15121 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15122 if (childInfo != null) { 15123 childInfo.removedForAllUsers = mPackages.get( 15124 childInfo.removedPackage) == null; 15125 } 15126 } 15127 } 15128 } 15129 // If we uninstalled an update to a system app there may be some 15130 // child packages that appeared as they are declared in the system 15131 // app but were not declared in the update. 15132 if (isSystemApp(ps)) { 15133 synchronized (mPackages) { 15134 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15135 final int childCount = (updatedPs.childPackageNames != null) 15136 ? updatedPs.childPackageNames.size() : 0; 15137 for (int i = 0; i < childCount; i++) { 15138 String childPackageName = updatedPs.childPackageNames.get(i); 15139 if (outInfo.removedChildPackages == null 15140 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15141 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15142 if (childPs == null) { 15143 continue; 15144 } 15145 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15146 installRes.name = childPackageName; 15147 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15148 installRes.pkg = mPackages.get(childPackageName); 15149 installRes.uid = childPs.pkg.applicationInfo.uid; 15150 if (outInfo.appearedChildPackages == null) { 15151 outInfo.appearedChildPackages = new ArrayMap<>(); 15152 } 15153 outInfo.appearedChildPackages.put(childPackageName, installRes); 15154 } 15155 } 15156 } 15157 } 15158 } 15159 15160 return ret; 15161 } 15162 15163 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15164 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15165 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15166 for (int nextUserId : userIds) { 15167 if (DEBUG_REMOVE) { 15168 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15169 } 15170 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15171 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15172 false /*hidden*/, false /*suspended*/, null, null, null, 15173 false /*blockUninstall*/, 15174 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15175 } 15176 } 15177 15178 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15179 PackageRemovedInfo outInfo) { 15180 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15181 : new int[] {userId}; 15182 for (int nextUserId : userIds) { 15183 if (DEBUG_REMOVE) { 15184 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15185 + nextUserId); 15186 } 15187 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15188 try { 15189 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15190 } catch (InstallerException e) { 15191 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15192 return false; 15193 } 15194 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15195 schedulePackageCleaning(ps.name, nextUserId, false); 15196 synchronized (mPackages) { 15197 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15198 scheduleWritePackageRestrictionsLocked(nextUserId); 15199 } 15200 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15201 } 15202 } 15203 15204 if (outInfo != null) { 15205 outInfo.removedPackage = ps.name; 15206 outInfo.removedAppId = ps.appId; 15207 outInfo.removedUsers = userIds; 15208 } 15209 15210 return true; 15211 } 15212 15213 private final class ClearStorageConnection implements ServiceConnection { 15214 IMediaContainerService mContainerService; 15215 15216 @Override 15217 public void onServiceConnected(ComponentName name, IBinder service) { 15218 synchronized (this) { 15219 mContainerService = IMediaContainerService.Stub.asInterface(service); 15220 notifyAll(); 15221 } 15222 } 15223 15224 @Override 15225 public void onServiceDisconnected(ComponentName name) { 15226 } 15227 } 15228 15229 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15230 final boolean mounted; 15231 if (Environment.isExternalStorageEmulated()) { 15232 mounted = true; 15233 } else { 15234 final String status = Environment.getExternalStorageState(); 15235 15236 mounted = status.equals(Environment.MEDIA_MOUNTED) 15237 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15238 } 15239 15240 if (!mounted) { 15241 return; 15242 } 15243 15244 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15245 int[] users; 15246 if (userId == UserHandle.USER_ALL) { 15247 users = sUserManager.getUserIds(); 15248 } else { 15249 users = new int[] { userId }; 15250 } 15251 final ClearStorageConnection conn = new ClearStorageConnection(); 15252 if (mContext.bindServiceAsUser( 15253 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15254 try { 15255 for (int curUser : users) { 15256 long timeout = SystemClock.uptimeMillis() + 5000; 15257 synchronized (conn) { 15258 long now = SystemClock.uptimeMillis(); 15259 while (conn.mContainerService == null && now < timeout) { 15260 try { 15261 conn.wait(timeout - now); 15262 } catch (InterruptedException e) { 15263 } 15264 } 15265 } 15266 if (conn.mContainerService == null) { 15267 return; 15268 } 15269 15270 final UserEnvironment userEnv = new UserEnvironment(curUser); 15271 clearDirectory(conn.mContainerService, 15272 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15273 if (allData) { 15274 clearDirectory(conn.mContainerService, 15275 userEnv.buildExternalStorageAppDataDirs(packageName)); 15276 clearDirectory(conn.mContainerService, 15277 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15278 } 15279 } 15280 } finally { 15281 mContext.unbindService(conn); 15282 } 15283 } 15284 } 15285 15286 @Override 15287 public void clearApplicationProfileData(String packageName) { 15288 enforceSystemOrRoot("Only the system can clear all profile data"); 15289 try { 15290 mInstaller.clearAppProfiles(packageName); 15291 } catch (InstallerException ex) { 15292 Log.e(TAG, "Could not clear profile data of package " + packageName); 15293 } 15294 } 15295 15296 @Override 15297 public void clearApplicationUserData(final String packageName, 15298 final IPackageDataObserver observer, final int userId) { 15299 mContext.enforceCallingOrSelfPermission( 15300 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15301 15302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15303 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15304 15305 final DevicePolicyManagerInternal dpmi = LocalServices 15306 .getService(DevicePolicyManagerInternal.class); 15307 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15308 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15309 } 15310 // Queue up an async operation since the package deletion may take a little while. 15311 mHandler.post(new Runnable() { 15312 public void run() { 15313 mHandler.removeCallbacks(this); 15314 final boolean succeeded; 15315 synchronized (mInstallLock) { 15316 succeeded = clearApplicationUserDataLI(packageName, userId); 15317 } 15318 clearExternalStorageDataSync(packageName, userId, true); 15319 if (succeeded) { 15320 // invoke DeviceStorageMonitor's update method to clear any notifications 15321 DeviceStorageMonitorInternal dsm = LocalServices 15322 .getService(DeviceStorageMonitorInternal.class); 15323 if (dsm != null) { 15324 dsm.checkMemory(); 15325 } 15326 } 15327 if(observer != null) { 15328 try { 15329 observer.onRemoveCompleted(packageName, succeeded); 15330 } catch (RemoteException e) { 15331 Log.i(TAG, "Observer no longer exists."); 15332 } 15333 } //end if observer 15334 } //end run 15335 }); 15336 } 15337 15338 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15339 if (packageName == null) { 15340 Slog.w(TAG, "Attempt to delete null packageName."); 15341 return false; 15342 } 15343 15344 // Try finding details about the requested package 15345 PackageParser.Package pkg; 15346 synchronized (mPackages) { 15347 pkg = mPackages.get(packageName); 15348 if (pkg == null) { 15349 final PackageSetting ps = mSettings.mPackages.get(packageName); 15350 if (ps != null) { 15351 pkg = ps.pkg; 15352 } 15353 } 15354 15355 if (pkg == null) { 15356 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15357 return false; 15358 } 15359 15360 PackageSetting ps = (PackageSetting) pkg.mExtras; 15361 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15362 } 15363 15364 // Always delete data directories for package, even if we found no other 15365 // record of app. This helps users recover from UID mismatches without 15366 // resorting to a full data wipe. 15367 // TODO: triage flags as part of 26466827 15368 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15369 try { 15370 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15371 } catch (InstallerException e) { 15372 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15373 return false; 15374 } 15375 15376 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15377 removeKeystoreDataIfNeeded(userId, appId); 15378 15379 // Create a native library symlink only if we have native libraries 15380 // and if the native libraries are 32 bit libraries. We do not provide 15381 // this symlink for 64 bit libraries. 15382 if (pkg.applicationInfo.primaryCpuAbi != null && 15383 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15384 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15385 try { 15386 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15387 nativeLibPath, userId); 15388 } catch (InstallerException e) { 15389 Slog.w(TAG, "Failed linking native library dir", e); 15390 return false; 15391 } 15392 } 15393 15394 return true; 15395 } 15396 15397 /** 15398 * Reverts user permission state changes (permissions and flags) in 15399 * all packages for a given user. 15400 * 15401 * @param userId The device user for which to do a reset. 15402 */ 15403 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15404 final int packageCount = mPackages.size(); 15405 for (int i = 0; i < packageCount; i++) { 15406 PackageParser.Package pkg = mPackages.valueAt(i); 15407 PackageSetting ps = (PackageSetting) pkg.mExtras; 15408 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15409 } 15410 } 15411 15412 /** 15413 * Reverts user permission state changes (permissions and flags). 15414 * 15415 * @param ps The package for which to reset. 15416 * @param userId The device user for which to do a reset. 15417 */ 15418 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15419 final PackageSetting ps, final int userId) { 15420 if (ps.pkg == null) { 15421 return; 15422 } 15423 15424 // These are flags that can change base on user actions. 15425 final int userSettableMask = FLAG_PERMISSION_USER_SET 15426 | FLAG_PERMISSION_USER_FIXED 15427 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15428 | FLAG_PERMISSION_REVIEW_REQUIRED; 15429 15430 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15431 | FLAG_PERMISSION_POLICY_FIXED; 15432 15433 boolean writeInstallPermissions = false; 15434 boolean writeRuntimePermissions = false; 15435 15436 final int permissionCount = ps.pkg.requestedPermissions.size(); 15437 for (int i = 0; i < permissionCount; i++) { 15438 String permission = ps.pkg.requestedPermissions.get(i); 15439 15440 BasePermission bp = mSettings.mPermissions.get(permission); 15441 if (bp == null) { 15442 continue; 15443 } 15444 15445 // If shared user we just reset the state to which only this app contributed. 15446 if (ps.sharedUser != null) { 15447 boolean used = false; 15448 final int packageCount = ps.sharedUser.packages.size(); 15449 for (int j = 0; j < packageCount; j++) { 15450 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15451 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15452 && pkg.pkg.requestedPermissions.contains(permission)) { 15453 used = true; 15454 break; 15455 } 15456 } 15457 if (used) { 15458 continue; 15459 } 15460 } 15461 15462 PermissionsState permissionsState = ps.getPermissionsState(); 15463 15464 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15465 15466 // Always clear the user settable flags. 15467 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15468 bp.name) != null; 15469 // If permission review is enabled and this is a legacy app, mark the 15470 // permission as requiring a review as this is the initial state. 15471 int flags = 0; 15472 if (Build.PERMISSIONS_REVIEW_REQUIRED 15473 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15474 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15475 } 15476 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15477 if (hasInstallState) { 15478 writeInstallPermissions = true; 15479 } else { 15480 writeRuntimePermissions = true; 15481 } 15482 } 15483 15484 // Below is only runtime permission handling. 15485 if (!bp.isRuntime()) { 15486 continue; 15487 } 15488 15489 // Never clobber system or policy. 15490 if ((oldFlags & policyOrSystemFlags) != 0) { 15491 continue; 15492 } 15493 15494 // If this permission was granted by default, make sure it is. 15495 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15496 if (permissionsState.grantRuntimePermission(bp, userId) 15497 != PERMISSION_OPERATION_FAILURE) { 15498 writeRuntimePermissions = true; 15499 } 15500 // If permission review is enabled the permissions for a legacy apps 15501 // are represented as constantly granted runtime ones, so don't revoke. 15502 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15503 // Otherwise, reset the permission. 15504 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15505 switch (revokeResult) { 15506 case PERMISSION_OPERATION_SUCCESS: { 15507 writeRuntimePermissions = true; 15508 } break; 15509 15510 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15511 writeRuntimePermissions = true; 15512 final int appId = ps.appId; 15513 mHandler.post(new Runnable() { 15514 @Override 15515 public void run() { 15516 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15517 } 15518 }); 15519 } break; 15520 } 15521 } 15522 } 15523 15524 // Synchronously write as we are taking permissions away. 15525 if (writeRuntimePermissions) { 15526 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15527 } 15528 15529 // Synchronously write as we are taking permissions away. 15530 if (writeInstallPermissions) { 15531 mSettings.writeLPr(); 15532 } 15533 } 15534 15535 /** 15536 * Remove entries from the keystore daemon. Will only remove it if the 15537 * {@code appId} is valid. 15538 */ 15539 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15540 if (appId < 0) { 15541 return; 15542 } 15543 15544 final KeyStore keyStore = KeyStore.getInstance(); 15545 if (keyStore != null) { 15546 if (userId == UserHandle.USER_ALL) { 15547 for (final int individual : sUserManager.getUserIds()) { 15548 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15549 } 15550 } else { 15551 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15552 } 15553 } else { 15554 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15555 } 15556 } 15557 15558 @Override 15559 public void deleteApplicationCacheFiles(final String packageName, 15560 final IPackageDataObserver observer) { 15561 mContext.enforceCallingOrSelfPermission( 15562 android.Manifest.permission.DELETE_CACHE_FILES, null); 15563 // Queue up an async operation since the package deletion may take a little while. 15564 final int userId = UserHandle.getCallingUserId(); 15565 mHandler.post(new Runnable() { 15566 public void run() { 15567 mHandler.removeCallbacks(this); 15568 final boolean succeded; 15569 synchronized (mInstallLock) { 15570 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15571 } 15572 clearExternalStorageDataSync(packageName, userId, false); 15573 if (observer != null) { 15574 try { 15575 observer.onRemoveCompleted(packageName, succeded); 15576 } catch (RemoteException e) { 15577 Log.i(TAG, "Observer no longer exists."); 15578 } 15579 } //end if observer 15580 } //end run 15581 }); 15582 } 15583 15584 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15585 if (packageName == null) { 15586 Slog.w(TAG, "Attempt to delete null packageName."); 15587 return false; 15588 } 15589 PackageParser.Package p; 15590 synchronized (mPackages) { 15591 p = mPackages.get(packageName); 15592 } 15593 if (p == null) { 15594 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15595 return false; 15596 } 15597 final ApplicationInfo applicationInfo = p.applicationInfo; 15598 if (applicationInfo == null) { 15599 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15600 return false; 15601 } 15602 // TODO: triage flags as part of 26466827 15603 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15604 try { 15605 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15606 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15607 } catch (InstallerException e) { 15608 Slog.w(TAG, "Couldn't remove cache files for package " 15609 + packageName + " u" + userId, e); 15610 return false; 15611 } 15612 return true; 15613 } 15614 15615 @Override 15616 public void getPackageSizeInfo(final String packageName, int userHandle, 15617 final IPackageStatsObserver observer) { 15618 mContext.enforceCallingOrSelfPermission( 15619 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15620 if (packageName == null) { 15621 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15622 } 15623 15624 PackageStats stats = new PackageStats(packageName, userHandle); 15625 15626 /* 15627 * Queue up an async operation since the package measurement may take a 15628 * little while. 15629 */ 15630 Message msg = mHandler.obtainMessage(INIT_COPY); 15631 msg.obj = new MeasureParams(stats, observer); 15632 mHandler.sendMessage(msg); 15633 } 15634 15635 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15636 PackageStats pStats) { 15637 if (packageName == null) { 15638 Slog.w(TAG, "Attempt to get size of null packageName."); 15639 return false; 15640 } 15641 PackageParser.Package p; 15642 boolean dataOnly = false; 15643 String libDirRoot = null; 15644 String asecPath = null; 15645 PackageSetting ps = null; 15646 synchronized (mPackages) { 15647 p = mPackages.get(packageName); 15648 ps = mSettings.mPackages.get(packageName); 15649 if(p == null) { 15650 dataOnly = true; 15651 if((ps == null) || (ps.pkg == null)) { 15652 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15653 return false; 15654 } 15655 p = ps.pkg; 15656 } 15657 if (ps != null) { 15658 libDirRoot = ps.legacyNativeLibraryPathString; 15659 } 15660 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15661 final long token = Binder.clearCallingIdentity(); 15662 try { 15663 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15664 if (secureContainerId != null) { 15665 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15666 } 15667 } finally { 15668 Binder.restoreCallingIdentity(token); 15669 } 15670 } 15671 } 15672 String publicSrcDir = null; 15673 if(!dataOnly) { 15674 final ApplicationInfo applicationInfo = p.applicationInfo; 15675 if (applicationInfo == null) { 15676 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15677 return false; 15678 } 15679 if (p.isForwardLocked()) { 15680 publicSrcDir = applicationInfo.getBaseResourcePath(); 15681 } 15682 } 15683 // TODO: extend to measure size of split APKs 15684 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15685 // not just the first level. 15686 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15687 // just the primary. 15688 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15689 15690 String apkPath; 15691 File packageDir = new File(p.codePath); 15692 15693 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15694 apkPath = packageDir.getAbsolutePath(); 15695 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15696 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15697 libDirRoot = null; 15698 } 15699 } else { 15700 apkPath = p.baseCodePath; 15701 } 15702 15703 // TODO: triage flags as part of 26466827 15704 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15705 try { 15706 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15707 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15708 } catch (InstallerException e) { 15709 return false; 15710 } 15711 15712 // Fix-up for forward-locked applications in ASEC containers. 15713 if (!isExternal(p)) { 15714 pStats.codeSize += pStats.externalCodeSize; 15715 pStats.externalCodeSize = 0L; 15716 } 15717 15718 return true; 15719 } 15720 15721 private int getUidTargetSdkVersionLockedLPr(int uid) { 15722 Object obj = mSettings.getUserIdLPr(uid); 15723 if (obj instanceof SharedUserSetting) { 15724 final SharedUserSetting sus = (SharedUserSetting) obj; 15725 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15726 final Iterator<PackageSetting> it = sus.packages.iterator(); 15727 while (it.hasNext()) { 15728 final PackageSetting ps = it.next(); 15729 if (ps.pkg != null) { 15730 int v = ps.pkg.applicationInfo.targetSdkVersion; 15731 if (v < vers) vers = v; 15732 } 15733 } 15734 return vers; 15735 } else if (obj instanceof PackageSetting) { 15736 final PackageSetting ps = (PackageSetting) obj; 15737 if (ps.pkg != null) { 15738 return ps.pkg.applicationInfo.targetSdkVersion; 15739 } 15740 } 15741 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15742 } 15743 15744 @Override 15745 public void addPreferredActivity(IntentFilter filter, int match, 15746 ComponentName[] set, ComponentName activity, int userId) { 15747 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15748 "Adding preferred"); 15749 } 15750 15751 private void addPreferredActivityInternal(IntentFilter filter, int match, 15752 ComponentName[] set, ComponentName activity, boolean always, int userId, 15753 String opname) { 15754 // writer 15755 int callingUid = Binder.getCallingUid(); 15756 enforceCrossUserPermission(callingUid, userId, 15757 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15758 if (filter.countActions() == 0) { 15759 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15760 return; 15761 } 15762 synchronized (mPackages) { 15763 if (mContext.checkCallingOrSelfPermission( 15764 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15765 != PackageManager.PERMISSION_GRANTED) { 15766 if (getUidTargetSdkVersionLockedLPr(callingUid) 15767 < Build.VERSION_CODES.FROYO) { 15768 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15769 + callingUid); 15770 return; 15771 } 15772 mContext.enforceCallingOrSelfPermission( 15773 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15774 } 15775 15776 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15777 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15778 + userId + ":"); 15779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15780 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15781 scheduleWritePackageRestrictionsLocked(userId); 15782 } 15783 } 15784 15785 @Override 15786 public void replacePreferredActivity(IntentFilter filter, int match, 15787 ComponentName[] set, ComponentName activity, int userId) { 15788 if (filter.countActions() != 1) { 15789 throw new IllegalArgumentException( 15790 "replacePreferredActivity expects filter to have only 1 action."); 15791 } 15792 if (filter.countDataAuthorities() != 0 15793 || filter.countDataPaths() != 0 15794 || filter.countDataSchemes() > 1 15795 || filter.countDataTypes() != 0) { 15796 throw new IllegalArgumentException( 15797 "replacePreferredActivity expects filter to have no data authorities, " + 15798 "paths, or types; and at most one scheme."); 15799 } 15800 15801 final int callingUid = Binder.getCallingUid(); 15802 enforceCrossUserPermission(callingUid, userId, 15803 true /* requireFullPermission */, false /* checkShell */, 15804 "replace preferred activity"); 15805 synchronized (mPackages) { 15806 if (mContext.checkCallingOrSelfPermission( 15807 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15808 != PackageManager.PERMISSION_GRANTED) { 15809 if (getUidTargetSdkVersionLockedLPr(callingUid) 15810 < Build.VERSION_CODES.FROYO) { 15811 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15812 + Binder.getCallingUid()); 15813 return; 15814 } 15815 mContext.enforceCallingOrSelfPermission( 15816 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15817 } 15818 15819 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15820 if (pir != null) { 15821 // Get all of the existing entries that exactly match this filter. 15822 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15823 if (existing != null && existing.size() == 1) { 15824 PreferredActivity cur = existing.get(0); 15825 if (DEBUG_PREFERRED) { 15826 Slog.i(TAG, "Checking replace of preferred:"); 15827 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15828 if (!cur.mPref.mAlways) { 15829 Slog.i(TAG, " -- CUR; not mAlways!"); 15830 } else { 15831 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15832 Slog.i(TAG, " -- CUR: mSet=" 15833 + Arrays.toString(cur.mPref.mSetComponents)); 15834 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15835 Slog.i(TAG, " -- NEW: mMatch=" 15836 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15837 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15838 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15839 } 15840 } 15841 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15842 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15843 && cur.mPref.sameSet(set)) { 15844 // Setting the preferred activity to what it happens to be already 15845 if (DEBUG_PREFERRED) { 15846 Slog.i(TAG, "Replacing with same preferred activity " 15847 + cur.mPref.mShortComponent + " for user " 15848 + userId + ":"); 15849 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15850 } 15851 return; 15852 } 15853 } 15854 15855 if (existing != null) { 15856 if (DEBUG_PREFERRED) { 15857 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15858 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15859 } 15860 for (int i = 0; i < existing.size(); i++) { 15861 PreferredActivity pa = existing.get(i); 15862 if (DEBUG_PREFERRED) { 15863 Slog.i(TAG, "Removing existing preferred activity " 15864 + pa.mPref.mComponent + ":"); 15865 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15866 } 15867 pir.removeFilter(pa); 15868 } 15869 } 15870 } 15871 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15872 "Replacing preferred"); 15873 } 15874 } 15875 15876 @Override 15877 public void clearPackagePreferredActivities(String packageName) { 15878 final int uid = Binder.getCallingUid(); 15879 // writer 15880 synchronized (mPackages) { 15881 PackageParser.Package pkg = mPackages.get(packageName); 15882 if (pkg == null || pkg.applicationInfo.uid != uid) { 15883 if (mContext.checkCallingOrSelfPermission( 15884 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15885 != PackageManager.PERMISSION_GRANTED) { 15886 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15887 < Build.VERSION_CODES.FROYO) { 15888 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15889 + Binder.getCallingUid()); 15890 return; 15891 } 15892 mContext.enforceCallingOrSelfPermission( 15893 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15894 } 15895 } 15896 15897 int user = UserHandle.getCallingUserId(); 15898 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15899 scheduleWritePackageRestrictionsLocked(user); 15900 } 15901 } 15902 } 15903 15904 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15905 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15906 ArrayList<PreferredActivity> removed = null; 15907 boolean changed = false; 15908 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15909 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15910 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15911 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15912 continue; 15913 } 15914 Iterator<PreferredActivity> it = pir.filterIterator(); 15915 while (it.hasNext()) { 15916 PreferredActivity pa = it.next(); 15917 // Mark entry for removal only if it matches the package name 15918 // and the entry is of type "always". 15919 if (packageName == null || 15920 (pa.mPref.mComponent.getPackageName().equals(packageName) 15921 && pa.mPref.mAlways)) { 15922 if (removed == null) { 15923 removed = new ArrayList<PreferredActivity>(); 15924 } 15925 removed.add(pa); 15926 } 15927 } 15928 if (removed != null) { 15929 for (int j=0; j<removed.size(); j++) { 15930 PreferredActivity pa = removed.get(j); 15931 pir.removeFilter(pa); 15932 } 15933 changed = true; 15934 } 15935 } 15936 return changed; 15937 } 15938 15939 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15940 private void clearIntentFilterVerificationsLPw(int userId) { 15941 final int packageCount = mPackages.size(); 15942 for (int i = 0; i < packageCount; i++) { 15943 PackageParser.Package pkg = mPackages.valueAt(i); 15944 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15945 } 15946 } 15947 15948 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15949 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15950 if (userId == UserHandle.USER_ALL) { 15951 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15952 sUserManager.getUserIds())) { 15953 for (int oneUserId : sUserManager.getUserIds()) { 15954 scheduleWritePackageRestrictionsLocked(oneUserId); 15955 } 15956 } 15957 } else { 15958 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15959 scheduleWritePackageRestrictionsLocked(userId); 15960 } 15961 } 15962 } 15963 15964 void clearDefaultBrowserIfNeeded(String packageName) { 15965 for (int oneUserId : sUserManager.getUserIds()) { 15966 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15967 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15968 if (packageName.equals(defaultBrowserPackageName)) { 15969 setDefaultBrowserPackageName(null, oneUserId); 15970 } 15971 } 15972 } 15973 15974 @Override 15975 public void resetApplicationPreferences(int userId) { 15976 mContext.enforceCallingOrSelfPermission( 15977 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15978 // writer 15979 synchronized (mPackages) { 15980 final long identity = Binder.clearCallingIdentity(); 15981 try { 15982 clearPackagePreferredActivitiesLPw(null, userId); 15983 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15984 // TODO: We have to reset the default SMS and Phone. This requires 15985 // significant refactoring to keep all default apps in the package 15986 // manager (cleaner but more work) or have the services provide 15987 // callbacks to the package manager to request a default app reset. 15988 applyFactoryDefaultBrowserLPw(userId); 15989 clearIntentFilterVerificationsLPw(userId); 15990 primeDomainVerificationsLPw(userId); 15991 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15992 scheduleWritePackageRestrictionsLocked(userId); 15993 } finally { 15994 Binder.restoreCallingIdentity(identity); 15995 } 15996 } 15997 } 15998 15999 @Override 16000 public int getPreferredActivities(List<IntentFilter> outFilters, 16001 List<ComponentName> outActivities, String packageName) { 16002 16003 int num = 0; 16004 final int userId = UserHandle.getCallingUserId(); 16005 // reader 16006 synchronized (mPackages) { 16007 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16008 if (pir != null) { 16009 final Iterator<PreferredActivity> it = pir.filterIterator(); 16010 while (it.hasNext()) { 16011 final PreferredActivity pa = it.next(); 16012 if (packageName == null 16013 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16014 && pa.mPref.mAlways)) { 16015 if (outFilters != null) { 16016 outFilters.add(new IntentFilter(pa)); 16017 } 16018 if (outActivities != null) { 16019 outActivities.add(pa.mPref.mComponent); 16020 } 16021 } 16022 } 16023 } 16024 } 16025 16026 return num; 16027 } 16028 16029 @Override 16030 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16031 int userId) { 16032 int callingUid = Binder.getCallingUid(); 16033 if (callingUid != Process.SYSTEM_UID) { 16034 throw new SecurityException( 16035 "addPersistentPreferredActivity can only be run by the system"); 16036 } 16037 if (filter.countActions() == 0) { 16038 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16039 return; 16040 } 16041 synchronized (mPackages) { 16042 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16043 ":"); 16044 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16045 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16046 new PersistentPreferredActivity(filter, activity)); 16047 scheduleWritePackageRestrictionsLocked(userId); 16048 } 16049 } 16050 16051 @Override 16052 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16053 int callingUid = Binder.getCallingUid(); 16054 if (callingUid != Process.SYSTEM_UID) { 16055 throw new SecurityException( 16056 "clearPackagePersistentPreferredActivities can only be run by the system"); 16057 } 16058 ArrayList<PersistentPreferredActivity> removed = null; 16059 boolean changed = false; 16060 synchronized (mPackages) { 16061 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16062 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16063 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16064 .valueAt(i); 16065 if (userId != thisUserId) { 16066 continue; 16067 } 16068 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16069 while (it.hasNext()) { 16070 PersistentPreferredActivity ppa = it.next(); 16071 // Mark entry for removal only if it matches the package name. 16072 if (ppa.mComponent.getPackageName().equals(packageName)) { 16073 if (removed == null) { 16074 removed = new ArrayList<PersistentPreferredActivity>(); 16075 } 16076 removed.add(ppa); 16077 } 16078 } 16079 if (removed != null) { 16080 for (int j=0; j<removed.size(); j++) { 16081 PersistentPreferredActivity ppa = removed.get(j); 16082 ppir.removeFilter(ppa); 16083 } 16084 changed = true; 16085 } 16086 } 16087 16088 if (changed) { 16089 scheduleWritePackageRestrictionsLocked(userId); 16090 } 16091 } 16092 } 16093 16094 /** 16095 * Common machinery for picking apart a restored XML blob and passing 16096 * it to a caller-supplied functor to be applied to the running system. 16097 */ 16098 private void restoreFromXml(XmlPullParser parser, int userId, 16099 String expectedStartTag, BlobXmlRestorer functor) 16100 throws IOException, XmlPullParserException { 16101 int type; 16102 while ((type = parser.next()) != XmlPullParser.START_TAG 16103 && type != XmlPullParser.END_DOCUMENT) { 16104 } 16105 if (type != XmlPullParser.START_TAG) { 16106 // oops didn't find a start tag?! 16107 if (DEBUG_BACKUP) { 16108 Slog.e(TAG, "Didn't find start tag during restore"); 16109 } 16110 return; 16111 } 16112Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16113 // this is supposed to be TAG_PREFERRED_BACKUP 16114 if (!expectedStartTag.equals(parser.getName())) { 16115 if (DEBUG_BACKUP) { 16116 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16117 } 16118 return; 16119 } 16120 16121 // skip interfering stuff, then we're aligned with the backing implementation 16122 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16123Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16124 functor.apply(parser, userId); 16125 } 16126 16127 private interface BlobXmlRestorer { 16128 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16129 } 16130 16131 /** 16132 * Non-Binder method, support for the backup/restore mechanism: write the 16133 * full set of preferred activities in its canonical XML format. Returns the 16134 * XML output as a byte array, or null if there is none. 16135 */ 16136 @Override 16137 public byte[] getPreferredActivityBackup(int userId) { 16138 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16139 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16140 } 16141 16142 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16143 try { 16144 final XmlSerializer serializer = new FastXmlSerializer(); 16145 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16146 serializer.startDocument(null, true); 16147 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16148 16149 synchronized (mPackages) { 16150 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16151 } 16152 16153 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16154 serializer.endDocument(); 16155 serializer.flush(); 16156 } catch (Exception e) { 16157 if (DEBUG_BACKUP) { 16158 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16159 } 16160 return null; 16161 } 16162 16163 return dataStream.toByteArray(); 16164 } 16165 16166 @Override 16167 public void restorePreferredActivities(byte[] backup, int userId) { 16168 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16169 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16170 } 16171 16172 try { 16173 final XmlPullParser parser = Xml.newPullParser(); 16174 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16175 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16176 new BlobXmlRestorer() { 16177 @Override 16178 public void apply(XmlPullParser parser, int userId) 16179 throws XmlPullParserException, IOException { 16180 synchronized (mPackages) { 16181 mSettings.readPreferredActivitiesLPw(parser, userId); 16182 } 16183 } 16184 } ); 16185 } catch (Exception e) { 16186 if (DEBUG_BACKUP) { 16187 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16188 } 16189 } 16190 } 16191 16192 /** 16193 * Non-Binder method, support for the backup/restore mechanism: write the 16194 * default browser (etc) settings in its canonical XML format. Returns the default 16195 * browser XML representation as a byte array, or null if there is none. 16196 */ 16197 @Override 16198 public byte[] getDefaultAppsBackup(int userId) { 16199 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16200 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16201 } 16202 16203 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16204 try { 16205 final XmlSerializer serializer = new FastXmlSerializer(); 16206 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16207 serializer.startDocument(null, true); 16208 serializer.startTag(null, TAG_DEFAULT_APPS); 16209 16210 synchronized (mPackages) { 16211 mSettings.writeDefaultAppsLPr(serializer, userId); 16212 } 16213 16214 serializer.endTag(null, TAG_DEFAULT_APPS); 16215 serializer.endDocument(); 16216 serializer.flush(); 16217 } catch (Exception e) { 16218 if (DEBUG_BACKUP) { 16219 Slog.e(TAG, "Unable to write default apps for backup", e); 16220 } 16221 return null; 16222 } 16223 16224 return dataStream.toByteArray(); 16225 } 16226 16227 @Override 16228 public void restoreDefaultApps(byte[] backup, int userId) { 16229 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16230 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16231 } 16232 16233 try { 16234 final XmlPullParser parser = Xml.newPullParser(); 16235 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16236 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16237 new BlobXmlRestorer() { 16238 @Override 16239 public void apply(XmlPullParser parser, int userId) 16240 throws XmlPullParserException, IOException { 16241 synchronized (mPackages) { 16242 mSettings.readDefaultAppsLPw(parser, userId); 16243 } 16244 } 16245 } ); 16246 } catch (Exception e) { 16247 if (DEBUG_BACKUP) { 16248 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16249 } 16250 } 16251 } 16252 16253 @Override 16254 public byte[] getIntentFilterVerificationBackup(int userId) { 16255 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16256 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16257 } 16258 16259 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16260 try { 16261 final XmlSerializer serializer = new FastXmlSerializer(); 16262 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16263 serializer.startDocument(null, true); 16264 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16265 16266 synchronized (mPackages) { 16267 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16268 } 16269 16270 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16271 serializer.endDocument(); 16272 serializer.flush(); 16273 } catch (Exception e) { 16274 if (DEBUG_BACKUP) { 16275 Slog.e(TAG, "Unable to write default apps for backup", e); 16276 } 16277 return null; 16278 } 16279 16280 return dataStream.toByteArray(); 16281 } 16282 16283 @Override 16284 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16285 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16286 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16287 } 16288 16289 try { 16290 final XmlPullParser parser = Xml.newPullParser(); 16291 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16292 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16293 new BlobXmlRestorer() { 16294 @Override 16295 public void apply(XmlPullParser parser, int userId) 16296 throws XmlPullParserException, IOException { 16297 synchronized (mPackages) { 16298 mSettings.readAllDomainVerificationsLPr(parser, userId); 16299 mSettings.writeLPr(); 16300 } 16301 } 16302 } ); 16303 } catch (Exception e) { 16304 if (DEBUG_BACKUP) { 16305 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16306 } 16307 } 16308 } 16309 16310 @Override 16311 public byte[] getPermissionGrantBackup(int userId) { 16312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16313 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16314 } 16315 16316 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16317 try { 16318 final XmlSerializer serializer = new FastXmlSerializer(); 16319 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16320 serializer.startDocument(null, true); 16321 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16322 16323 synchronized (mPackages) { 16324 serializeRuntimePermissionGrantsLPr(serializer, userId); 16325 } 16326 16327 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16328 serializer.endDocument(); 16329 serializer.flush(); 16330 } catch (Exception e) { 16331 if (DEBUG_BACKUP) { 16332 Slog.e(TAG, "Unable to write default apps for backup", e); 16333 } 16334 return null; 16335 } 16336 16337 return dataStream.toByteArray(); 16338 } 16339 16340 @Override 16341 public void restorePermissionGrants(byte[] backup, int userId) { 16342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16343 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16344 } 16345 16346 try { 16347 final XmlPullParser parser = Xml.newPullParser(); 16348 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16349 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16350 new BlobXmlRestorer() { 16351 @Override 16352 public void apply(XmlPullParser parser, int userId) 16353 throws XmlPullParserException, IOException { 16354 synchronized (mPackages) { 16355 processRestoredPermissionGrantsLPr(parser, userId); 16356 } 16357 } 16358 } ); 16359 } catch (Exception e) { 16360 if (DEBUG_BACKUP) { 16361 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16362 } 16363 } 16364 } 16365 16366 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16367 throws IOException { 16368 serializer.startTag(null, TAG_ALL_GRANTS); 16369 16370 final int N = mSettings.mPackages.size(); 16371 for (int i = 0; i < N; i++) { 16372 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16373 boolean pkgGrantsKnown = false; 16374 16375 PermissionsState packagePerms = ps.getPermissionsState(); 16376 16377 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16378 final int grantFlags = state.getFlags(); 16379 // only look at grants that are not system/policy fixed 16380 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16381 final boolean isGranted = state.isGranted(); 16382 // And only back up the user-twiddled state bits 16383 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16384 final String packageName = mSettings.mPackages.keyAt(i); 16385 if (!pkgGrantsKnown) { 16386 serializer.startTag(null, TAG_GRANT); 16387 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16388 pkgGrantsKnown = true; 16389 } 16390 16391 final boolean userSet = 16392 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16393 final boolean userFixed = 16394 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16395 final boolean revoke = 16396 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16397 16398 serializer.startTag(null, TAG_PERMISSION); 16399 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16400 if (isGranted) { 16401 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16402 } 16403 if (userSet) { 16404 serializer.attribute(null, ATTR_USER_SET, "true"); 16405 } 16406 if (userFixed) { 16407 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16408 } 16409 if (revoke) { 16410 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16411 } 16412 serializer.endTag(null, TAG_PERMISSION); 16413 } 16414 } 16415 } 16416 16417 if (pkgGrantsKnown) { 16418 serializer.endTag(null, TAG_GRANT); 16419 } 16420 } 16421 16422 serializer.endTag(null, TAG_ALL_GRANTS); 16423 } 16424 16425 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16426 throws XmlPullParserException, IOException { 16427 String pkgName = null; 16428 int outerDepth = parser.getDepth(); 16429 int type; 16430 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16431 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16432 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16433 continue; 16434 } 16435 16436 final String tagName = parser.getName(); 16437 if (tagName.equals(TAG_GRANT)) { 16438 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16439 if (DEBUG_BACKUP) { 16440 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16441 } 16442 } else if (tagName.equals(TAG_PERMISSION)) { 16443 16444 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16445 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16446 16447 int newFlagSet = 0; 16448 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16449 newFlagSet |= FLAG_PERMISSION_USER_SET; 16450 } 16451 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16452 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16453 } 16454 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16455 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16456 } 16457 if (DEBUG_BACKUP) { 16458 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16459 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16460 } 16461 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16462 if (ps != null) { 16463 // Already installed so we apply the grant immediately 16464 if (DEBUG_BACKUP) { 16465 Slog.v(TAG, " + already installed; applying"); 16466 } 16467 PermissionsState perms = ps.getPermissionsState(); 16468 BasePermission bp = mSettings.mPermissions.get(permName); 16469 if (bp != null) { 16470 if (isGranted) { 16471 perms.grantRuntimePermission(bp, userId); 16472 } 16473 if (newFlagSet != 0) { 16474 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16475 } 16476 } 16477 } else { 16478 // Need to wait for post-restore install to apply the grant 16479 if (DEBUG_BACKUP) { 16480 Slog.v(TAG, " - not yet installed; saving for later"); 16481 } 16482 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16483 isGranted, newFlagSet, userId); 16484 } 16485 } else { 16486 PackageManagerService.reportSettingsProblem(Log.WARN, 16487 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16488 XmlUtils.skipCurrentTag(parser); 16489 } 16490 } 16491 16492 scheduleWriteSettingsLocked(); 16493 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16494 } 16495 16496 @Override 16497 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16498 int sourceUserId, int targetUserId, int flags) { 16499 mContext.enforceCallingOrSelfPermission( 16500 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16501 int callingUid = Binder.getCallingUid(); 16502 enforceOwnerRights(ownerPackage, callingUid); 16503 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16504 if (intentFilter.countActions() == 0) { 16505 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16506 return; 16507 } 16508 synchronized (mPackages) { 16509 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16510 ownerPackage, targetUserId, flags); 16511 CrossProfileIntentResolver resolver = 16512 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16513 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16514 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16515 if (existing != null) { 16516 int size = existing.size(); 16517 for (int i = 0; i < size; i++) { 16518 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16519 return; 16520 } 16521 } 16522 } 16523 resolver.addFilter(newFilter); 16524 scheduleWritePackageRestrictionsLocked(sourceUserId); 16525 } 16526 } 16527 16528 @Override 16529 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16530 mContext.enforceCallingOrSelfPermission( 16531 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16532 int callingUid = Binder.getCallingUid(); 16533 enforceOwnerRights(ownerPackage, callingUid); 16534 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16535 synchronized (mPackages) { 16536 CrossProfileIntentResolver resolver = 16537 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16538 ArraySet<CrossProfileIntentFilter> set = 16539 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16540 for (CrossProfileIntentFilter filter : set) { 16541 if (filter.getOwnerPackage().equals(ownerPackage)) { 16542 resolver.removeFilter(filter); 16543 } 16544 } 16545 scheduleWritePackageRestrictionsLocked(sourceUserId); 16546 } 16547 } 16548 16549 // Enforcing that callingUid is owning pkg on userId 16550 private void enforceOwnerRights(String pkg, int callingUid) { 16551 // The system owns everything. 16552 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16553 return; 16554 } 16555 int callingUserId = UserHandle.getUserId(callingUid); 16556 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16557 if (pi == null) { 16558 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16559 + callingUserId); 16560 } 16561 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16562 throw new SecurityException("Calling uid " + callingUid 16563 + " does not own package " + pkg); 16564 } 16565 } 16566 16567 @Override 16568 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16569 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16570 } 16571 16572 private Intent getHomeIntent() { 16573 Intent intent = new Intent(Intent.ACTION_MAIN); 16574 intent.addCategory(Intent.CATEGORY_HOME); 16575 return intent; 16576 } 16577 16578 private IntentFilter getHomeFilter() { 16579 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16580 filter.addCategory(Intent.CATEGORY_HOME); 16581 filter.addCategory(Intent.CATEGORY_DEFAULT); 16582 return filter; 16583 } 16584 16585 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16586 int userId) { 16587 Intent intent = getHomeIntent(); 16588 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16589 PackageManager.GET_META_DATA, userId); 16590 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16591 true, false, false, userId); 16592 16593 allHomeCandidates.clear(); 16594 if (list != null) { 16595 for (ResolveInfo ri : list) { 16596 allHomeCandidates.add(ri); 16597 } 16598 } 16599 return (preferred == null || preferred.activityInfo == null) 16600 ? null 16601 : new ComponentName(preferred.activityInfo.packageName, 16602 preferred.activityInfo.name); 16603 } 16604 16605 @Override 16606 public void setHomeActivity(ComponentName comp, int userId) { 16607 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16608 getHomeActivitiesAsUser(homeActivities, userId); 16609 16610 boolean found = false; 16611 16612 final int size = homeActivities.size(); 16613 final ComponentName[] set = new ComponentName[size]; 16614 for (int i = 0; i < size; i++) { 16615 final ResolveInfo candidate = homeActivities.get(i); 16616 final ActivityInfo info = candidate.activityInfo; 16617 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16618 set[i] = activityName; 16619 if (!found && activityName.equals(comp)) { 16620 found = true; 16621 } 16622 } 16623 if (!found) { 16624 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16625 + userId); 16626 } 16627 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16628 set, comp, userId); 16629 } 16630 16631 private @Nullable String getSetupWizardPackageName() { 16632 final Intent intent = new Intent(Intent.ACTION_MAIN); 16633 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 16634 16635 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 16636 MATCH_SYSTEM_ONLY | MATCH_DISABLED_COMPONENTS, UserHandle.myUserId()); 16637 if (matches.size() == 1) { 16638 return matches.get(0).getComponentInfo().packageName; 16639 } else { 16640 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 16641 + ": matches=" + matches); 16642 return null; 16643 } 16644 } 16645 16646 @Override 16647 public void setApplicationEnabledSetting(String appPackageName, 16648 int newState, int flags, int userId, String callingPackage) { 16649 if (!sUserManager.exists(userId)) return; 16650 if (callingPackage == null) { 16651 callingPackage = Integer.toString(Binder.getCallingUid()); 16652 } 16653 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16654 } 16655 16656 @Override 16657 public void setComponentEnabledSetting(ComponentName componentName, 16658 int newState, int flags, int userId) { 16659 if (!sUserManager.exists(userId)) return; 16660 setEnabledSetting(componentName.getPackageName(), 16661 componentName.getClassName(), newState, flags, userId, null); 16662 } 16663 16664 private void setEnabledSetting(final String packageName, String className, int newState, 16665 final int flags, int userId, String callingPackage) { 16666 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16667 || newState == COMPONENT_ENABLED_STATE_ENABLED 16668 || newState == COMPONENT_ENABLED_STATE_DISABLED 16669 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16670 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16671 throw new IllegalArgumentException("Invalid new component state: " 16672 + newState); 16673 } 16674 PackageSetting pkgSetting; 16675 final int uid = Binder.getCallingUid(); 16676 final int permission = mContext.checkCallingOrSelfPermission( 16677 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16678 enforceCrossUserPermission(uid, userId, 16679 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16680 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16681 boolean sendNow = false; 16682 boolean isApp = (className == null); 16683 String componentName = isApp ? packageName : className; 16684 int packageUid = -1; 16685 ArrayList<String> components; 16686 16687 // writer 16688 synchronized (mPackages) { 16689 pkgSetting = mSettings.mPackages.get(packageName); 16690 if (pkgSetting == null) { 16691 if (className == null) { 16692 throw new IllegalArgumentException("Unknown package: " + packageName); 16693 } 16694 throw new IllegalArgumentException( 16695 "Unknown component: " + packageName + "/" + className); 16696 } 16697 // Allow root and verify that userId is not being specified by a different user 16698 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16699 throw new SecurityException( 16700 "Permission Denial: attempt to change component state from pid=" 16701 + Binder.getCallingPid() 16702 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16703 } 16704 if (className == null) { 16705 // We're dealing with an application/package level state change 16706 if (pkgSetting.getEnabled(userId) == newState) { 16707 // Nothing to do 16708 return; 16709 } 16710 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16711 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16712 // Don't care about who enables an app. 16713 callingPackage = null; 16714 } 16715 pkgSetting.setEnabled(newState, userId, callingPackage); 16716 // pkgSetting.pkg.mSetEnabled = newState; 16717 } else { 16718 // We're dealing with a component level state change 16719 // First, verify that this is a valid class name. 16720 PackageParser.Package pkg = pkgSetting.pkg; 16721 if (pkg == null || !pkg.hasComponentClassName(className)) { 16722 if (pkg != null && 16723 pkg.applicationInfo.targetSdkVersion >= 16724 Build.VERSION_CODES.JELLY_BEAN) { 16725 throw new IllegalArgumentException("Component class " + className 16726 + " does not exist in " + packageName); 16727 } else { 16728 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16729 + className + " does not exist in " + packageName); 16730 } 16731 } 16732 switch (newState) { 16733 case COMPONENT_ENABLED_STATE_ENABLED: 16734 if (!pkgSetting.enableComponentLPw(className, userId)) { 16735 return; 16736 } 16737 break; 16738 case COMPONENT_ENABLED_STATE_DISABLED: 16739 if (!pkgSetting.disableComponentLPw(className, userId)) { 16740 return; 16741 } 16742 break; 16743 case COMPONENT_ENABLED_STATE_DEFAULT: 16744 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16745 return; 16746 } 16747 break; 16748 default: 16749 Slog.e(TAG, "Invalid new component state: " + newState); 16750 return; 16751 } 16752 } 16753 scheduleWritePackageRestrictionsLocked(userId); 16754 components = mPendingBroadcasts.get(userId, packageName); 16755 final boolean newPackage = components == null; 16756 if (newPackage) { 16757 components = new ArrayList<String>(); 16758 } 16759 if (!components.contains(componentName)) { 16760 components.add(componentName); 16761 } 16762 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16763 sendNow = true; 16764 // Purge entry from pending broadcast list if another one exists already 16765 // since we are sending one right away. 16766 mPendingBroadcasts.remove(userId, packageName); 16767 } else { 16768 if (newPackage) { 16769 mPendingBroadcasts.put(userId, packageName, components); 16770 } 16771 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16772 // Schedule a message 16773 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16774 } 16775 } 16776 } 16777 16778 long callingId = Binder.clearCallingIdentity(); 16779 try { 16780 if (sendNow) { 16781 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16782 sendPackageChangedBroadcast(packageName, 16783 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16784 } 16785 } finally { 16786 Binder.restoreCallingIdentity(callingId); 16787 } 16788 } 16789 16790 @Override 16791 public void flushPackageRestrictionsAsUser(int userId) { 16792 if (!sUserManager.exists(userId)) { 16793 return; 16794 } 16795 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 16796 false /* checkShell */, "flushPackageRestrictions"); 16797 synchronized (mPackages) { 16798 mSettings.writePackageRestrictionsLPr(userId); 16799 mDirtyUsers.remove(userId); 16800 if (mDirtyUsers.isEmpty()) { 16801 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 16802 } 16803 } 16804 } 16805 16806 private void sendPackageChangedBroadcast(String packageName, 16807 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16808 if (DEBUG_INSTALL) 16809 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16810 + componentNames); 16811 Bundle extras = new Bundle(4); 16812 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16813 String nameList[] = new String[componentNames.size()]; 16814 componentNames.toArray(nameList); 16815 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16816 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16817 extras.putInt(Intent.EXTRA_UID, packageUid); 16818 // If this is not reporting a change of the overall package, then only send it 16819 // to registered receivers. We don't want to launch a swath of apps for every 16820 // little component state change. 16821 final int flags = !componentNames.contains(packageName) 16822 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16823 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16824 new int[] {UserHandle.getUserId(packageUid)}); 16825 } 16826 16827 @Override 16828 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16829 if (!sUserManager.exists(userId)) return; 16830 final int uid = Binder.getCallingUid(); 16831 final int permission = mContext.checkCallingOrSelfPermission( 16832 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16833 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16834 enforceCrossUserPermission(uid, userId, 16835 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16836 // writer 16837 synchronized (mPackages) { 16838 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16839 allowedByPermission, uid, userId)) { 16840 scheduleWritePackageRestrictionsLocked(userId); 16841 } 16842 } 16843 } 16844 16845 @Override 16846 public String getInstallerPackageName(String packageName) { 16847 // reader 16848 synchronized (mPackages) { 16849 return mSettings.getInstallerPackageNameLPr(packageName); 16850 } 16851 } 16852 16853 @Override 16854 public int getApplicationEnabledSetting(String packageName, int userId) { 16855 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16856 int uid = Binder.getCallingUid(); 16857 enforceCrossUserPermission(uid, userId, 16858 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16859 // reader 16860 synchronized (mPackages) { 16861 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16862 } 16863 } 16864 16865 @Override 16866 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16867 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16868 int uid = Binder.getCallingUid(); 16869 enforceCrossUserPermission(uid, userId, 16870 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16871 // reader 16872 synchronized (mPackages) { 16873 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16874 } 16875 } 16876 16877 @Override 16878 public void enterSafeMode() { 16879 enforceSystemOrRoot("Only the system can request entering safe mode"); 16880 16881 if (!mSystemReady) { 16882 mSafeMode = true; 16883 } 16884 } 16885 16886 @Override 16887 public void systemReady() { 16888 mSystemReady = true; 16889 16890 // Read the compatibilty setting when the system is ready. 16891 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16892 mContext.getContentResolver(), 16893 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16894 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16895 if (DEBUG_SETTINGS) { 16896 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16897 } 16898 16899 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16900 16901 synchronized (mPackages) { 16902 // Verify that all of the preferred activity components actually 16903 // exist. It is possible for applications to be updated and at 16904 // that point remove a previously declared activity component that 16905 // had been set as a preferred activity. We try to clean this up 16906 // the next time we encounter that preferred activity, but it is 16907 // possible for the user flow to never be able to return to that 16908 // situation so here we do a sanity check to make sure we haven't 16909 // left any junk around. 16910 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16911 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16912 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16913 removed.clear(); 16914 for (PreferredActivity pa : pir.filterSet()) { 16915 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16916 removed.add(pa); 16917 } 16918 } 16919 if (removed.size() > 0) { 16920 for (int r=0; r<removed.size(); r++) { 16921 PreferredActivity pa = removed.get(r); 16922 Slog.w(TAG, "Removing dangling preferred activity: " 16923 + pa.mPref.mComponent); 16924 pir.removeFilter(pa); 16925 } 16926 mSettings.writePackageRestrictionsLPr( 16927 mSettings.mPreferredActivities.keyAt(i)); 16928 } 16929 } 16930 16931 for (int userId : UserManagerService.getInstance().getUserIds()) { 16932 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16933 grantPermissionsUserIds = ArrayUtils.appendInt( 16934 grantPermissionsUserIds, userId); 16935 } 16936 } 16937 } 16938 sUserManager.systemReady(); 16939 16940 // If we upgraded grant all default permissions before kicking off. 16941 for (int userId : grantPermissionsUserIds) { 16942 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16943 } 16944 16945 // Kick off any messages waiting for system ready 16946 if (mPostSystemReadyMessages != null) { 16947 for (Message msg : mPostSystemReadyMessages) { 16948 msg.sendToTarget(); 16949 } 16950 mPostSystemReadyMessages = null; 16951 } 16952 16953 // Watch for external volumes that come and go over time 16954 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16955 storage.registerListener(mStorageListener); 16956 16957 mInstallerService.systemReady(); 16958 mPackageDexOptimizer.systemReady(); 16959 16960 MountServiceInternal mountServiceInternal = LocalServices.getService( 16961 MountServiceInternal.class); 16962 mountServiceInternal.addExternalStoragePolicy( 16963 new MountServiceInternal.ExternalStorageMountPolicy() { 16964 @Override 16965 public int getMountMode(int uid, String packageName) { 16966 if (Process.isIsolated(uid)) { 16967 return Zygote.MOUNT_EXTERNAL_NONE; 16968 } 16969 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16970 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16971 } 16972 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16973 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16974 } 16975 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16976 return Zygote.MOUNT_EXTERNAL_READ; 16977 } 16978 return Zygote.MOUNT_EXTERNAL_WRITE; 16979 } 16980 16981 @Override 16982 public boolean hasExternalStorage(int uid, String packageName) { 16983 return true; 16984 } 16985 }); 16986 } 16987 16988 @Override 16989 public boolean isSafeMode() { 16990 return mSafeMode; 16991 } 16992 16993 @Override 16994 public boolean hasSystemUidErrors() { 16995 return mHasSystemUidErrors; 16996 } 16997 16998 static String arrayToString(int[] array) { 16999 StringBuffer buf = new StringBuffer(128); 17000 buf.append('['); 17001 if (array != null) { 17002 for (int i=0; i<array.length; i++) { 17003 if (i > 0) buf.append(", "); 17004 buf.append(array[i]); 17005 } 17006 } 17007 buf.append(']'); 17008 return buf.toString(); 17009 } 17010 17011 static class DumpState { 17012 public static final int DUMP_LIBS = 1 << 0; 17013 public static final int DUMP_FEATURES = 1 << 1; 17014 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17015 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17016 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17017 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17018 public static final int DUMP_PERMISSIONS = 1 << 6; 17019 public static final int DUMP_PACKAGES = 1 << 7; 17020 public static final int DUMP_SHARED_USERS = 1 << 8; 17021 public static final int DUMP_MESSAGES = 1 << 9; 17022 public static final int DUMP_PROVIDERS = 1 << 10; 17023 public static final int DUMP_VERIFIERS = 1 << 11; 17024 public static final int DUMP_PREFERRED = 1 << 12; 17025 public static final int DUMP_PREFERRED_XML = 1 << 13; 17026 public static final int DUMP_KEYSETS = 1 << 14; 17027 public static final int DUMP_VERSION = 1 << 15; 17028 public static final int DUMP_INSTALLS = 1 << 16; 17029 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17030 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17031 17032 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17033 17034 private int mTypes; 17035 17036 private int mOptions; 17037 17038 private boolean mTitlePrinted; 17039 17040 private SharedUserSetting mSharedUser; 17041 17042 public boolean isDumping(int type) { 17043 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17044 return true; 17045 } 17046 17047 return (mTypes & type) != 0; 17048 } 17049 17050 public void setDump(int type) { 17051 mTypes |= type; 17052 } 17053 17054 public boolean isOptionEnabled(int option) { 17055 return (mOptions & option) != 0; 17056 } 17057 17058 public void setOptionEnabled(int option) { 17059 mOptions |= option; 17060 } 17061 17062 public boolean onTitlePrinted() { 17063 final boolean printed = mTitlePrinted; 17064 mTitlePrinted = true; 17065 return printed; 17066 } 17067 17068 public boolean getTitlePrinted() { 17069 return mTitlePrinted; 17070 } 17071 17072 public void setTitlePrinted(boolean enabled) { 17073 mTitlePrinted = enabled; 17074 } 17075 17076 public SharedUserSetting getSharedUser() { 17077 return mSharedUser; 17078 } 17079 17080 public void setSharedUser(SharedUserSetting user) { 17081 mSharedUser = user; 17082 } 17083 } 17084 17085 @Override 17086 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17087 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17088 (new PackageManagerShellCommand(this)).exec( 17089 this, in, out, err, args, resultReceiver); 17090 } 17091 17092 @Override 17093 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17094 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17095 != PackageManager.PERMISSION_GRANTED) { 17096 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17097 + Binder.getCallingPid() 17098 + ", uid=" + Binder.getCallingUid() 17099 + " without permission " 17100 + android.Manifest.permission.DUMP); 17101 return; 17102 } 17103 17104 DumpState dumpState = new DumpState(); 17105 boolean fullPreferred = false; 17106 boolean checkin = false; 17107 17108 String packageName = null; 17109 ArraySet<String> permissionNames = null; 17110 17111 int opti = 0; 17112 while (opti < args.length) { 17113 String opt = args[opti]; 17114 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17115 break; 17116 } 17117 opti++; 17118 17119 if ("-a".equals(opt)) { 17120 // Right now we only know how to print all. 17121 } else if ("-h".equals(opt)) { 17122 pw.println("Package manager dump options:"); 17123 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17124 pw.println(" --checkin: dump for a checkin"); 17125 pw.println(" -f: print details of intent filters"); 17126 pw.println(" -h: print this help"); 17127 pw.println(" cmd may be one of:"); 17128 pw.println(" l[ibraries]: list known shared libraries"); 17129 pw.println(" f[eatures]: list device features"); 17130 pw.println(" k[eysets]: print known keysets"); 17131 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17132 pw.println(" perm[issions]: dump permissions"); 17133 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17134 pw.println(" pref[erred]: print preferred package settings"); 17135 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17136 pw.println(" prov[iders]: dump content providers"); 17137 pw.println(" p[ackages]: dump installed packages"); 17138 pw.println(" s[hared-users]: dump shared user IDs"); 17139 pw.println(" m[essages]: print collected runtime messages"); 17140 pw.println(" v[erifiers]: print package verifier info"); 17141 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17142 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17143 pw.println(" version: print database version info"); 17144 pw.println(" write: write current settings now"); 17145 pw.println(" installs: details about install sessions"); 17146 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17147 pw.println(" <package.name>: info about given package"); 17148 return; 17149 } else if ("--checkin".equals(opt)) { 17150 checkin = true; 17151 } else if ("-f".equals(opt)) { 17152 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17153 } else { 17154 pw.println("Unknown argument: " + opt + "; use -h for help"); 17155 } 17156 } 17157 17158 // Is the caller requesting to dump a particular piece of data? 17159 if (opti < args.length) { 17160 String cmd = args[opti]; 17161 opti++; 17162 // Is this a package name? 17163 if ("android".equals(cmd) || cmd.contains(".")) { 17164 packageName = cmd; 17165 // When dumping a single package, we always dump all of its 17166 // filter information since the amount of data will be reasonable. 17167 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17168 } else if ("check-permission".equals(cmd)) { 17169 if (opti >= args.length) { 17170 pw.println("Error: check-permission missing permission argument"); 17171 return; 17172 } 17173 String perm = args[opti]; 17174 opti++; 17175 if (opti >= args.length) { 17176 pw.println("Error: check-permission missing package argument"); 17177 return; 17178 } 17179 String pkg = args[opti]; 17180 opti++; 17181 int user = UserHandle.getUserId(Binder.getCallingUid()); 17182 if (opti < args.length) { 17183 try { 17184 user = Integer.parseInt(args[opti]); 17185 } catch (NumberFormatException e) { 17186 pw.println("Error: check-permission user argument is not a number: " 17187 + args[opti]); 17188 return; 17189 } 17190 } 17191 pw.println(checkPermission(perm, pkg, user)); 17192 return; 17193 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17194 dumpState.setDump(DumpState.DUMP_LIBS); 17195 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17196 dumpState.setDump(DumpState.DUMP_FEATURES); 17197 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17198 if (opti >= args.length) { 17199 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17200 | DumpState.DUMP_SERVICE_RESOLVERS 17201 | DumpState.DUMP_RECEIVER_RESOLVERS 17202 | DumpState.DUMP_CONTENT_RESOLVERS); 17203 } else { 17204 while (opti < args.length) { 17205 String name = args[opti]; 17206 if ("a".equals(name) || "activity".equals(name)) { 17207 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17208 } else if ("s".equals(name) || "service".equals(name)) { 17209 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17210 } else if ("r".equals(name) || "receiver".equals(name)) { 17211 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17212 } else if ("c".equals(name) || "content".equals(name)) { 17213 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17214 } else { 17215 pw.println("Error: unknown resolver table type: " + name); 17216 return; 17217 } 17218 opti++; 17219 } 17220 } 17221 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17222 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17223 } else if ("permission".equals(cmd)) { 17224 if (opti >= args.length) { 17225 pw.println("Error: permission requires permission name"); 17226 return; 17227 } 17228 permissionNames = new ArraySet<>(); 17229 while (opti < args.length) { 17230 permissionNames.add(args[opti]); 17231 opti++; 17232 } 17233 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17234 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17235 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17236 dumpState.setDump(DumpState.DUMP_PREFERRED); 17237 } else if ("preferred-xml".equals(cmd)) { 17238 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17239 if (opti < args.length && "--full".equals(args[opti])) { 17240 fullPreferred = true; 17241 opti++; 17242 } 17243 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17244 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17245 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17246 dumpState.setDump(DumpState.DUMP_PACKAGES); 17247 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17248 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17249 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17250 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17251 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17252 dumpState.setDump(DumpState.DUMP_MESSAGES); 17253 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17254 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17255 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17256 || "intent-filter-verifiers".equals(cmd)) { 17257 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17258 } else if ("version".equals(cmd)) { 17259 dumpState.setDump(DumpState.DUMP_VERSION); 17260 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17261 dumpState.setDump(DumpState.DUMP_KEYSETS); 17262 } else if ("installs".equals(cmd)) { 17263 dumpState.setDump(DumpState.DUMP_INSTALLS); 17264 } else if ("write".equals(cmd)) { 17265 synchronized (mPackages) { 17266 mSettings.writeLPr(); 17267 pw.println("Settings written."); 17268 return; 17269 } 17270 } 17271 } 17272 17273 if (checkin) { 17274 pw.println("vers,1"); 17275 } 17276 17277 // reader 17278 synchronized (mPackages) { 17279 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17280 if (!checkin) { 17281 if (dumpState.onTitlePrinted()) 17282 pw.println(); 17283 pw.println("Database versions:"); 17284 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17285 } 17286 } 17287 17288 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17289 if (!checkin) { 17290 if (dumpState.onTitlePrinted()) 17291 pw.println(); 17292 pw.println("Verifiers:"); 17293 pw.print(" Required: "); 17294 pw.print(mRequiredVerifierPackage); 17295 pw.print(" (uid="); 17296 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17297 UserHandle.USER_SYSTEM)); 17298 pw.println(")"); 17299 } else if (mRequiredVerifierPackage != null) { 17300 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17301 pw.print(","); 17302 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17303 UserHandle.USER_SYSTEM)); 17304 } 17305 } 17306 17307 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17308 packageName == null) { 17309 if (mIntentFilterVerifierComponent != null) { 17310 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17311 if (!checkin) { 17312 if (dumpState.onTitlePrinted()) 17313 pw.println(); 17314 pw.println("Intent Filter Verifier:"); 17315 pw.print(" Using: "); 17316 pw.print(verifierPackageName); 17317 pw.print(" (uid="); 17318 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17319 UserHandle.USER_SYSTEM)); 17320 pw.println(")"); 17321 } else if (verifierPackageName != null) { 17322 pw.print("ifv,"); pw.print(verifierPackageName); 17323 pw.print(","); 17324 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17325 UserHandle.USER_SYSTEM)); 17326 } 17327 } else { 17328 pw.println(); 17329 pw.println("No Intent Filter Verifier available!"); 17330 } 17331 } 17332 17333 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17334 boolean printedHeader = false; 17335 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17336 while (it.hasNext()) { 17337 String name = it.next(); 17338 SharedLibraryEntry ent = mSharedLibraries.get(name); 17339 if (!checkin) { 17340 if (!printedHeader) { 17341 if (dumpState.onTitlePrinted()) 17342 pw.println(); 17343 pw.println("Libraries:"); 17344 printedHeader = true; 17345 } 17346 pw.print(" "); 17347 } else { 17348 pw.print("lib,"); 17349 } 17350 pw.print(name); 17351 if (!checkin) { 17352 pw.print(" -> "); 17353 } 17354 if (ent.path != null) { 17355 if (!checkin) { 17356 pw.print("(jar) "); 17357 pw.print(ent.path); 17358 } else { 17359 pw.print(",jar,"); 17360 pw.print(ent.path); 17361 } 17362 } else { 17363 if (!checkin) { 17364 pw.print("(apk) "); 17365 pw.print(ent.apk); 17366 } else { 17367 pw.print(",apk,"); 17368 pw.print(ent.apk); 17369 } 17370 } 17371 pw.println(); 17372 } 17373 } 17374 17375 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17376 if (dumpState.onTitlePrinted()) 17377 pw.println(); 17378 if (!checkin) { 17379 pw.println("Features:"); 17380 } 17381 17382 for (FeatureInfo feat : mAvailableFeatures.values()) { 17383 if (checkin) { 17384 pw.print("feat,"); 17385 pw.print(feat.name); 17386 pw.print(","); 17387 pw.println(feat.version); 17388 } else { 17389 pw.print(" "); 17390 pw.print(feat.name); 17391 if (feat.version > 0) { 17392 pw.print(" version="); 17393 pw.print(feat.version); 17394 } 17395 pw.println(); 17396 } 17397 } 17398 } 17399 17400 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17401 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17402 : "Activity Resolver Table:", " ", packageName, 17403 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17404 dumpState.setTitlePrinted(true); 17405 } 17406 } 17407 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17408 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17409 : "Receiver Resolver Table:", " ", packageName, 17410 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17411 dumpState.setTitlePrinted(true); 17412 } 17413 } 17414 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17415 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17416 : "Service Resolver Table:", " ", packageName, 17417 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17418 dumpState.setTitlePrinted(true); 17419 } 17420 } 17421 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17422 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17423 : "Provider Resolver Table:", " ", packageName, 17424 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17425 dumpState.setTitlePrinted(true); 17426 } 17427 } 17428 17429 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17430 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17431 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17432 int user = mSettings.mPreferredActivities.keyAt(i); 17433 if (pir.dump(pw, 17434 dumpState.getTitlePrinted() 17435 ? "\nPreferred Activities User " + user + ":" 17436 : "Preferred Activities User " + user + ":", " ", 17437 packageName, true, false)) { 17438 dumpState.setTitlePrinted(true); 17439 } 17440 } 17441 } 17442 17443 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17444 pw.flush(); 17445 FileOutputStream fout = new FileOutputStream(fd); 17446 BufferedOutputStream str = new BufferedOutputStream(fout); 17447 XmlSerializer serializer = new FastXmlSerializer(); 17448 try { 17449 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17450 serializer.startDocument(null, true); 17451 serializer.setFeature( 17452 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17453 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17454 serializer.endDocument(); 17455 serializer.flush(); 17456 } catch (IllegalArgumentException e) { 17457 pw.println("Failed writing: " + e); 17458 } catch (IllegalStateException e) { 17459 pw.println("Failed writing: " + e); 17460 } catch (IOException e) { 17461 pw.println("Failed writing: " + e); 17462 } 17463 } 17464 17465 if (!checkin 17466 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17467 && packageName == null) { 17468 pw.println(); 17469 int count = mSettings.mPackages.size(); 17470 if (count == 0) { 17471 pw.println("No applications!"); 17472 pw.println(); 17473 } else { 17474 final String prefix = " "; 17475 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17476 if (allPackageSettings.size() == 0) { 17477 pw.println("No domain preferred apps!"); 17478 pw.println(); 17479 } else { 17480 pw.println("App verification status:"); 17481 pw.println(); 17482 count = 0; 17483 for (PackageSetting ps : allPackageSettings) { 17484 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17485 if (ivi == null || ivi.getPackageName() == null) continue; 17486 pw.println(prefix + "Package: " + ivi.getPackageName()); 17487 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17488 pw.println(prefix + "Status: " + ivi.getStatusString()); 17489 pw.println(); 17490 count++; 17491 } 17492 if (count == 0) { 17493 pw.println(prefix + "No app verification established."); 17494 pw.println(); 17495 } 17496 for (int userId : sUserManager.getUserIds()) { 17497 pw.println("App linkages for user " + userId + ":"); 17498 pw.println(); 17499 count = 0; 17500 for (PackageSetting ps : allPackageSettings) { 17501 final long status = ps.getDomainVerificationStatusForUser(userId); 17502 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17503 continue; 17504 } 17505 pw.println(prefix + "Package: " + ps.name); 17506 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17507 String statusStr = IntentFilterVerificationInfo. 17508 getStatusStringFromValue(status); 17509 pw.println(prefix + "Status: " + statusStr); 17510 pw.println(); 17511 count++; 17512 } 17513 if (count == 0) { 17514 pw.println(prefix + "No configured app linkages."); 17515 pw.println(); 17516 } 17517 } 17518 } 17519 } 17520 } 17521 17522 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17523 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17524 if (packageName == null && permissionNames == null) { 17525 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17526 if (iperm == 0) { 17527 if (dumpState.onTitlePrinted()) 17528 pw.println(); 17529 pw.println("AppOp Permissions:"); 17530 } 17531 pw.print(" AppOp Permission "); 17532 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17533 pw.println(":"); 17534 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17535 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17536 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17537 } 17538 } 17539 } 17540 } 17541 17542 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17543 boolean printedSomething = false; 17544 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17545 if (packageName != null && !packageName.equals(p.info.packageName)) { 17546 continue; 17547 } 17548 if (!printedSomething) { 17549 if (dumpState.onTitlePrinted()) 17550 pw.println(); 17551 pw.println("Registered ContentProviders:"); 17552 printedSomething = true; 17553 } 17554 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17555 pw.print(" "); pw.println(p.toString()); 17556 } 17557 printedSomething = false; 17558 for (Map.Entry<String, PackageParser.Provider> entry : 17559 mProvidersByAuthority.entrySet()) { 17560 PackageParser.Provider p = entry.getValue(); 17561 if (packageName != null && !packageName.equals(p.info.packageName)) { 17562 continue; 17563 } 17564 if (!printedSomething) { 17565 if (dumpState.onTitlePrinted()) 17566 pw.println(); 17567 pw.println("ContentProvider Authorities:"); 17568 printedSomething = true; 17569 } 17570 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17571 pw.print(" "); pw.println(p.toString()); 17572 if (p.info != null && p.info.applicationInfo != null) { 17573 final String appInfo = p.info.applicationInfo.toString(); 17574 pw.print(" applicationInfo="); pw.println(appInfo); 17575 } 17576 } 17577 } 17578 17579 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17580 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17581 } 17582 17583 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17584 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17585 } 17586 17587 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17588 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17589 } 17590 17591 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17592 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17593 } 17594 17595 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17596 // XXX should handle packageName != null by dumping only install data that 17597 // the given package is involved with. 17598 if (dumpState.onTitlePrinted()) pw.println(); 17599 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17600 } 17601 17602 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17603 if (dumpState.onTitlePrinted()) pw.println(); 17604 mSettings.dumpReadMessagesLPr(pw, dumpState); 17605 17606 pw.println(); 17607 pw.println("Package warning messages:"); 17608 BufferedReader in = null; 17609 String line = null; 17610 try { 17611 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17612 while ((line = in.readLine()) != null) { 17613 if (line.contains("ignored: updated version")) continue; 17614 pw.println(line); 17615 } 17616 } catch (IOException ignored) { 17617 } finally { 17618 IoUtils.closeQuietly(in); 17619 } 17620 } 17621 17622 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17623 BufferedReader in = null; 17624 String line = null; 17625 try { 17626 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17627 while ((line = in.readLine()) != null) { 17628 if (line.contains("ignored: updated version")) continue; 17629 pw.print("msg,"); 17630 pw.println(line); 17631 } 17632 } catch (IOException ignored) { 17633 } finally { 17634 IoUtils.closeQuietly(in); 17635 } 17636 } 17637 } 17638 } 17639 17640 private String dumpDomainString(String packageName) { 17641 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17642 .getList(); 17643 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17644 17645 ArraySet<String> result = new ArraySet<>(); 17646 if (iviList.size() > 0) { 17647 for (IntentFilterVerificationInfo ivi : iviList) { 17648 for (String host : ivi.getDomains()) { 17649 result.add(host); 17650 } 17651 } 17652 } 17653 if (filters != null && filters.size() > 0) { 17654 for (IntentFilter filter : filters) { 17655 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17656 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17657 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17658 result.addAll(filter.getHostsList()); 17659 } 17660 } 17661 } 17662 17663 StringBuilder sb = new StringBuilder(result.size() * 16); 17664 for (String domain : result) { 17665 if (sb.length() > 0) sb.append(" "); 17666 sb.append(domain); 17667 } 17668 return sb.toString(); 17669 } 17670 17671 // ------- apps on sdcard specific code ------- 17672 static final boolean DEBUG_SD_INSTALL = false; 17673 17674 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17675 17676 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17677 17678 private boolean mMediaMounted = false; 17679 17680 static String getEncryptKey() { 17681 try { 17682 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17683 SD_ENCRYPTION_KEYSTORE_NAME); 17684 if (sdEncKey == null) { 17685 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17686 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17687 if (sdEncKey == null) { 17688 Slog.e(TAG, "Failed to create encryption keys"); 17689 return null; 17690 } 17691 } 17692 return sdEncKey; 17693 } catch (NoSuchAlgorithmException nsae) { 17694 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17695 return null; 17696 } catch (IOException ioe) { 17697 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17698 return null; 17699 } 17700 } 17701 17702 /* 17703 * Update media status on PackageManager. 17704 */ 17705 @Override 17706 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17707 int callingUid = Binder.getCallingUid(); 17708 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17709 throw new SecurityException("Media status can only be updated by the system"); 17710 } 17711 // reader; this apparently protects mMediaMounted, but should probably 17712 // be a different lock in that case. 17713 synchronized (mPackages) { 17714 Log.i(TAG, "Updating external media status from " 17715 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17716 + (mediaStatus ? "mounted" : "unmounted")); 17717 if (DEBUG_SD_INSTALL) 17718 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17719 + ", mMediaMounted=" + mMediaMounted); 17720 if (mediaStatus == mMediaMounted) { 17721 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17722 : 0, -1); 17723 mHandler.sendMessage(msg); 17724 return; 17725 } 17726 mMediaMounted = mediaStatus; 17727 } 17728 // Queue up an async operation since the package installation may take a 17729 // little while. 17730 mHandler.post(new Runnable() { 17731 public void run() { 17732 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17733 } 17734 }); 17735 } 17736 17737 /** 17738 * Called by MountService when the initial ASECs to scan are available. 17739 * Should block until all the ASEC containers are finished being scanned. 17740 */ 17741 public void scanAvailableAsecs() { 17742 updateExternalMediaStatusInner(true, false, false); 17743 } 17744 17745 /* 17746 * Collect information of applications on external media, map them against 17747 * existing containers and update information based on current mount status. 17748 * Please note that we always have to report status if reportStatus has been 17749 * set to true especially when unloading packages. 17750 */ 17751 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17752 boolean externalStorage) { 17753 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17754 int[] uidArr = EmptyArray.INT; 17755 17756 final String[] list = PackageHelper.getSecureContainerList(); 17757 if (ArrayUtils.isEmpty(list)) { 17758 Log.i(TAG, "No secure containers found"); 17759 } else { 17760 // Process list of secure containers and categorize them 17761 // as active or stale based on their package internal state. 17762 17763 // reader 17764 synchronized (mPackages) { 17765 for (String cid : list) { 17766 // Leave stages untouched for now; installer service owns them 17767 if (PackageInstallerService.isStageName(cid)) continue; 17768 17769 if (DEBUG_SD_INSTALL) 17770 Log.i(TAG, "Processing container " + cid); 17771 String pkgName = getAsecPackageName(cid); 17772 if (pkgName == null) { 17773 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17774 continue; 17775 } 17776 if (DEBUG_SD_INSTALL) 17777 Log.i(TAG, "Looking for pkg : " + pkgName); 17778 17779 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17780 if (ps == null) { 17781 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17782 continue; 17783 } 17784 17785 /* 17786 * Skip packages that are not external if we're unmounting 17787 * external storage. 17788 */ 17789 if (externalStorage && !isMounted && !isExternal(ps)) { 17790 continue; 17791 } 17792 17793 final AsecInstallArgs args = new AsecInstallArgs(cid, 17794 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17795 // The package status is changed only if the code path 17796 // matches between settings and the container id. 17797 if (ps.codePathString != null 17798 && ps.codePathString.startsWith(args.getCodePath())) { 17799 if (DEBUG_SD_INSTALL) { 17800 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17801 + " at code path: " + ps.codePathString); 17802 } 17803 17804 // We do have a valid package installed on sdcard 17805 processCids.put(args, ps.codePathString); 17806 final int uid = ps.appId; 17807 if (uid != -1) { 17808 uidArr = ArrayUtils.appendInt(uidArr, uid); 17809 } 17810 } else { 17811 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17812 + ps.codePathString); 17813 } 17814 } 17815 } 17816 17817 Arrays.sort(uidArr); 17818 } 17819 17820 // Process packages with valid entries. 17821 if (isMounted) { 17822 if (DEBUG_SD_INSTALL) 17823 Log.i(TAG, "Loading packages"); 17824 loadMediaPackages(processCids, uidArr, externalStorage); 17825 startCleaningPackages(); 17826 mInstallerService.onSecureContainersAvailable(); 17827 } else { 17828 if (DEBUG_SD_INSTALL) 17829 Log.i(TAG, "Unloading packages"); 17830 unloadMediaPackages(processCids, uidArr, reportStatus); 17831 } 17832 } 17833 17834 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17835 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17836 final int size = infos.size(); 17837 final String[] packageNames = new String[size]; 17838 final int[] packageUids = new int[size]; 17839 for (int i = 0; i < size; i++) { 17840 final ApplicationInfo info = infos.get(i); 17841 packageNames[i] = info.packageName; 17842 packageUids[i] = info.uid; 17843 } 17844 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17845 finishedReceiver); 17846 } 17847 17848 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17849 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17850 sendResourcesChangedBroadcast(mediaStatus, replacing, 17851 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17852 } 17853 17854 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17855 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17856 int size = pkgList.length; 17857 if (size > 0) { 17858 // Send broadcasts here 17859 Bundle extras = new Bundle(); 17860 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17861 if (uidArr != null) { 17862 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17863 } 17864 if (replacing) { 17865 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17866 } 17867 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17868 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17869 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17870 } 17871 } 17872 17873 /* 17874 * Look at potentially valid container ids from processCids If package 17875 * information doesn't match the one on record or package scanning fails, 17876 * the cid is added to list of removeCids. We currently don't delete stale 17877 * containers. 17878 */ 17879 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17880 boolean externalStorage) { 17881 ArrayList<String> pkgList = new ArrayList<String>(); 17882 Set<AsecInstallArgs> keys = processCids.keySet(); 17883 17884 for (AsecInstallArgs args : keys) { 17885 String codePath = processCids.get(args); 17886 if (DEBUG_SD_INSTALL) 17887 Log.i(TAG, "Loading container : " + args.cid); 17888 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17889 try { 17890 // Make sure there are no container errors first. 17891 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17892 Slog.e(TAG, "Failed to mount cid : " + args.cid 17893 + " when installing from sdcard"); 17894 continue; 17895 } 17896 // Check code path here. 17897 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17898 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17899 + " does not match one in settings " + codePath); 17900 continue; 17901 } 17902 // Parse package 17903 int parseFlags = mDefParseFlags; 17904 if (args.isExternalAsec()) { 17905 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17906 } 17907 if (args.isFwdLocked()) { 17908 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17909 } 17910 17911 synchronized (mInstallLock) { 17912 PackageParser.Package pkg = null; 17913 try { 17914 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17915 } catch (PackageManagerException e) { 17916 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17917 } 17918 // Scan the package 17919 if (pkg != null) { 17920 /* 17921 * TODO why is the lock being held? doPostInstall is 17922 * called in other places without the lock. This needs 17923 * to be straightened out. 17924 */ 17925 // writer 17926 synchronized (mPackages) { 17927 retCode = PackageManager.INSTALL_SUCCEEDED; 17928 pkgList.add(pkg.packageName); 17929 // Post process args 17930 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17931 pkg.applicationInfo.uid); 17932 } 17933 } else { 17934 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17935 } 17936 } 17937 17938 } finally { 17939 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17940 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17941 } 17942 } 17943 } 17944 // writer 17945 synchronized (mPackages) { 17946 // If the platform SDK has changed since the last time we booted, 17947 // we need to re-grant app permission to catch any new ones that 17948 // appear. This is really a hack, and means that apps can in some 17949 // cases get permissions that the user didn't initially explicitly 17950 // allow... it would be nice to have some better way to handle 17951 // this situation. 17952 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17953 : mSettings.getInternalVersion(); 17954 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17955 : StorageManager.UUID_PRIVATE_INTERNAL; 17956 17957 int updateFlags = UPDATE_PERMISSIONS_ALL; 17958 if (ver.sdkVersion != mSdkVersion) { 17959 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17960 + mSdkVersion + "; regranting permissions for external"); 17961 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17962 } 17963 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17964 17965 // Yay, everything is now upgraded 17966 ver.forceCurrent(); 17967 17968 // can downgrade to reader 17969 // Persist settings 17970 mSettings.writeLPr(); 17971 } 17972 // Send a broadcast to let everyone know we are done processing 17973 if (pkgList.size() > 0) { 17974 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17975 } 17976 } 17977 17978 /* 17979 * Utility method to unload a list of specified containers 17980 */ 17981 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17982 // Just unmount all valid containers. 17983 for (AsecInstallArgs arg : cidArgs) { 17984 synchronized (mInstallLock) { 17985 arg.doPostDeleteLI(false); 17986 } 17987 } 17988 } 17989 17990 /* 17991 * Unload packages mounted on external media. This involves deleting package 17992 * data from internal structures, sending broadcasts about disabled packages, 17993 * gc'ing to free up references, unmounting all secure containers 17994 * corresponding to packages on external media, and posting a 17995 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17996 * that we always have to post this message if status has been requested no 17997 * matter what. 17998 */ 17999 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18000 final boolean reportStatus) { 18001 if (DEBUG_SD_INSTALL) 18002 Log.i(TAG, "unloading media packages"); 18003 ArrayList<String> pkgList = new ArrayList<String>(); 18004 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18005 final Set<AsecInstallArgs> keys = processCids.keySet(); 18006 for (AsecInstallArgs args : keys) { 18007 String pkgName = args.getPackageName(); 18008 if (DEBUG_SD_INSTALL) 18009 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18010 // Delete package internally 18011 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18012 synchronized (mInstallLock) { 18013 boolean res = deletePackageLI(pkgName, null, false, null, 18014 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18015 if (res) { 18016 pkgList.add(pkgName); 18017 } else { 18018 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18019 failedList.add(args); 18020 } 18021 } 18022 } 18023 18024 // reader 18025 synchronized (mPackages) { 18026 // We didn't update the settings after removing each package; 18027 // write them now for all packages. 18028 mSettings.writeLPr(); 18029 } 18030 18031 // We have to absolutely send UPDATED_MEDIA_STATUS only 18032 // after confirming that all the receivers processed the ordered 18033 // broadcast when packages get disabled, force a gc to clean things up. 18034 // and unload all the containers. 18035 if (pkgList.size() > 0) { 18036 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18037 new IIntentReceiver.Stub() { 18038 public void performReceive(Intent intent, int resultCode, String data, 18039 Bundle extras, boolean ordered, boolean sticky, 18040 int sendingUser) throws RemoteException { 18041 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18042 reportStatus ? 1 : 0, 1, keys); 18043 mHandler.sendMessage(msg); 18044 } 18045 }); 18046 } else { 18047 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18048 keys); 18049 mHandler.sendMessage(msg); 18050 } 18051 } 18052 18053 private void loadPrivatePackages(final VolumeInfo vol) { 18054 mHandler.post(new Runnable() { 18055 @Override 18056 public void run() { 18057 loadPrivatePackagesInner(vol); 18058 } 18059 }); 18060 } 18061 18062 private void loadPrivatePackagesInner(VolumeInfo vol) { 18063 final String volumeUuid = vol.fsUuid; 18064 if (TextUtils.isEmpty(volumeUuid)) { 18065 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18066 return; 18067 } 18068 18069 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18070 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18071 18072 final VersionInfo ver; 18073 final List<PackageSetting> packages; 18074 synchronized (mPackages) { 18075 ver = mSettings.findOrCreateVersion(volumeUuid); 18076 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18077 } 18078 18079 // TODO: introduce a new concept similar to "frozen" to prevent these 18080 // apps from being launched until after data has been fully reconciled 18081 for (PackageSetting ps : packages) { 18082 synchronized (mInstallLock) { 18083 final PackageParser.Package pkg; 18084 try { 18085 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18086 loaded.add(pkg.applicationInfo); 18087 18088 } catch (PackageManagerException e) { 18089 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18090 } 18091 18092 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18093 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18094 } 18095 } 18096 } 18097 18098 // Reconcile app data for all started/unlocked users 18099 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18100 final UserManager um = mContext.getSystemService(UserManager.class); 18101 for (UserInfo user : um.getUsers()) { 18102 final int flags; 18103 if (um.isUserUnlocked(user.id)) { 18104 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18105 } else if (um.isUserRunning(user.id)) { 18106 flags = StorageManager.FLAG_STORAGE_DE; 18107 } else { 18108 continue; 18109 } 18110 18111 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18112 reconcileAppsData(volumeUuid, user.id, flags); 18113 } 18114 18115 synchronized (mPackages) { 18116 int updateFlags = UPDATE_PERMISSIONS_ALL; 18117 if (ver.sdkVersion != mSdkVersion) { 18118 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18119 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18120 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18121 } 18122 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18123 18124 // Yay, everything is now upgraded 18125 ver.forceCurrent(); 18126 18127 mSettings.writeLPr(); 18128 } 18129 18130 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18131 sendResourcesChangedBroadcast(true, false, loaded, null); 18132 } 18133 18134 private void unloadPrivatePackages(final VolumeInfo vol) { 18135 mHandler.post(new Runnable() { 18136 @Override 18137 public void run() { 18138 unloadPrivatePackagesInner(vol); 18139 } 18140 }); 18141 } 18142 18143 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18144 final String volumeUuid = vol.fsUuid; 18145 if (TextUtils.isEmpty(volumeUuid)) { 18146 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18147 return; 18148 } 18149 18150 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18151 synchronized (mInstallLock) { 18152 synchronized (mPackages) { 18153 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18154 for (PackageSetting ps : packages) { 18155 if (ps.pkg == null) continue; 18156 18157 final ApplicationInfo info = ps.pkg.applicationInfo; 18158 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18159 if (deletePackageLI(ps.name, null, false, null, 18160 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18161 unloaded.add(info); 18162 } else { 18163 Slog.w(TAG, "Failed to unload " + ps.codePath); 18164 } 18165 } 18166 18167 mSettings.writeLPr(); 18168 } 18169 } 18170 18171 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18172 sendResourcesChangedBroadcast(false, false, unloaded, null); 18173 } 18174 18175 /** 18176 * Examine all users present on given mounted volume, and destroy data 18177 * belonging to users that are no longer valid, or whose user ID has been 18178 * recycled. 18179 */ 18180 private void reconcileUsers(String volumeUuid) { 18181 // TODO: also reconcile DE directories 18182 final File[] files = FileUtils 18183 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18184 for (File file : files) { 18185 if (!file.isDirectory()) continue; 18186 18187 final int userId; 18188 final UserInfo info; 18189 try { 18190 userId = Integer.parseInt(file.getName()); 18191 info = sUserManager.getUserInfo(userId); 18192 } catch (NumberFormatException e) { 18193 Slog.w(TAG, "Invalid user directory " + file); 18194 continue; 18195 } 18196 18197 boolean destroyUser = false; 18198 if (info == null) { 18199 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18200 + " because no matching user was found"); 18201 destroyUser = true; 18202 } else { 18203 try { 18204 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18205 } catch (IOException e) { 18206 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18207 + " because we failed to enforce serial number: " + e); 18208 destroyUser = true; 18209 } 18210 } 18211 18212 if (destroyUser) { 18213 synchronized (mInstallLock) { 18214 try { 18215 mInstaller.removeUserDataDirs(volumeUuid, userId); 18216 } catch (InstallerException e) { 18217 Slog.w(TAG, "Failed to clean up user dirs", e); 18218 } 18219 } 18220 } 18221 } 18222 } 18223 18224 private void assertPackageKnown(String volumeUuid, String packageName) 18225 throws PackageManagerException { 18226 synchronized (mPackages) { 18227 final PackageSetting ps = mSettings.mPackages.get(packageName); 18228 if (ps == null) { 18229 throw new PackageManagerException("Package " + packageName + " is unknown"); 18230 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18231 throw new PackageManagerException( 18232 "Package " + packageName + " found on unknown volume " + volumeUuid 18233 + "; expected volume " + ps.volumeUuid); 18234 } 18235 } 18236 } 18237 18238 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18239 throws PackageManagerException { 18240 synchronized (mPackages) { 18241 final PackageSetting ps = mSettings.mPackages.get(packageName); 18242 if (ps == null) { 18243 throw new PackageManagerException("Package " + packageName + " is unknown"); 18244 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18245 throw new PackageManagerException( 18246 "Package " + packageName + " found on unknown volume " + volumeUuid 18247 + "; expected volume " + ps.volumeUuid); 18248 } else if (!ps.getInstalled(userId)) { 18249 throw new PackageManagerException( 18250 "Package " + packageName + " not installed for user " + userId); 18251 } 18252 } 18253 } 18254 18255 /** 18256 * Examine all apps present on given mounted volume, and destroy apps that 18257 * aren't expected, either due to uninstallation or reinstallation on 18258 * another volume. 18259 */ 18260 private void reconcileApps(String volumeUuid) { 18261 final File[] files = FileUtils 18262 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18263 for (File file : files) { 18264 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18265 && !PackageInstallerService.isStageName(file.getName()); 18266 if (!isPackage) { 18267 // Ignore entries which are not packages 18268 continue; 18269 } 18270 18271 try { 18272 final PackageLite pkg = PackageParser.parsePackageLite(file, 18273 PackageParser.PARSE_MUST_BE_APK); 18274 assertPackageKnown(volumeUuid, pkg.packageName); 18275 18276 } catch (PackageParserException | PackageManagerException e) { 18277 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18278 synchronized (mInstallLock) { 18279 removeCodePathLI(file); 18280 } 18281 } 18282 } 18283 } 18284 18285 /** 18286 * Reconcile all app data for the given user. 18287 * <p> 18288 * Verifies that directories exist and that ownership and labeling is 18289 * correct for all installed apps on all mounted volumes. 18290 */ 18291 void reconcileAppsData(int userId, int flags) { 18292 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18293 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18294 final String volumeUuid = vol.getFsUuid(); 18295 reconcileAppsData(volumeUuid, userId, flags); 18296 } 18297 } 18298 18299 /** 18300 * Reconcile all app data on given mounted volume. 18301 * <p> 18302 * Destroys app data that isn't expected, either due to uninstallation or 18303 * reinstallation on another volume. 18304 * <p> 18305 * Verifies that directories exist and that ownership and labeling is 18306 * correct for all installed apps. 18307 */ 18308 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18309 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18310 + Integer.toHexString(flags)); 18311 18312 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18313 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18314 18315 boolean restoreconNeeded = false; 18316 18317 // First look for stale data that doesn't belong, and check if things 18318 // have changed since we did our last restorecon 18319 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18320 if (!isUserKeyUnlocked(userId)) { 18321 throw new RuntimeException( 18322 "Yikes, someone asked us to reconcile CE storage while " + userId 18323 + " was still locked; this would have caused massive data loss!"); 18324 } 18325 18326 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18327 18328 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18329 for (File file : files) { 18330 final String packageName = file.getName(); 18331 try { 18332 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18333 } catch (PackageManagerException e) { 18334 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18335 synchronized (mInstallLock) { 18336 destroyAppDataLI(volumeUuid, packageName, userId, 18337 StorageManager.FLAG_STORAGE_CE); 18338 } 18339 } 18340 } 18341 } 18342 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18343 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18344 18345 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18346 for (File file : files) { 18347 final String packageName = file.getName(); 18348 try { 18349 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18350 } catch (PackageManagerException e) { 18351 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18352 synchronized (mInstallLock) { 18353 destroyAppDataLI(volumeUuid, packageName, userId, 18354 StorageManager.FLAG_STORAGE_DE); 18355 } 18356 } 18357 } 18358 } 18359 18360 // Ensure that data directories are ready to roll for all packages 18361 // installed for this volume and user 18362 final List<PackageSetting> packages; 18363 synchronized (mPackages) { 18364 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18365 } 18366 int preparedCount = 0; 18367 for (PackageSetting ps : packages) { 18368 final String packageName = ps.name; 18369 if (ps.pkg == null) { 18370 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18371 // TODO: might be due to legacy ASEC apps; we should circle back 18372 // and reconcile again once they're scanned 18373 continue; 18374 } 18375 18376 if (ps.getInstalled(userId)) { 18377 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18378 18379 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18380 // We may have just shuffled around app data directories, so 18381 // prepare them one more time 18382 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18383 } 18384 18385 preparedCount++; 18386 } 18387 } 18388 18389 if (restoreconNeeded) { 18390 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18391 SELinuxMMAC.setRestoreconDone(ceDir); 18392 } 18393 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18394 SELinuxMMAC.setRestoreconDone(deDir); 18395 } 18396 } 18397 18398 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18399 + " packages; restoreconNeeded was " + restoreconNeeded); 18400 } 18401 18402 /** 18403 * Prepare app data for the given app just after it was installed or 18404 * upgraded. This method carefully only touches users that it's installed 18405 * for, and it forces a restorecon to handle any seinfo changes. 18406 * <p> 18407 * Verifies that directories exist and that ownership and labeling is 18408 * correct for all installed apps. If there is an ownership mismatch, it 18409 * will try recovering system apps by wiping data; third-party app data is 18410 * left intact. 18411 * <p> 18412 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18413 */ 18414 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18415 prepareAppDataAfterInstallInternal(pkg); 18416 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18417 for (int i = 0; i < childCount; i++) { 18418 PackageParser.Package childPackage = pkg.childPackages.get(i); 18419 prepareAppDataAfterInstallInternal(childPackage); 18420 } 18421 } 18422 18423 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18424 final PackageSetting ps; 18425 synchronized (mPackages) { 18426 ps = mSettings.mPackages.get(pkg.packageName); 18427 mSettings.writeKernelMappingLPr(ps); 18428 } 18429 18430 final UserManager um = mContext.getSystemService(UserManager.class); 18431 for (UserInfo user : um.getUsers()) { 18432 final int flags; 18433 if (um.isUserUnlocked(user.id)) { 18434 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18435 } else if (um.isUserRunning(user.id)) { 18436 flags = StorageManager.FLAG_STORAGE_DE; 18437 } else { 18438 continue; 18439 } 18440 18441 if (ps.getInstalled(user.id)) { 18442 // Whenever an app changes, force a restorecon of its data 18443 // TODO: when user data is locked, mark that we're still dirty 18444 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18445 } 18446 } 18447 } 18448 18449 /** 18450 * Prepare app data for the given app. 18451 * <p> 18452 * Verifies that directories exist and that ownership and labeling is 18453 * correct for all installed apps. If there is an ownership mismatch, this 18454 * will try recovering system apps by wiping data; third-party app data is 18455 * left intact. 18456 */ 18457 private void prepareAppData(String volumeUuid, int userId, int flags, 18458 PackageParser.Package pkg, boolean restoreconNeeded) { 18459 if (DEBUG_APP_DATA) { 18460 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18461 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18462 } 18463 18464 final String packageName = pkg.packageName; 18465 final ApplicationInfo app = pkg.applicationInfo; 18466 final int appId = UserHandle.getAppId(app.uid); 18467 18468 Preconditions.checkNotNull(app.seinfo); 18469 18470 synchronized (mInstallLock) { 18471 try { 18472 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18473 appId, app.seinfo, app.targetSdkVersion); 18474 } catch (InstallerException e) { 18475 if (app.isSystemApp()) { 18476 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18477 + ", but trying to recover: " + e); 18478 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18479 try { 18480 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18481 appId, app.seinfo, app.targetSdkVersion); 18482 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18483 } catch (InstallerException e2) { 18484 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18485 } 18486 } else { 18487 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18488 } 18489 } 18490 18491 if (restoreconNeeded) { 18492 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18493 } 18494 18495 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18496 // Create a native library symlink only if we have native libraries 18497 // and if the native libraries are 32 bit libraries. We do not provide 18498 // this symlink for 64 bit libraries. 18499 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18500 final String nativeLibPath = app.nativeLibraryDir; 18501 try { 18502 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18503 nativeLibPath, userId); 18504 } catch (InstallerException e) { 18505 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18506 } 18507 } 18508 } 18509 } 18510 } 18511 18512 /** 18513 * For system apps on non-FBE devices, this method migrates any existing 18514 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18515 * requested by the app. 18516 */ 18517 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18518 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18519 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18520 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18521 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18522 synchronized (mInstallLock) { 18523 try { 18524 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18525 } catch (InstallerException e) { 18526 logCriticalInfo(Log.WARN, 18527 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18528 } 18529 } 18530 return true; 18531 } else { 18532 return false; 18533 } 18534 } 18535 18536 private void unfreezePackage(String packageName) { 18537 synchronized (mPackages) { 18538 final PackageSetting ps = mSettings.mPackages.get(packageName); 18539 if (ps != null) { 18540 ps.frozen = false; 18541 } 18542 } 18543 } 18544 18545 @Override 18546 public int movePackage(final String packageName, final String volumeUuid) { 18547 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18548 18549 final int moveId = mNextMoveId.getAndIncrement(); 18550 mHandler.post(new Runnable() { 18551 @Override 18552 public void run() { 18553 try { 18554 movePackageInternal(packageName, volumeUuid, moveId); 18555 } catch (PackageManagerException e) { 18556 Slog.w(TAG, "Failed to move " + packageName, e); 18557 mMoveCallbacks.notifyStatusChanged(moveId, 18558 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18559 } 18560 } 18561 }); 18562 return moveId; 18563 } 18564 18565 private void movePackageInternal(final String packageName, final String volumeUuid, 18566 final int moveId) throws PackageManagerException { 18567 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18568 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18569 final PackageManager pm = mContext.getPackageManager(); 18570 18571 final boolean currentAsec; 18572 final String currentVolumeUuid; 18573 final File codeFile; 18574 final String installerPackageName; 18575 final String packageAbiOverride; 18576 final int appId; 18577 final String seinfo; 18578 final String label; 18579 final int targetSdkVersion; 18580 18581 // reader 18582 synchronized (mPackages) { 18583 final PackageParser.Package pkg = mPackages.get(packageName); 18584 final PackageSetting ps = mSettings.mPackages.get(packageName); 18585 if (pkg == null || ps == null) { 18586 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18587 } 18588 18589 if (pkg.applicationInfo.isSystemApp()) { 18590 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18591 "Cannot move system application"); 18592 } 18593 18594 if (pkg.applicationInfo.isExternalAsec()) { 18595 currentAsec = true; 18596 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18597 } else if (pkg.applicationInfo.isForwardLocked()) { 18598 currentAsec = true; 18599 currentVolumeUuid = "forward_locked"; 18600 } else { 18601 currentAsec = false; 18602 currentVolumeUuid = ps.volumeUuid; 18603 18604 final File probe = new File(pkg.codePath); 18605 final File probeOat = new File(probe, "oat"); 18606 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18607 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18608 "Move only supported for modern cluster style installs"); 18609 } 18610 } 18611 18612 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18613 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18614 "Package already moved to " + volumeUuid); 18615 } 18616 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18617 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18618 "Device admin cannot be moved"); 18619 } 18620 18621 if (ps.frozen) { 18622 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18623 "Failed to move already frozen package"); 18624 } 18625 ps.frozen = true; 18626 18627 codeFile = new File(pkg.codePath); 18628 installerPackageName = ps.installerPackageName; 18629 packageAbiOverride = ps.cpuAbiOverrideString; 18630 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18631 seinfo = pkg.applicationInfo.seinfo; 18632 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18633 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18634 } 18635 18636 // Now that we're guarded by frozen state, kill app during move 18637 final long token = Binder.clearCallingIdentity(); 18638 try { 18639 killApplication(packageName, appId, "move pkg"); 18640 } finally { 18641 Binder.restoreCallingIdentity(token); 18642 } 18643 18644 final Bundle extras = new Bundle(); 18645 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18646 extras.putString(Intent.EXTRA_TITLE, label); 18647 mMoveCallbacks.notifyCreated(moveId, extras); 18648 18649 int installFlags; 18650 final boolean moveCompleteApp; 18651 final File measurePath; 18652 18653 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18654 installFlags = INSTALL_INTERNAL; 18655 moveCompleteApp = !currentAsec; 18656 measurePath = Environment.getDataAppDirectory(volumeUuid); 18657 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18658 installFlags = INSTALL_EXTERNAL; 18659 moveCompleteApp = false; 18660 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18661 } else { 18662 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18663 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18664 || !volume.isMountedWritable()) { 18665 unfreezePackage(packageName); 18666 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18667 "Move location not mounted private volume"); 18668 } 18669 18670 Preconditions.checkState(!currentAsec); 18671 18672 installFlags = INSTALL_INTERNAL; 18673 moveCompleteApp = true; 18674 measurePath = Environment.getDataAppDirectory(volumeUuid); 18675 } 18676 18677 final PackageStats stats = new PackageStats(null, -1); 18678 synchronized (mInstaller) { 18679 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18680 unfreezePackage(packageName); 18681 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18682 "Failed to measure package size"); 18683 } 18684 } 18685 18686 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18687 + stats.dataSize); 18688 18689 final long startFreeBytes = measurePath.getFreeSpace(); 18690 final long sizeBytes; 18691 if (moveCompleteApp) { 18692 sizeBytes = stats.codeSize + stats.dataSize; 18693 } else { 18694 sizeBytes = stats.codeSize; 18695 } 18696 18697 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18698 unfreezePackage(packageName); 18699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18700 "Not enough free space to move"); 18701 } 18702 18703 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18704 18705 final CountDownLatch installedLatch = new CountDownLatch(1); 18706 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18707 @Override 18708 public void onUserActionRequired(Intent intent) throws RemoteException { 18709 throw new IllegalStateException(); 18710 } 18711 18712 @Override 18713 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18714 Bundle extras) throws RemoteException { 18715 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18716 + PackageManager.installStatusToString(returnCode, msg)); 18717 18718 installedLatch.countDown(); 18719 18720 // Regardless of success or failure of the move operation, 18721 // always unfreeze the package 18722 unfreezePackage(packageName); 18723 18724 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18725 switch (status) { 18726 case PackageInstaller.STATUS_SUCCESS: 18727 mMoveCallbacks.notifyStatusChanged(moveId, 18728 PackageManager.MOVE_SUCCEEDED); 18729 break; 18730 case PackageInstaller.STATUS_FAILURE_STORAGE: 18731 mMoveCallbacks.notifyStatusChanged(moveId, 18732 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18733 break; 18734 default: 18735 mMoveCallbacks.notifyStatusChanged(moveId, 18736 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18737 break; 18738 } 18739 } 18740 }; 18741 18742 final MoveInfo move; 18743 if (moveCompleteApp) { 18744 // Kick off a thread to report progress estimates 18745 new Thread() { 18746 @Override 18747 public void run() { 18748 while (true) { 18749 try { 18750 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18751 break; 18752 } 18753 } catch (InterruptedException ignored) { 18754 } 18755 18756 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18757 final int progress = 10 + (int) MathUtils.constrain( 18758 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18759 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18760 } 18761 } 18762 }.start(); 18763 18764 final String dataAppName = codeFile.getName(); 18765 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18766 dataAppName, appId, seinfo, targetSdkVersion); 18767 } else { 18768 move = null; 18769 } 18770 18771 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18772 18773 final Message msg = mHandler.obtainMessage(INIT_COPY); 18774 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18775 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18776 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18777 packageAbiOverride, null); 18778 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18779 msg.obj = params; 18780 18781 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18782 System.identityHashCode(msg.obj)); 18783 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18784 System.identityHashCode(msg.obj)); 18785 18786 mHandler.sendMessage(msg); 18787 } 18788 18789 @Override 18790 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18791 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18792 18793 final int realMoveId = mNextMoveId.getAndIncrement(); 18794 final Bundle extras = new Bundle(); 18795 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18796 mMoveCallbacks.notifyCreated(realMoveId, extras); 18797 18798 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18799 @Override 18800 public void onCreated(int moveId, Bundle extras) { 18801 // Ignored 18802 } 18803 18804 @Override 18805 public void onStatusChanged(int moveId, int status, long estMillis) { 18806 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18807 } 18808 }; 18809 18810 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18811 storage.setPrimaryStorageUuid(volumeUuid, callback); 18812 return realMoveId; 18813 } 18814 18815 @Override 18816 public int getMoveStatus(int moveId) { 18817 mContext.enforceCallingOrSelfPermission( 18818 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18819 return mMoveCallbacks.mLastStatus.get(moveId); 18820 } 18821 18822 @Override 18823 public void registerMoveCallback(IPackageMoveObserver callback) { 18824 mContext.enforceCallingOrSelfPermission( 18825 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18826 mMoveCallbacks.register(callback); 18827 } 18828 18829 @Override 18830 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18831 mContext.enforceCallingOrSelfPermission( 18832 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18833 mMoveCallbacks.unregister(callback); 18834 } 18835 18836 @Override 18837 public boolean setInstallLocation(int loc) { 18838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18839 null); 18840 if (getInstallLocation() == loc) { 18841 return true; 18842 } 18843 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18844 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18845 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18846 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18847 return true; 18848 } 18849 return false; 18850 } 18851 18852 @Override 18853 public int getInstallLocation() { 18854 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18855 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18856 PackageHelper.APP_INSTALL_AUTO); 18857 } 18858 18859 /** Called by UserManagerService */ 18860 void cleanUpUser(UserManagerService userManager, int userHandle) { 18861 synchronized (mPackages) { 18862 mDirtyUsers.remove(userHandle); 18863 mUserNeedsBadging.delete(userHandle); 18864 mSettings.removeUserLPw(userHandle); 18865 mPendingBroadcasts.remove(userHandle); 18866 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18867 } 18868 synchronized (mInstallLock) { 18869 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18870 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18871 final String volumeUuid = vol.getFsUuid(); 18872 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18873 try { 18874 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18875 } catch (InstallerException e) { 18876 Slog.w(TAG, "Failed to remove user data", e); 18877 } 18878 } 18879 synchronized (mPackages) { 18880 removeUnusedPackagesLILPw(userManager, userHandle); 18881 } 18882 } 18883 } 18884 18885 /** 18886 * We're removing userHandle and would like to remove any downloaded packages 18887 * that are no longer in use by any other user. 18888 * @param userHandle the user being removed 18889 */ 18890 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18891 final boolean DEBUG_CLEAN_APKS = false; 18892 int [] users = userManager.getUserIds(); 18893 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18894 while (psit.hasNext()) { 18895 PackageSetting ps = psit.next(); 18896 if (ps.pkg == null) { 18897 continue; 18898 } 18899 final String packageName = ps.pkg.packageName; 18900 // Skip over if system app 18901 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18902 continue; 18903 } 18904 if (DEBUG_CLEAN_APKS) { 18905 Slog.i(TAG, "Checking package " + packageName); 18906 } 18907 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18908 if (keep) { 18909 if (DEBUG_CLEAN_APKS) { 18910 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18911 } 18912 } else { 18913 for (int i = 0; i < users.length; i++) { 18914 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18915 keep = true; 18916 if (DEBUG_CLEAN_APKS) { 18917 Slog.i(TAG, " Keeping package " + packageName + " for user " 18918 + users[i]); 18919 } 18920 break; 18921 } 18922 } 18923 } 18924 if (!keep) { 18925 if (DEBUG_CLEAN_APKS) { 18926 Slog.i(TAG, " Removing package " + packageName); 18927 } 18928 mHandler.post(new Runnable() { 18929 public void run() { 18930 deletePackageX(packageName, userHandle, 0); 18931 } //end run 18932 }); 18933 } 18934 } 18935 } 18936 18937 /** Called by UserManagerService */ 18938 void createNewUser(int userHandle) { 18939 synchronized (mInstallLock) { 18940 try { 18941 mInstaller.createUserConfig(userHandle); 18942 } catch (InstallerException e) { 18943 Slog.w(TAG, "Failed to create user config", e); 18944 } 18945 mSettings.createNewUserLI(this, mInstaller, userHandle); 18946 } 18947 synchronized (mPackages) { 18948 applyFactoryDefaultBrowserLPw(userHandle); 18949 primeDomainVerificationsLPw(userHandle); 18950 } 18951 } 18952 18953 void newUserCreated(final int userHandle) { 18954 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18955 // If permission review for legacy apps is required, we represent 18956 // dagerous permissions for such apps as always granted runtime 18957 // permissions to keep per user flag state whether review is needed. 18958 // Hence, if a new user is added we have to propagate dangerous 18959 // permission grants for these legacy apps. 18960 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18961 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18962 | UPDATE_PERMISSIONS_REPLACE_ALL); 18963 } 18964 } 18965 18966 @Override 18967 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18968 mContext.enforceCallingOrSelfPermission( 18969 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18970 "Only package verification agents can read the verifier device identity"); 18971 18972 synchronized (mPackages) { 18973 return mSettings.getVerifierDeviceIdentityLPw(); 18974 } 18975 } 18976 18977 @Override 18978 public void setPermissionEnforced(String permission, boolean enforced) { 18979 // TODO: Now that we no longer change GID for storage, this should to away. 18980 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18981 "setPermissionEnforced"); 18982 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18983 synchronized (mPackages) { 18984 if (mSettings.mReadExternalStorageEnforced == null 18985 || mSettings.mReadExternalStorageEnforced != enforced) { 18986 mSettings.mReadExternalStorageEnforced = enforced; 18987 mSettings.writeLPr(); 18988 } 18989 } 18990 // kill any non-foreground processes so we restart them and 18991 // grant/revoke the GID. 18992 final IActivityManager am = ActivityManagerNative.getDefault(); 18993 if (am != null) { 18994 final long token = Binder.clearCallingIdentity(); 18995 try { 18996 am.killProcessesBelowForeground("setPermissionEnforcement"); 18997 } catch (RemoteException e) { 18998 } finally { 18999 Binder.restoreCallingIdentity(token); 19000 } 19001 } 19002 } else { 19003 throw new IllegalArgumentException("No selective enforcement for " + permission); 19004 } 19005 } 19006 19007 @Override 19008 @Deprecated 19009 public boolean isPermissionEnforced(String permission) { 19010 return true; 19011 } 19012 19013 @Override 19014 public boolean isStorageLow() { 19015 final long token = Binder.clearCallingIdentity(); 19016 try { 19017 final DeviceStorageMonitorInternal 19018 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19019 if (dsm != null) { 19020 return dsm.isMemoryLow(); 19021 } else { 19022 return false; 19023 } 19024 } finally { 19025 Binder.restoreCallingIdentity(token); 19026 } 19027 } 19028 19029 @Override 19030 public IPackageInstaller getPackageInstaller() { 19031 return mInstallerService; 19032 } 19033 19034 private boolean userNeedsBadging(int userId) { 19035 int index = mUserNeedsBadging.indexOfKey(userId); 19036 if (index < 0) { 19037 final UserInfo userInfo; 19038 final long token = Binder.clearCallingIdentity(); 19039 try { 19040 userInfo = sUserManager.getUserInfo(userId); 19041 } finally { 19042 Binder.restoreCallingIdentity(token); 19043 } 19044 final boolean b; 19045 if (userInfo != null && userInfo.isManagedProfile()) { 19046 b = true; 19047 } else { 19048 b = false; 19049 } 19050 mUserNeedsBadging.put(userId, b); 19051 return b; 19052 } 19053 return mUserNeedsBadging.valueAt(index); 19054 } 19055 19056 @Override 19057 public KeySet getKeySetByAlias(String packageName, String alias) { 19058 if (packageName == null || alias == null) { 19059 return null; 19060 } 19061 synchronized(mPackages) { 19062 final PackageParser.Package pkg = mPackages.get(packageName); 19063 if (pkg == null) { 19064 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19065 throw new IllegalArgumentException("Unknown package: " + packageName); 19066 } 19067 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19068 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19069 } 19070 } 19071 19072 @Override 19073 public KeySet getSigningKeySet(String packageName) { 19074 if (packageName == null) { 19075 return null; 19076 } 19077 synchronized(mPackages) { 19078 final PackageParser.Package pkg = mPackages.get(packageName); 19079 if (pkg == null) { 19080 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19081 throw new IllegalArgumentException("Unknown package: " + packageName); 19082 } 19083 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19084 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19085 throw new SecurityException("May not access signing KeySet of other apps."); 19086 } 19087 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19088 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19089 } 19090 } 19091 19092 @Override 19093 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19094 if (packageName == null || ks == null) { 19095 return false; 19096 } 19097 synchronized(mPackages) { 19098 final PackageParser.Package pkg = mPackages.get(packageName); 19099 if (pkg == null) { 19100 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19101 throw new IllegalArgumentException("Unknown package: " + packageName); 19102 } 19103 IBinder ksh = ks.getToken(); 19104 if (ksh instanceof KeySetHandle) { 19105 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19106 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19107 } 19108 return false; 19109 } 19110 } 19111 19112 @Override 19113 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19114 if (packageName == null || ks == null) { 19115 return false; 19116 } 19117 synchronized(mPackages) { 19118 final PackageParser.Package pkg = mPackages.get(packageName); 19119 if (pkg == null) { 19120 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19121 throw new IllegalArgumentException("Unknown package: " + packageName); 19122 } 19123 IBinder ksh = ks.getToken(); 19124 if (ksh instanceof KeySetHandle) { 19125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19126 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19127 } 19128 return false; 19129 } 19130 } 19131 19132 private void deletePackageIfUnusedLPr(final String packageName) { 19133 PackageSetting ps = mSettings.mPackages.get(packageName); 19134 if (ps == null) { 19135 return; 19136 } 19137 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19138 // TODO Implement atomic delete if package is unused 19139 // It is currently possible that the package will be deleted even if it is installed 19140 // after this method returns. 19141 mHandler.post(new Runnable() { 19142 public void run() { 19143 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19144 } 19145 }); 19146 } 19147 } 19148 19149 /** 19150 * Check and throw if the given before/after packages would be considered a 19151 * downgrade. 19152 */ 19153 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19154 throws PackageManagerException { 19155 if (after.versionCode < before.mVersionCode) { 19156 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19157 "Update version code " + after.versionCode + " is older than current " 19158 + before.mVersionCode); 19159 } else if (after.versionCode == before.mVersionCode) { 19160 if (after.baseRevisionCode < before.baseRevisionCode) { 19161 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19162 "Update base revision code " + after.baseRevisionCode 19163 + " is older than current " + before.baseRevisionCode); 19164 } 19165 19166 if (!ArrayUtils.isEmpty(after.splitNames)) { 19167 for (int i = 0; i < after.splitNames.length; i++) { 19168 final String splitName = after.splitNames[i]; 19169 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19170 if (j != -1) { 19171 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19172 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19173 "Update split " + splitName + " revision code " 19174 + after.splitRevisionCodes[i] + " is older than current " 19175 + before.splitRevisionCodes[j]); 19176 } 19177 } 19178 } 19179 } 19180 } 19181 } 19182 19183 private static class MoveCallbacks extends Handler { 19184 private static final int MSG_CREATED = 1; 19185 private static final int MSG_STATUS_CHANGED = 2; 19186 19187 private final RemoteCallbackList<IPackageMoveObserver> 19188 mCallbacks = new RemoteCallbackList<>(); 19189 19190 private final SparseIntArray mLastStatus = new SparseIntArray(); 19191 19192 public MoveCallbacks(Looper looper) { 19193 super(looper); 19194 } 19195 19196 public void register(IPackageMoveObserver callback) { 19197 mCallbacks.register(callback); 19198 } 19199 19200 public void unregister(IPackageMoveObserver callback) { 19201 mCallbacks.unregister(callback); 19202 } 19203 19204 @Override 19205 public void handleMessage(Message msg) { 19206 final SomeArgs args = (SomeArgs) msg.obj; 19207 final int n = mCallbacks.beginBroadcast(); 19208 for (int i = 0; i < n; i++) { 19209 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19210 try { 19211 invokeCallback(callback, msg.what, args); 19212 } catch (RemoteException ignored) { 19213 } 19214 } 19215 mCallbacks.finishBroadcast(); 19216 args.recycle(); 19217 } 19218 19219 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19220 throws RemoteException { 19221 switch (what) { 19222 case MSG_CREATED: { 19223 callback.onCreated(args.argi1, (Bundle) args.arg2); 19224 break; 19225 } 19226 case MSG_STATUS_CHANGED: { 19227 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19228 break; 19229 } 19230 } 19231 } 19232 19233 private void notifyCreated(int moveId, Bundle extras) { 19234 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19235 19236 final SomeArgs args = SomeArgs.obtain(); 19237 args.argi1 = moveId; 19238 args.arg2 = extras; 19239 obtainMessage(MSG_CREATED, args).sendToTarget(); 19240 } 19241 19242 private void notifyStatusChanged(int moveId, int status) { 19243 notifyStatusChanged(moveId, status, -1); 19244 } 19245 19246 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19247 Slog.v(TAG, "Move " + moveId + " status " + status); 19248 19249 final SomeArgs args = SomeArgs.obtain(); 19250 args.argi1 = moveId; 19251 args.argi2 = status; 19252 args.arg3 = estMillis; 19253 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19254 19255 synchronized (mLastStatus) { 19256 mLastStatus.put(moveId, status); 19257 } 19258 } 19259 } 19260 19261 private final static class OnPermissionChangeListeners extends Handler { 19262 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19263 19264 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19265 new RemoteCallbackList<>(); 19266 19267 public OnPermissionChangeListeners(Looper looper) { 19268 super(looper); 19269 } 19270 19271 @Override 19272 public void handleMessage(Message msg) { 19273 switch (msg.what) { 19274 case MSG_ON_PERMISSIONS_CHANGED: { 19275 final int uid = msg.arg1; 19276 handleOnPermissionsChanged(uid); 19277 } break; 19278 } 19279 } 19280 19281 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19282 mPermissionListeners.register(listener); 19283 19284 } 19285 19286 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19287 mPermissionListeners.unregister(listener); 19288 } 19289 19290 public void onPermissionsChanged(int uid) { 19291 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19292 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19293 } 19294 } 19295 19296 private void handleOnPermissionsChanged(int uid) { 19297 final int count = mPermissionListeners.beginBroadcast(); 19298 try { 19299 for (int i = 0; i < count; i++) { 19300 IOnPermissionsChangeListener callback = mPermissionListeners 19301 .getBroadcastItem(i); 19302 try { 19303 callback.onPermissionsChanged(uid); 19304 } catch (RemoteException e) { 19305 Log.e(TAG, "Permission listener is dead", e); 19306 } 19307 } 19308 } finally { 19309 mPermissionListeners.finishBroadcast(); 19310 } 19311 } 19312 } 19313 19314 private class PackageManagerInternalImpl extends PackageManagerInternal { 19315 @Override 19316 public void setLocationPackagesProvider(PackagesProvider provider) { 19317 synchronized (mPackages) { 19318 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19319 } 19320 } 19321 19322 @Override 19323 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19324 synchronized (mPackages) { 19325 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19326 } 19327 } 19328 19329 @Override 19330 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19331 synchronized (mPackages) { 19332 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19333 } 19334 } 19335 19336 @Override 19337 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19338 synchronized (mPackages) { 19339 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19340 } 19341 } 19342 19343 @Override 19344 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19345 synchronized (mPackages) { 19346 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19347 } 19348 } 19349 19350 @Override 19351 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19352 synchronized (mPackages) { 19353 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19354 } 19355 } 19356 19357 @Override 19358 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19359 synchronized (mPackages) { 19360 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19361 packageName, userId); 19362 } 19363 } 19364 19365 @Override 19366 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19367 synchronized (mPackages) { 19368 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19369 packageName, userId); 19370 } 19371 } 19372 19373 @Override 19374 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19375 synchronized (mPackages) { 19376 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19377 packageName, userId); 19378 } 19379 } 19380 19381 @Override 19382 public void setKeepUninstalledPackages(final List<String> packageList) { 19383 Preconditions.checkNotNull(packageList); 19384 List<String> removedFromList = null; 19385 synchronized (mPackages) { 19386 if (mKeepUninstalledPackages != null) { 19387 final int packagesCount = mKeepUninstalledPackages.size(); 19388 for (int i = 0; i < packagesCount; i++) { 19389 String oldPackage = mKeepUninstalledPackages.get(i); 19390 if (packageList != null && packageList.contains(oldPackage)) { 19391 continue; 19392 } 19393 if (removedFromList == null) { 19394 removedFromList = new ArrayList<>(); 19395 } 19396 removedFromList.add(oldPackage); 19397 } 19398 } 19399 mKeepUninstalledPackages = new ArrayList<>(packageList); 19400 if (removedFromList != null) { 19401 final int removedCount = removedFromList.size(); 19402 for (int i = 0; i < removedCount; i++) { 19403 deletePackageIfUnusedLPr(removedFromList.get(i)); 19404 } 19405 } 19406 } 19407 } 19408 19409 @Override 19410 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19411 synchronized (mPackages) { 19412 // If we do not support permission review, done. 19413 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19414 return false; 19415 } 19416 19417 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19418 if (packageSetting == null) { 19419 return false; 19420 } 19421 19422 // Permission review applies only to apps not supporting the new permission model. 19423 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19424 return false; 19425 } 19426 19427 // Legacy apps have the permission and get user consent on launch. 19428 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19429 return permissionsState.isPermissionReviewRequired(userId); 19430 } 19431 } 19432 19433 @Override 19434 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19435 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19436 } 19437 19438 @Override 19439 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19440 int userId) { 19441 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19442 } 19443 } 19444 19445 @Override 19446 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19447 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19448 synchronized (mPackages) { 19449 final long identity = Binder.clearCallingIdentity(); 19450 try { 19451 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19452 packageNames, userId); 19453 } finally { 19454 Binder.restoreCallingIdentity(identity); 19455 } 19456 } 19457 } 19458 19459 private static void enforceSystemOrPhoneCaller(String tag) { 19460 int callingUid = Binder.getCallingUid(); 19461 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19462 throw new SecurityException( 19463 "Cannot call " + tag + " from UID " + callingUid); 19464 } 19465 } 19466 19467 boolean isHistoricalPackageUsageAvailable() { 19468 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19469 } 19470 19471 /** 19472 * Return a <b>copy</b> of the collection of packages known to the package manager. 19473 * @return A copy of the values of mPackages. 19474 */ 19475 Collection<PackageParser.Package> getPackages() { 19476 synchronized (mPackages) { 19477 return new ArrayList<>(mPackages.values()); 19478 } 19479 } 19480 19481 /** 19482 * Logs process start information (including base APK hash) to the security log. 19483 * @hide 19484 */ 19485 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19486 String apkFile, int pid) { 19487 if (!SecurityLog.isLoggingEnabled()) { 19488 return; 19489 } 19490 Bundle data = new Bundle(); 19491 data.putLong("startTimestamp", System.currentTimeMillis()); 19492 data.putString("processName", processName); 19493 data.putInt("uid", uid); 19494 data.putString("seinfo", seinfo); 19495 data.putString("apkFile", apkFile); 19496 data.putInt("pid", pid); 19497 Message msg = mProcessLoggingHandler.obtainMessage( 19498 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19499 msg.setData(data); 19500 mProcessLoggingHandler.sendMessage(msg); 19501 } 19502} 19503